Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the programming language of this snippet from VB to Java without modifying what it does.
Imports System.Math, System.Console, BI = System.Numerics.BigInteger Module Module1 Sub Main(ByVal args As String()) Dim i, j, k, d As BI : i = 2 j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j Dim n As Integer = -1, n0 As Integer = -1, st As DateTime = DateTime.Now If args.Length > 0 Then Integer.TryParse(args(0), n) If n > 0 Then n0 = n Else n = 1 Do Write(d) : i = (i - k * d) * 100 : k = 20 * j For d = 1 To 10 If (k + d) * d > i Then d -= 1 : Exit For Next j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1 Loop While n > 0 If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st) End Sub End Module
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0))); var k = j; var d = j; int n = 500; int n0 = n; do { System.out.print(d); i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED); k = TWENTY.multiply(j); for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) { if (k.add(d).multiply(d).compareTo(i) > 0) { d = d.subtract(BigInteger.ONE); break; } } j = j.multiply(BigInteger.TEN).add(d); k = k.add(d); if (n0 > 0) { n--; } } while (n > 0); System.out.println(); } }
Preserve the algorithm and functionality while converting the code from VB to Java.
Imports System.Math, System.Console, BI = System.Numerics.BigInteger Module Module1 Sub Main(ByVal args As String()) Dim i, j, k, d As BI : i = 2 j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j Dim n As Integer = -1, n0 As Integer = -1, st As DateTime = DateTime.Now If args.Length > 0 Then Integer.TryParse(args(0), n) If n > 0 Then n0 = n Else n = 1 Do Write(d) : i = (i - k * d) * 100 : k = 20 * j For d = 1 To 10 If (k + d) * d > i Then d -= 1 : Exit For Next j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1 Loop While n > 0 If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st) End Sub End Module
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0))); var k = j; var d = j; int n = 500; int n0 = n; do { System.out.print(d); i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED); k = TWENTY.multiply(j); for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) { if (k.add(d).multiply(d).compareTo(i) > 0) { d = d.subtract(BigInteger.ONE); break; } } j = j.multiply(BigInteger.TEN).add(d); k = k.add(d); if (n0 > 0) { n--; } } while (n > 0); System.out.println(); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
Imports System.Reflection Module Module1 Class TestClass Private privateField = 7 Public ReadOnly Property PublicNumber = 4 Private ReadOnly Property PrivateNumber = 2 End Class Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return From p In obj.GetType().GetProperties(flags) Where p.GetIndexParameters().Length = 0 Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)} End Function Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)}) End Function Sub Main() Dim t As New TestClass() Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance For Each prop In GetPropertyValues(t, flags) Console.WriteLine(prop) Next For Each field In GetFieldValues(t, flags) Console.WriteLine(field) Next End Sub End Module
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); System.out.println("All public fields (including inherited):"); for (Field f : clazz.getFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } System.out.println(); System.out.println("All declared fields (excluding inherited):"); for (Field f : clazz.getDeclaredFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } } }
Please provide an equivalent version of this VB code in Java.
Dim MText as QMemorystream MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" MText.WriteLine "are$delineated$by$a$single$ MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" MText.WriteLine "column$are$separated$by$at$least$one$space." MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$" MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column." DefStr TextLeft, TextRight, TextCenter DefStr MLine, LWord, Newline = chr$(13)+chr$(10) DefInt ColWidth(100), ColCount DefSng NrSpaces MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y)) next next MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) NrSpaces = ColWidth(y) - len(LWord) TextLeft = TextLeft + LWord + Space$(NrSpaces+1) TextRight = TextRight + Space$(NrSpaces+1) + LWord TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2)) next TextLeft = TextLeft + Newline TextRight = TextRight + Newline TextCenter = TextCenter + Newline next
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class ColumnAligner { private List<String[]> words = new ArrayList<>(); private int columns = 0; private List<Integer> columnWidths = new ArrayList<>(); public ColumnAligner(String s) { String[] lines = s.split("\\n"); for (String line : lines) { processInputLine(line); } } public ColumnAligner(List<String> lines) { for (String line : lines) { processInputLine(line); } } private void processInputLine(String line) { String[] lineWords = line.split("\\$"); words.add(lineWords); columns = Math.max(columns, lineWords.length); for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i >= columnWidths.size()) { columnWidths.add(word.length()); } else { columnWidths.set(i, Math.max(columnWidths.get(i), word.length())); } } } interface AlignFunction { String align(String s, int length); } public String alignLeft() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.rightPad(s, length); } }); } public String alignRight() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.leftPad(s, length); } }); } public String alignCenter() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.center(s, length); } }); } private String align(AlignFunction a) { StringBuilder result = new StringBuilder(); for (String[] lineWords : words) { for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i == 0) { result.append("|"); } result.append(a.align(word, columnWidths.get(i)) + "|"); } result.append("\n"); } return result.toString(); } public static void main(String args[]) throws IOException { if (args.length < 1) { System.out.println("Usage: ColumnAligner file [left|right|center]"); return; } String filePath = args[0]; String alignment = "left"; if (args.length >= 2) { alignment = args[1]; } ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8)); switch (alignment) { case "left": System.out.print(ca.alignLeft()); break; case "right": System.out.print(ca.alignRight()); break; case "center": System.out.print(ca.alignCenter()); break; default: System.err.println(String.format("Error! Unknown alignment: '%s'", alignment)); break; } } }
Preserve the algorithm and functionality while converting the code from VB to Java.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Change the programming language of this snippet from VB to Java without modifying what it does.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Preserve the algorithm and functionality while converting the code from VB to Java.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Change the following VB code into Java without altering its purpose.
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
Write the same code in Java as shown below in VB.
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
Generate a Java translation of this VB snippet without changing its computational steps.
Imports System.IO Imports System.Security.Cryptography Module Module1 Function ByteArrayToString(ba As Byte()) As String Return BitConverter.ToString(ba).Replace("-", "") End Function Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte() Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} Dim provider As New DESCryptoServiceProvider Dim transform = provider.CreateEncryptor(passwordBytes, iv) Dim mode = CryptoStreamMode.Write Dim memStream As New MemoryStream Dim cryptoStream As New CryptoStream(memStream, transform, mode) cryptoStream.Write(messageBytes, 0, messageBytes.Length) cryptoStream.FlushFinalBlock() Dim encryptedMessageBytes(memStream.Length - 1) As Byte memStream.Position = 0 memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length) Return encryptedMessageBytes End Function Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte() Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} Dim provider As New DESCryptoServiceProvider Dim transform = provider.CreateDecryptor(passwordBytes, iv) Dim mode = CryptoStreamMode.Write Dim memStream As New MemoryStream Dim cryptoStream As New CryptoStream(memStream, transform, mode) cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length) cryptoStream.FlushFinalBlock() Dim decryptedMessageBytes(memStream.Length - 1) As Byte memStream.Position = 0 memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length) Return decryptedMessageBytes End Function Sub Main() Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73} Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87} Dim encStr = Encrypt(plainBytes, keyBytes) Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr)) Dim decStr = Decrypt(encStr, keyBytes) Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr)) End Sub End Module
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class DataEncryptionStandard { private static byte[] toHexByteArray(String self) { byte[] bytes = new byte[self.length() / 2]; for (int i = 0; i < bytes.length; ++i) { bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16)); } return bytes; } private static void printHexBytes(byte[] self, String label) { System.out.printf("%s: ", label); for (byte b : self) { int bb = (b >= 0) ? ((int) b) : b + 256; String ts = Integer.toString(bb, 16); if (ts.length() < 2) { ts = "0" + ts; } System.out.print(ts); } System.out.println(); } public static void main(String[] args) throws Exception { String strKey = "0e329232ea6d0d73"; byte[] keyBytes = toHexByteArray(strKey); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); Cipher encCipher = Cipher.getInstance("DES"); encCipher.init(Cipher.ENCRYPT_MODE, key); String strPlain = "8787878787878787"; byte[] plainBytes = toHexByteArray(strPlain); byte[] encBytes = encCipher.doFinal(plainBytes); printHexBytes(encBytes, "Encoded"); Cipher decCipher = Cipher.getInstance("DES"); decCipher.init(Cipher.DECRYPT_MODE, key); byte[] decBytes = decCipher.doFinal(encBytes); printHexBytes(decBytes, "Decoded"); } }
Translate the given VB code snippet into Java without altering its behavior.
Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3) Dim l As Integer: l = Len(s) For i = start To l If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then For j = i + 1 To l + 1 If j > l Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For Else If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For End If End If Next j Exit For End If Next i Debug.Print s End Sub Public Sub main() commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5 commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "." commatize """-in Aus$+1411.8millions""" commatize "===US$0017440 millions=== (in 2000 dollars)" commatize "123.e8000 is pretty big." commatize "The land area of the earth is 57268900(29% of the surface) square miles." commatize "Ain commatize "James was never known as 0000000007" commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." commatize " $-140000±100 millions." commatize "6/9/1946 was a good year for some." End Sub
import java.io.File; import java.util.*; import java.util.regex.*; public class CommatizingNumbers { public static void main(String[] args) throws Exception { commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " "); commatize("The author has two Z$100000000000000 Zimbabwe notes (100 " + "trillion).", 0, 3, "."); try (Scanner sc = new Scanner(new File("input.txt"))) { while(sc.hasNext()) commatize(sc.nextLine()); } } static void commatize(String s) { commatize(s, 0, 3, ","); } static void commatize(String s, int start, int step, String ins) { if (start < 0 || start > s.length() || step < 1 || step > s.length()) return; Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start)); StringBuffer result = new StringBuffer(s.substring(0, start)); if (m.find()) { StringBuilder sb = new StringBuilder(m.group(1)).reverse(); for (int i = step; i < sb.length(); i += step) sb.insert(i++, ins); m.appendReplacement(result, sb.reverse().toString()); } System.out.println(m.appendTail(result)); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
Imports System.Numerics Imports System.Text Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long) Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long)) Module Module1 Function CumulativeFreq(freq As Freq) As Freq Dim total As Long = 0 Dim cf As New Freq For i = 0 To 255 Dim c = Chr(i) If freq.ContainsKey(c) Then Dim v = freq(c) cf(c) = total total += v End If Next Return cf End Function Function ArithmeticCoding(str As String, radix As Long) As Triple Dim freq As New Freq For Each c In str If freq.ContainsKey(c) Then freq(c) += 1 Else freq(c) = 1 End If Next Dim cf = CumulativeFreq(freq) Dim base As BigInteger = str.Length Dim lower As BigInteger = 0 Dim pf As BigInteger = 1 For Each c In str Dim x = cf(c) lower = lower * base + x * pf pf = pf * freq(c) Next Dim upper = lower + pf Dim powr = 0 Dim bigRadix As BigInteger = radix While True pf = pf / bigRadix If pf = 0 Then Exit While End If powr = powr + 1 End While Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)) Return New Triple(diff, powr, freq) End Function Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String Dim powr As BigInteger = radix Dim enc = num * BigInteger.Pow(powr, pwr) Dim base = freq.Values.Sum() Dim cf = CumulativeFreq(freq) Dim dict As New Dictionary(Of Long, Char) For Each key In cf.Keys Dim value = cf(key) dict(value) = key Next Dim lchar As Long = -1 For i As Long = 0 To base - 1 If dict.ContainsKey(i) Then lchar = AscW(dict(i)) Else dict(i) = ChrW(lchar) End If Next Dim decoded As New StringBuilder Dim bigBase As BigInteger = base For i As Long = base - 1 To 0 Step -1 Dim pow = BigInteger.Pow(bigBase, i) Dim div = enc / pow Dim c = dict(div) Dim fv = freq(c) Dim cv = cf(c) Dim diff = enc - pow * cv enc = diff / fv decoded.Append(c) Next Return decoded.ToString() End Function Sub Main() Dim radix As Long = 10 Dim strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"} For Each St In strings Dim encoded = ArithmeticCoding(St, radix) Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3) Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", St, encoded.Item1, radix, encoded.Item2) If St <> dec Then Throw New Exception(vbTab + "However that is incorrect!") End If Next End Sub End Module
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ArithmeticCoding { private static class Triple<A, B, C> { A a; B b; C c; Triple(A a, B b, C c) { this.a = a; this.b = b; this.c = c; } } private static class Freq extends HashMap<Character, Long> { } private static Freq cumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; ++i) { char c = (char) i; Long v = freq.get(c); if (v != null) { cf.put(c, total); total += v; } } return cf; } private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) { char[] chars = str.toCharArray(); Freq freq = new Freq(); for (char c : chars) { if (!freq.containsKey(c)) freq.put(c, 1L); else freq.put(c, freq.get(c) + 1); } Freq cf = cumulativeFreq(freq); BigInteger base = BigInteger.valueOf(chars.length); BigInteger lower = BigInteger.ZERO; BigInteger pf = BigInteger.ONE; for (char c : chars) { BigInteger x = BigInteger.valueOf(cf.get(c)); lower = lower.multiply(base).add(x.multiply(pf)); pf = pf.multiply(BigInteger.valueOf(freq.get(c))); } BigInteger upper = lower.add(pf); int powr = 0; BigInteger bigRadix = BigInteger.valueOf(radix); while (true) { pf = pf.divide(bigRadix); if (pf.equals(BigInteger.ZERO)) break; powr++; } BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr)); return new Triple<>(diff, powr, freq); } private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = BigInteger.valueOf(radix); BigInteger enc = num.multiply(powr.pow(pwr)); long base = 0; for (Long v : freq.values()) base += v; Freq cf = cumulativeFreq(freq); Map<Long, Character> dict = new HashMap<>(); for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey()); long lchar = -1; for (long i = 0; i < base; ++i) { Character v = dict.get(i); if (v != null) { lchar = v; } else if (lchar != -1) { dict.put(i, (char) lchar); } } StringBuilder decoded = new StringBuilder((int) base); BigInteger bigBase = BigInteger.valueOf(base); for (long i = base - 1; i >= 0; --i) { BigInteger pow = bigBase.pow((int) i); BigInteger div = enc.divide(pow); Character c = dict.get(div.longValue()); BigInteger fv = BigInteger.valueOf(freq.get(c)); BigInteger cv = BigInteger.valueOf(cf.get(c)); BigInteger diff = enc.subtract(pow.multiply(cv)); enc = diff.divide(fv); decoded.append(c); } return decoded.toString(); } public static void main(String[] args) { long radix = 10; String[] strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"}; String fmt = "%-25s=> %19s * %d^%s\n"; for (String str : strings) { Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix); String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c); System.out.printf(fmt, str, encoded.a, radix, encoded.b); if (!Objects.equals(str, dec)) throw new RuntimeException("\tHowever that is incorrect!"); } } }
Maintain the same structure and functionality when rewriting this code in Java.
Module Module1 Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer) Dim size = g.Count Dim vis(size - 1) As Boolean Dim l(size - 1) As Integer Dim x = size Dim t As New List(Of List(Of Integer)) For i = 1 To size t.Add(New List(Of Integer)) Next Dim visit As Action(Of Integer) = Sub(u As Integer) If Not vis(u) Then vis(u) = True For Each v In g(u) visit(v) t(v).Add(u) Next x -= 1 l(x) = u End If End Sub For i = 1 To size visit(i - 1) Next Dim c(size - 1) As Integer Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer) If vis(u) Then vis(u) = False c(u) = root For Each v In t(u) assign(v, root) Next End If End Sub For Each u In l assign(u, u) Next Return c.ToList End Function Sub Main() Dim g = New List(Of List(Of Integer)) From { New List(Of Integer) From {1}, New List(Of Integer) From {2}, New List(Of Integer) From {0}, New List(Of Integer) From {1, 2, 4}, New List(Of Integer) From {3, 5}, New List(Of Integer) From {2, 6}, New List(Of Integer) From {5}, New List(Of Integer) From {4, 6, 7} } Dim output = Kosaraju(g) Console.WriteLine("[{0}]", String.Join(", ", output)) End Sub End Module
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; public class Kosaraju { static class Recursive<I> { I func; } private static List<Integer> kosaraju(List<List<Integer>> g) { int size = g.size(); boolean[] vis = new boolean[size]; int[] l = new int[size]; AtomicInteger x = new AtomicInteger(size); List<List<Integer>> t = new ArrayList<>(); for (int i = 0; i < size; ++i) { t.add(new ArrayList<>()); } Recursive<IntConsumer> visit = new Recursive<>(); visit.func = (int u) -> { if (!vis[u]) { vis[u] = true; for (Integer v : g.get(u)) { visit.func.accept(v); t.get(v).add(u); } int xval = x.decrementAndGet(); l[xval] = u; } }; for (int i = 0; i < size; ++i) { visit.func.accept(i); } int[] c = new int[size]; Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>(); assign.func = (Integer u, Integer root) -> { if (vis[u]) { vis[u] = false; c[u] = root; for (Integer v : t.get(u)) { assign.func.accept(v, root); } } }; for (int u : l) { assign.func.accept(u, u); } return Arrays.stream(c).boxed().collect(Collectors.toList()); } public static void main(String[] args) { List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < 8; ++i) { g.add(new ArrayList<>()); } g.get(0).add(1); g.get(1).add(2); g.get(2).add(0); g.get(3).add(1); g.get(3).add(2); g.get(3).add(4); g.get(4).add(3); g.get(4).add(5); g.get(5).add(2); g.get(5).add(6); g.get(6).add(5); g.get(7).add(4); g.get(7).add(6); g.get(7).add(7); List<Integer> output = kosaraju(g); System.out.println(output); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
Module Module1 Dim symbols As Char() = "XYPFTVNLUZWI█".ToCharArray(), nRows As Integer = 8, nCols As Integer = 8, target As Integer = 12, blank As Integer = 12, grid As Integer()() = New Integer(nRows - 1)() {}, placed As Boolean() = New Boolean(target - 1) {}, pens As List(Of List(Of Integer())), rand As Random, seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586} Sub Main() Unpack(seeds) : rand = New Random() : ShuffleShapes(2) For r As Integer = 0 To nRows - 1 grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next For i As Integer = 0 To 3 Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols) Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank Next If Solve(0, 0) Then PrintResult() Else Console.WriteLine("no solution for this configuration:") : PrintResult() End If If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey() End Sub Sub ShuffleShapes(count As Integer) For i As Integer = 0 To count : For j = 0 To pens.Count - 1 Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch Next : Next End Sub Sub PrintResult() For Each r As Integer() In grid : For Each i As Integer In r Console.Write("{0} ", If(i < 0, ".", symbols(i))) Next : Console.WriteLine() : Next End Sub Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean If numPlaced = target Then Return True Dim row As Integer = pos \ nCols, col As Integer = pos Mod nCols If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced) For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then For Each orientation As Integer() In pens(i) If Not TPO(orientation, row, col, i) Then Continue For placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True RmvO(orientation, row, col) : placed(i) = False Next : End If : Next : Return False End Function Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer) grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2 grid(row + ori(i))(col + ori(i + 1)) = -1 : Next End Sub Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer, ByVal sIdx As Integer) As Boolean For i As Integer = 0 To ori.Length - 1 Step 2 Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i) If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse grid(y)(x) <> -1 Then Return False Next : grid(row)(col) = sIdx For i As Integer = 0 To ori.Length - 1 Step 2 grid(row + ori(i))(col + ori(i + 1)) = sIdx Next : Return True End Function Sub Unpack(sv As Integer()) pens = New List(Of List(Of Integer())) : For Each item In sv Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item), fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7 If i = 4 Then Mir(exi) Else Rot(exi) fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi)) Next : pens.Add(Gen) : Next End Sub Function Expand(i As Integer) As List(Of Integer) Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next End Function Function ToP(p As List(Of Integer)) As Integer() Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1) tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next Dim res As New List(Of Integer) : For Each item In tmp.Skip(1) Dim adj = If((item And 7) > 4, 8, 0) res.Add((adj + item) \ 8) : res.Add((item And 7) - adj) Next : Return res.ToArray() End Function Function TheSame(a As Integer(), b As Integer()) As Boolean For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False Next : Return True End Function Sub Rot(ByRef p As List(Of Integer)) For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next End Sub Sub Mir(ByRef p As List(Of Integer)) For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next End Sub End Module
package pentominotiling; import java.util.*; public class PentominoTiling { static final char[] symbols = "FILNPTUVWXYZ-".toCharArray(); static final Random rand = new Random(); static final int nRows = 8; static final int nCols = 8; static final int blank = 12; static int[][] grid = new int[nRows][nCols]; static boolean[] placed = new boolean[symbols.length - 1]; public static void main(String[] args) { shuffleShapes(); for (int r = 0; r < nRows; r++) Arrays.fill(grid[r], -1); for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.nextInt(nRows); randCol = rand.nextInt(nCols); } while (grid[randRow][randCol] == blank); grid[randRow][randCol] = blank; } if (solve(0, 0)) { printResult(); } else { System.out.println("no solution"); } } static void shuffleShapes() { int n = shapes.length; while (n > 1) { int r = rand.nextInt(n--); int[][] tmp = shapes[r]; shapes[r] = shapes[n]; shapes[n] = tmp; char tmpSymbol = symbols[r]; symbols[r] = symbols[n]; symbols[n] = tmpSymbol; } } static void printResult() { for (int[] r : grid) { for (int i : r) System.out.printf("%c ", symbols[i]); System.out.println(); } } static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) { for (int i = 0; i < o.length; i += 2) { int x = c + o[i + 1]; int y = r + o[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; } grid[r][c] = shapeIndex; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex; return true; } static void removeOrientation(int[] o, int r, int c) { grid[r][c] = -1; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = -1; } static boolean solve(int pos, int numPlaced) { if (numPlaced == shapes.length) return true; int row = pos / nCols; int col = pos % nCols; if (grid[row][col] != -1) return solve(pos + 1, numPlaced); for (int i = 0; i < shapes.length; i++) { if (!placed[i]) { for (int[] orientation : shapes[i]) { if (!tryPlaceOrientation(orientation, row, col, i)) continue; placed[i] = true; if (solve(pos + 1, numPlaced + 1)) return true; removeOrientation(orientation, row, col); placed[i] = false; } } } return false; } static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}}; static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}; static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}}; static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}}; static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}}; static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}}; static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}}; static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}}; static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}}; static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}}; static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}}; static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}}; static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z}; }
Write the same algorithm in Java 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
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup"); if(!backFile.exists()) { backFile.createNewFile(); } Path back = Paths.get(filename + ".backup").toRealPath(); Files.move(file, back, StandardCopyOption.REPLACE_EXISTING); try(PrintWriter out = new PrintWriter(file.toFile())){ for(int i = 0; i < data.length; i++) { out.print(data[i]); if(i < data.length - 1) { out.println(); } } } } public static void main(String[] args) { try { saveWithBackup("original.txt", "fourth", "fifth", "sixth"); } catch (IOException e) { System.err.println(e); } } }
Produce a language-to-language conversion: from VB to Java, same semantics.
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
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup"); if(!backFile.exists()) { backFile.createNewFile(); } Path back = Paths.get(filename + ".backup").toRealPath(); Files.move(file, back, StandardCopyOption.REPLACE_EXISTING); try(PrintWriter out = new PrintWriter(file.toFile())){ for(int i = 0; i < data.length; i++) { out.print(data[i]); if(i < data.length - 1) { out.println(); } } } } public static void main(String[] args) { try { saveWithBackup("original.txt", "fourth", "fifth", "sixth"); } catch (IOException e) { System.err.println(e); } } }
Generate an equivalent Java version of this VB code.
Imports System.Numerics Public Class BigRat Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) nu = bRat.nu : de = bRat.de End Sub Sub New(n As BigInteger, d As BigInteger) If d = BigInteger.Zero Then _ Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d))) Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d) If bi > BigInteger.One Then n /= bi : d /= bi If d < BigInteger.Zero Then n = -n : d = -d nu = n : de = d End Sub Shared Operator -(x As BigRat) As BigRat Return New BigRat(-x.nu, x.de) End Operator Shared Operator +(x As BigRat, y As BigRat) Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de) End Operator Shared Operator -(x As BigRat, y As BigRat) As BigRat Return x + (-y) End Operator Shared Operator *(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.nu, x.de * y.de) End Operator Shared Operator /(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.de, x.de * y.nu) End Operator Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Dim dif As BigRat = New BigRat(nu, de) - obj If dif.nu < BigInteger.Zero Then Return -1 If dif.nu > BigInteger.Zero Then Return 1 Return 0 End Function Shared Operator =(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) = 0 End Operator Shared Operator <>(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) <> 0 End Operator Overrides Function ToString() As String If de = BigInteger.One Then Return nu.ToString Return String.Format("({0}/{1})", nu, de) End Function Shared Function Combine(a As BigRat, b As BigRat) As BigRat Return (a + b) / (BigRat.One - (a * b)) End Function End Class Public Structure Term Dim c As Integer, br As BigRat Sub New(cc As Integer, bigr As BigRat) c = cc : br = bigr End Sub End Structure Module Module1 Function Eval(c As Integer, x As BigRat) As BigRat If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x) Dim hc As Integer = c \ 2 Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x)) End Function Function Sum(terms As List(Of Term)) As BigRat If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br) Dim htc As Integer = terms.Count / 2 Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList)) End Function Function ParseLine(ByVal s As String) As List(Of Term) ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero) While t.Contains(" ") : t = t.Replace(" ", "") : End While p = t.IndexOf("pi/4=") : If p < 0 Then _ Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function t = t.Substring(p + 5) For Each item As String In t.Split(")") If item.Length > 5 Then If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item) ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function End If x.c = 1 : x.br = New BigRat(BigRat.One) p = item.IndexOf("/") : If p > 0 Then x.br.de = UInt64.Parse(item.Substring(p + 1)) item = item.Substring(0, p) p = item.IndexOf("(") : If p > 0 Then x.br.nu = UInt64.Parse(item.Substring(p + 1)) p = item.IndexOf("a") : If p > 0 Then Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c) If x.c = 0 Then x.c = 1 If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c End If ParseLine.Add(x) End If End If End If Next End Function Sub Main(ByVal args As String()) Dim nl As String = vbLf For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl & "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl & "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl & "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl & "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl & "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl & "PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl & "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl & "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl & "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl & "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl & "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl & "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl & "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl & "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl) Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item) Next End Sub End Module
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FILE_NAME = "MachinFormula.txt"; public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } } private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } } private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); } private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); } private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); } private static Fraction evaluateArctan(int coefficient, Fraction fraction) { if ( coefficient == 1 ) { return fraction; } else if ( coefficient < 0 ) { return evaluateArctan(-coefficient, fraction).negate(); } if ( coefficient % 2 == 0 ) { Fraction f = evaluateArctan(coefficient/2, fraction); return arctanFormula(f, f); } Fraction a = evaluateArctan(coefficient/2, fraction); Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); return arctanFormula(a, b); } private static Fraction arctanFormula(Fraction f1, Fraction f2) { return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); } private static class Fraction { public static final Fraction ONE = new Fraction("1", "1"); private BigInteger numerator; private BigInteger denominator; public Fraction(String num, String den) { numerator = new BigInteger(num); denominator = new BigInteger(den); } public Fraction(BigInteger num, BigInteger den) { numerator = num; denominator = den; } public Fraction negate() { return new Fraction(numerator.negate(), denominator); } public Fraction add(Fraction f) { BigInteger gcd = denominator.gcd(f.denominator); BigInteger first = numerator.multiply(f.denominator.divide(gcd)); BigInteger second = f.numerator.multiply(denominator.divide(gcd)); return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); } public Fraction subtract(Fraction f) { return add(f.negate()); } public Fraction multiply(Fraction f) { BigInteger num = numerator.multiply(f.numerator); BigInteger den = denominator.multiply(f.denominator); BigInteger gcd = num.gcd(den); return new Fraction(num.divide(gcd), den.divide(gcd)); } public Fraction divide(Fraction f) { return multiply(new Fraction(f.denominator, f.numerator)); } @Override public String toString() { if ( denominator.compareTo(BigInteger.ONE) == 0 ) { return numerator.toString(); } return numerator + " / " + denominator; } } private static class Term { private int coefficient; private Fraction fraction; public Term(int c, Fraction f) { coefficient = c; fraction = f; } } }
Translate the given VB code snippet into Java without altering its behavior.
Imports System.Numerics Public Class BigRat Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) nu = bRat.nu : de = bRat.de End Sub Sub New(n As BigInteger, d As BigInteger) If d = BigInteger.Zero Then _ Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d))) Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d) If bi > BigInteger.One Then n /= bi : d /= bi If d < BigInteger.Zero Then n = -n : d = -d nu = n : de = d End Sub Shared Operator -(x As BigRat) As BigRat Return New BigRat(-x.nu, x.de) End Operator Shared Operator +(x As BigRat, y As BigRat) Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de) End Operator Shared Operator -(x As BigRat, y As BigRat) As BigRat Return x + (-y) End Operator Shared Operator *(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.nu, x.de * y.de) End Operator Shared Operator /(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.de, x.de * y.nu) End Operator Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Dim dif As BigRat = New BigRat(nu, de) - obj If dif.nu < BigInteger.Zero Then Return -1 If dif.nu > BigInteger.Zero Then Return 1 Return 0 End Function Shared Operator =(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) = 0 End Operator Shared Operator <>(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) <> 0 End Operator Overrides Function ToString() As String If de = BigInteger.One Then Return nu.ToString Return String.Format("({0}/{1})", nu, de) End Function Shared Function Combine(a As BigRat, b As BigRat) As BigRat Return (a + b) / (BigRat.One - (a * b)) End Function End Class Public Structure Term Dim c As Integer, br As BigRat Sub New(cc As Integer, bigr As BigRat) c = cc : br = bigr End Sub End Structure Module Module1 Function Eval(c As Integer, x As BigRat) As BigRat If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x) Dim hc As Integer = c \ 2 Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x)) End Function Function Sum(terms As List(Of Term)) As BigRat If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br) Dim htc As Integer = terms.Count / 2 Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList)) End Function Function ParseLine(ByVal s As String) As List(Of Term) ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero) While t.Contains(" ") : t = t.Replace(" ", "") : End While p = t.IndexOf("pi/4=") : If p < 0 Then _ Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function t = t.Substring(p + 5) For Each item As String In t.Split(")") If item.Length > 5 Then If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item) ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function End If x.c = 1 : x.br = New BigRat(BigRat.One) p = item.IndexOf("/") : If p > 0 Then x.br.de = UInt64.Parse(item.Substring(p + 1)) item = item.Substring(0, p) p = item.IndexOf("(") : If p > 0 Then x.br.nu = UInt64.Parse(item.Substring(p + 1)) p = item.IndexOf("a") : If p > 0 Then Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c) If x.c = 0 Then x.c = 1 If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c End If ParseLine.Add(x) End If End If End If Next End Function Sub Main(ByVal args As String()) Dim nl As String = vbLf For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl & "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl & "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl & "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl & "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl & "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl & "PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl & "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl & "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl & "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl & "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl & "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl & "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl & "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl & "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl) Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item) Next End Sub End Module
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FILE_NAME = "MachinFormula.txt"; public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } } private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } } private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); } private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); } private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); } private static Fraction evaluateArctan(int coefficient, Fraction fraction) { if ( coefficient == 1 ) { return fraction; } else if ( coefficient < 0 ) { return evaluateArctan(-coefficient, fraction).negate(); } if ( coefficient % 2 == 0 ) { Fraction f = evaluateArctan(coefficient/2, fraction); return arctanFormula(f, f); } Fraction a = evaluateArctan(coefficient/2, fraction); Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); return arctanFormula(a, b); } private static Fraction arctanFormula(Fraction f1, Fraction f2) { return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); } private static class Fraction { public static final Fraction ONE = new Fraction("1", "1"); private BigInteger numerator; private BigInteger denominator; public Fraction(String num, String den) { numerator = new BigInteger(num); denominator = new BigInteger(den); } public Fraction(BigInteger num, BigInteger den) { numerator = num; denominator = den; } public Fraction negate() { return new Fraction(numerator.negate(), denominator); } public Fraction add(Fraction f) { BigInteger gcd = denominator.gcd(f.denominator); BigInteger first = numerator.multiply(f.denominator.divide(gcd)); BigInteger second = f.numerator.multiply(denominator.divide(gcd)); return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); } public Fraction subtract(Fraction f) { return add(f.negate()); } public Fraction multiply(Fraction f) { BigInteger num = numerator.multiply(f.numerator); BigInteger den = denominator.multiply(f.denominator); BigInteger gcd = num.gcd(den); return new Fraction(num.divide(gcd), den.divide(gcd)); } public Fraction divide(Fraction f) { return multiply(new Fraction(f.denominator, f.numerator)); } @Override public String toString() { if ( denominator.compareTo(BigInteger.ONE) == 0 ) { return numerator.toString(); } return numerator + " / " + denominator; } } private static class Term { private int coefficient; private Fraction fraction; public Term(int c, Fraction f) { coefficient = c; fraction = f; } } }
Change the programming language of this snippet from VB to Java without modifying what it does.
Imports System, Microsoft.VisualBasic.DateAndTime Public Module Module1 Const n As Integer = 5 Dim Board As String Dim Starting As Integer = 1 Dim Target As Integer = 13 Dim Moves As Integer() Dim bi() As Integer Dim ib() As Integer Dim nl As Char = Convert.ToChar(10) Public Function Dou(s As String) As String Dou = "" : Dim b As Boolean = True For Each ch As Char In s If b Then b = ch <> " " If b Then Dou &= ch & " " Else Dou = " " & Dou Next : Dou = Dou.TrimEnd() End Function Public Function Fmt(s As String) As String If s.Length < Board.Length Then Return s Fmt = "" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) & If(i = n, s.Substring(Board.Length), "") & nl Next End Function Public Function Triangle(n As Integer) As Integer Return (n * (n + 1)) / 2 End Function Public Function Init(s As String, pos As Integer) As String Init = s : Mid(Init, pos, 1) = "0" End Function Public Sub InitIndex() ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0 For i As Integer = 0 To ib.Length - 1 If i = 0 Then ib(i) = 0 : bi(j) = 0 : j += 1 Else If Board(i - 1) = "1" Then ib(i) = j : bi(j) = i : j += 1 End If Next End Sub Public Function solve(brd As String, pegsLeft As Integer) As String If pegsLeft = 1 Then If Target = 0 Then Return "Completed" If brd(bi(Target) - 1) = "1" Then Return "Completed" Else Return "fail" End If For i = 1 To Board.Length If brd(i - 1) = "1" Then For Each mj In Moves Dim over As Integer = i + mj Dim land As Integer = i + 2 * mj If land >= 1 AndAlso land <= brd.Length _ AndAlso brd(land - 1) = "0" _ AndAlso brd(over - 1) = "1" Then setPegs(brd, "001", i, over, land) Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1) If Res.Length <> 4 Then _ Return brd & info(i, over, land) & nl & Res setPegs(brd, "110", i, over, land) End If Next End If Next Return "fail" End Function Function info(frm As Integer, over As Integer, dest As Integer) As String Return " Peg from " & ib(frm).ToString() & " goes to " & ib(dest).ToString() & ", removing peg at " & ib(over).ToString() End Function Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer) Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2) End Sub Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer) x = Math.Max(Math.Min(x, hi), lo) End Sub Public Sub Main() Dim t As Integer = Triangle(n) LimitIt(Starting, 1, t) LimitIt(Target, 0, t) Dim stime As Date = Now() Moves = {-n - 1, -n, -1, 1, n, n + 1} Board = New String("1", n * n) For i As Integer = 0 To n - 2 Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(" ", n - 1 - i) Next InitIndex() Dim B As String = Init(Board, bi(Starting)) Console.WriteLine(Fmt(B & " Starting with peg removed from " & Starting.ToString())) Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl) Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & " ms." If res(0).Length = 4 Then If Target = 0 Then Console.WriteLine("Unable to find a solution with last peg left anywhere.") Else Console.WriteLine("Unable to find a solution with last peg left at " & Target.ToString() & ".") End If Console.WriteLine("Computation time: " & ts) Else For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next Console.WriteLine("Computation time to first found solution: " & ts) End If If Diagnostics.Debugger.IsAttached Then Console.ReadLine() End Sub End Module
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; public class IQPuzzle { public static void main(String[] args) { System.out.printf(" "); for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) { System.out.printf("  %,6d", start); } System.out.printf("%n"); for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) { System.out.printf("%2d", start); Map<Integer,Integer> solutions = solve(start); for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) { System.out.printf("  %,6d", solutions.containsKey(end) ? solutions.get(end) : 0); } System.out.printf("%n"); } int moveNum = 0; System.out.printf("%nOne Solution:%n"); for ( Move m : oneSolution ) { moveNum++; System.out.printf("Move %d = %s%n", moveNum, m); } } private static List<Move> oneSolution = null; private static Map<Integer, Integer> solve(int emptyPeg) { Puzzle puzzle = new Puzzle(emptyPeg); Map<Integer,Integer> solutions = new HashMap<>(); Stack<Puzzle> stack = new Stack<Puzzle>(); stack.push(puzzle); while ( ! stack.isEmpty() ) { Puzzle p = stack.pop(); if ( p.solved() ) { solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2); if ( oneSolution == null ) { oneSolution = p.moves; } continue; } for ( Move move : p.getValidMoves() ) { Puzzle pMove = p.move(move); stack.add(pMove); } } return solutions; } private static class Puzzle { public static int MAX_PEGS = 16; private boolean[] pegs = new boolean[MAX_PEGS]; private List<Move> moves; public Puzzle(int emptyPeg) { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { pegs[i] = true; } pegs[emptyPeg] = false; moves = new ArrayList<>(); } public Puzzle() { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { pegs[i] = true; } moves = new ArrayList<>(); } private static Map<Integer,List<Move>> validMoves = new HashMap<>(); static { validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6))); validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9))); validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10))); validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11))); validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14))); validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15))); validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9))); validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10))); validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7))); validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8))); validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13))); validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14))); validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15))); validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5))); validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6))); } public List<Move> getValidMoves() { List<Move> moves = new ArrayList<Move>(); for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { for ( Move testMove : validMoves.get(i) ) { if ( pegs[testMove.jump] && ! pegs[testMove.end] ) { moves.add(testMove); } } } } return moves; } public boolean solved() { boolean foundFirstPeg = false; for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { if ( foundFirstPeg ) { return false; } foundFirstPeg = true; } } return true; } public Puzzle move(Move move) { Puzzle p = new Puzzle(); if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) { throw new RuntimeException("Invalid move."); } for ( int i = 1 ; i < MAX_PEGS ; i++ ) { p.pegs[i] = pegs[i]; } p.pegs[move.start] = false; p.pegs[move.jump] = false; p.pegs[move.end] = true; for ( Move m : moves ) { p.moves.add(new Move(m.start, m.jump, m.end)); } p.moves.add(new Move(move.start, move.jump, move.end)); return p; } public int getLastPeg() { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { return i; } } throw new RuntimeException("ERROR: Illegal position."); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for ( int i = 1 ; i < MAX_PEGS ; i++ ) { sb.append(pegs[i] ? 1 : 0); sb.append(","); } sb.setLength(sb.length()-1); sb.append("]"); return sb.toString(); } } private static class Move { int start; int jump; int end; public Move(int s, int j, int e) { start = s; jump = j; end = e; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("s=" + start); sb.append(", j=" + jump); sb.append(", e=" + end); sb.append("}"); return sb.toString(); } } }
Maintain the same structure and functionality when rewriting this code in Java.
Public s As String Public t As Integer Function s1() s1 = Len(s) = 12 End Function Function s2() t = 0 For i = 7 To 12 t = t - (Mid(s, i, 1) = "1") Next i s2 = t = 3 End Function Function s3() t = 0 For i = 2 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s3 = t = 2 End Function Function s4() s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1")) End Function Function s5() s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0" End Function Function s6() t = 0 For i = 1 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s6 = t = 4 End Function Function s7() s7 = Mid(s, 2, 1) <> Mid(s, 3, 1) End Function Function s8() s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1") End Function Function s9() t = 0 For i = 1 To 6 t = t - (Mid(s, i, 1) = "1") Next i s9 = t = 3 End Function Function s10() s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1" End Function Function s11() t = 0 For i = 7 To 9 t = t - (Mid(s, i, 1) = "1") Next i s11 = t = 1 End Function Function s12() t = 0 For i = 1 To 11 t = t - (Mid(s, i, 1) = "1") Next i s12 = t = 4 End Function Public Sub twelve_statements() For i = 0 To 2 ^ 12 - 1 s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _ & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7) For b = 1 To 12 Select Case b Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For End Select If b = 12 Then Debug.Print s Next Next End Sub
public class LogicPuzzle { boolean S[] = new boolean[13]; int Count = 0; public boolean check2 () { int count = 0; for (int k = 7; k <= 12; k++) if (S[k]) count++; return S[2] == (count == 3); } public boolean check3 () { int count = 0; for (int k = 2; k <= 12; k += 2) if (S[k]) count++; return S[3] == (count == 2); } public boolean check4 () { return S[4] == ( !S[5] || S[6] && S[7]); } public boolean check5 () { return S[5] == ( !S[2] && !S[3] && !S[4]); } public boolean check6 () { int count = 0; for (int k = 1; k <= 11; k += 2) if (S[k]) count++; return S[6] == (count == 4); } public boolean check7 () { return S[7] == ((S[2] || S[3]) && !(S[2] && S[3])); } public boolean check8 () { return S[8] == ( !S[7] || S[5] && S[6]); } public boolean check9 () { int count = 0; for (int k = 1; k <= 6; k++) if (S[k]) count++; return S[9] == (count == 3); } public boolean check10 () { return S[10] == (S[11] && S[12]); } public boolean check11 () { int count = 0; for (int k = 7; k <= 9; k++) if (S[k]) count++; return S[11] == (count == 1); } public boolean check12 () { int count = 0; for (int k = 1; k <= 11; k++) if (S[k]) count++; return S[12] == (count == 4); } public void check () { if (check2() && check3() && check4() && check5() && check6() && check7() && check8() && check9() && check10() && check11() && check12()) { for (int k = 1; k <= 12; k++) if (S[k]) System.out.print(k + " "); System.out.println(); Count++; } } public void recurseAll (int k) { if (k == 13) check(); else { S[k] = false; recurseAll(k + 1); S[k] = true; recurseAll(k + 1); } } public static void main (String args[]) { LogicPuzzle P = new LogicPuzzle(); P.S[1] = true; P.recurseAll(2); System.out.println(); System.out.println(P.Count + " Solutions found."); } }
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import ( "fmt" ) const numbers = 3 func main() { max := 20 words := map[int]string{ 3: "Fizz", 5: "Buzz", 7: "Baxx", } keys := []int{3, 5, 7} divisible := false for i := 1; i <= max; i++ { for _, n := range keys { if i % n == 0 { fmt.Print(words[n]) divisible = true } } if !divisible { fmt.Print(i) } fmt.Println() divisible = false } }
#include <stdio.h> #include <stdlib.h> struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf("%s", info[it].text); found_word = 1; } } if (0 == found_word) printf("%d", i); printf("\n"); } } int main(void) { struct replace_info info[3] = { {5, "Buzz"}, {7, "Baxx"}, {3, "Fizz"} }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
Port the provided Go code into C while preserving the original functionality.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Maintain the same structure and functionality when rewriting this code in C.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Keep all operations the same but rewrite the snippet in C.
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Translate the given Go code snippet into C without altering its behavior.
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Write a version of this Go function in C with identical behavior.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Generate a C translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import ( "log" "math/rand" "sync" "time" ) func worker(part string) { log.Println(part, "worker begins part") time.Sleep(time.Duration(rand.Int63n(1e6))) log.Println(part, "worker completes part") wg.Done() } var ( partList = []string{"A", "B", "C", "D"} nAssemblies = 3 wg sync.WaitGroup ) func main() { rand.Seed(time.Now().UnixNano()) for c := 1; c <= nAssemblies; c++ { log.Println("begin assembly cycle", c) wg.Add(len(partList)) for _, part := range partList { go worker(part) } wg.Wait() log.Println("assemble. cycle", c, "complete") } }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> int main() { int jobs = 41, tid; omp_set_num_threads(5); #pragma omp parallel shared(jobs) private(tid) { tid = omp_get_thread_num(); while (jobs > 0) { #pragma omp barrier if (!jobs) break; printf("%d: taking job %d\n", tid, jobs--); usleep(100000 + rand() / (double) RAND_MAX * 3000000); printf("%d: done job\n", tid); } printf("[%d] leaving\n", tid); #pragma omp barrier } return 0; }
Translate this program into C but keep the logic exactly as in Go.
package main import ( "fmt" "encoding/binary" ) func main() { buf := make([]byte, binary.MaxVarintLen64) for _, x := range []int64{0x200000, 0x1fffff} { v := buf[:binary.PutVarint(buf, x)] fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v) x, _ = binary.Varint(v) fmt.Println(x, "decoded") } }
#include <stdio.h> #include <stdint.h> void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; } uint64_t from_seq(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++ & 128); return r; } int main() { uint8_t s[10]; uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; int i, j; for (j = 0; j < sizeof(x)/8; j++) { to_seq(x[j], s); printf("seq from %llx: [ ", x[j]); i = 0; do { printf("%02x ", s[i]); } while ((s[i++] & 128)); printf("] back: %llx\n", from_seq(s)); } return 0; }
Convert this Go snippet to C and keep its semantics consistent.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) name := "" for name == "" { fmt.Print("Enter output file name (without extension) : ") scanner.Scan() name = scanner.Text() check(scanner.Err()) } name += ".wav" rate := 0 for rate < 2000 || rate > 192000 { fmt.Print("Enter sampling rate in Hz (2000 to 192000) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) rate, _ = strconv.Atoi(input) } rateS := strconv.Itoa(rate) dur := 0.0 for dur < 5 || dur > 30 { fmt.Print("Enter duration in seconds (5 to 30)  : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) dur, _ = strconv.ParseFloat(input, 64) } durS := strconv.FormatFloat(dur, 'f', -1, 64) fmt.Println("OK, start speaking now...") args := []string{"-r", rateS, "-f", "S16_LE", "-d", durS, name} cmd := exec.Command("arecord", args...) err := cmd.Run() check(err) fmt.Printf("'%s' created on disk and will now be played back...\n", name) cmd = exec.Command("aplay", name) err = cmd.Run() check(err) fmt.Println("Play-back completed.") }
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> void * record(size_t bytes) { int fd; if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0; void *a = malloc(bytes); read(fd, a, bytes); close(fd); return a; } int play(void *buf, size_t len) { int fd; if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0; write(fd, buf, len); close(fd); return 1; } int main() { void *p = record(65536); play(p, 65536); return 0; }
Port the provided Go code into C while preserving the original functionality.
package main import ( "crypto/sha256" "fmt" "io" "log" "os" ) func main() { const blockSize = 1024 f, err := os.Open("title.png") if err != nil { log.Fatal(err) } defer f.Close() var hashes [][]byte buffer := make([]byte, blockSize) h := sha256.New() for { bytesRead, err := f.Read(buffer) if err != nil { if err != io.EOF { log.Fatal(err) } break } h.Reset() h.Write(buffer[:bytesRead]) hashes = append(hashes, h.Sum(nil)) } buffer = make([]byte, 64) for len(hashes) > 1 { var hashes2 [][]byte for i := 0; i < len(hashes); i += 2 { if i < len(hashes)-1 { copy(buffer, hashes[i]) copy(buffer[32:], hashes[i+1]) h.Reset() h.Write(buffer) hashes2 = append(hashes2, h.Sum(nil)) } else { hashes2 = append(hashes2, hashes[i]) } } hashes = hashes2 } fmt.Printf("%x", hashes[0]) fmt.Println() }
#include <glib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> guchar* sha256_merkle_tree(FILE* in, size_t block_size) { gchar* buffer = g_malloc(block_size); GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free); gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256); GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256); size_t bytes; while ((bytes = fread(buffer, 1, block_size, in)) > 0) { g_checksum_reset(checksum); g_checksum_update(checksum, (guchar*)buffer, bytes); gsize len = digest_length; guchar* digest = g_malloc(len); g_checksum_get_digest(checksum, digest, &len); g_ptr_array_add(hashes, digest); } g_free(buffer); guint hashes_length = hashes->len; if (hashes_length == 0) { g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return NULL; } while (hashes_length > 1) { guint j = 0; for (guint i = 0; i < hashes_length; i += 2, ++j) { guchar* digest1 = g_ptr_array_index(hashes, i); guchar* digest_out = g_ptr_array_index(hashes, j); if (i + 1 < hashes_length) { guchar* digest2 = g_ptr_array_index(hashes, i + 1); g_checksum_reset(checksum); g_checksum_update(checksum, digest1, digest_length); g_checksum_update(checksum, digest2, digest_length); gsize len = digest_length; g_checksum_get_digest(checksum, digest_out, &len); } else { memcpy(digest_out, digest1, digest_length); } } hashes_length = j; } guchar* result = g_ptr_array_steal_index(hashes, 0); g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return result; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s filename\n", argv[0]); return EXIT_FAILURE; } FILE* in = fopen(argv[1], "rb"); if (in) { guchar* digest = sha256_merkle_tree(in, 1024); fclose(in); if (digest) { gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256); for (gssize i = 0; i < length; ++i) printf("%02x", digest[i]); printf("\n"); g_free(digest); } } else { perror(argv[1]); return EXIT_FAILURE; } return EXIT_SUCCESS; }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "fmt" "strings" "unicode" "unicode/utf8" ) func main() { show("alphaBETA") show("alpha BETA") show("DŽLjnj") show("o'hare O'HARE o’hare don't") } func show(s string) { fmt.Println("\nstring: ", s, " len:", utf8.RuneCountInString(s), "runes") fmt.Println("All upper case: ", strings.ToUpper(s)) fmt.Println("All lower case: ", strings.ToLower(s)) fmt.Println("All title case: ", strings.ToTitle(s)) fmt.Println("Title words: ", strings.Title(s)) fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) }
#include <ctype.h> #include <stdio.h> void str_toupper(char *s) { while(*s) { *s=toupper(*s); s++; } } void str_tolower(char *s) { while(*s) { *s=tolower(*s); s++; } } int main(int argc, char *argv[]) { char t[255]="alphaBETA"; str_toupper(t); printf("uppercase: %s\n", t); str_tolower(t); printf("lowercase: %s\n", t); return 0; }
Change the following Go code into C without altering its purpose.
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str1, str2 string) bool { n, err := strconv.ParseFloat(str2, 64) if len(str1) == 0 || err != nil || n != 75000 { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid input", ) dialog.Run() dialog.Destroy() return false } return true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1) check(err, "Unable to create vertical box:") vbox.SetBorderWidth(1) hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create first horizontal box:") hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create second horizontal box:") label, err := gtk.LabelNew("Enter a string and the number 75000 \n") check(err, "Unable to create label:") sel, err := gtk.LabelNew("String: ") check(err, "Unable to create string entry label:") nel, err := gtk.LabelNew("Number: ") check(err, "Unable to create number entry label:") se, err := gtk.EntryNew() check(err, "Unable to create string entry:") ne, err := gtk.EntryNew() check(err, "Unable to create number entry:") hbox1.PackStart(sel, false, false, 2) hbox1.PackStart(se, false, false, 2) hbox2.PackStart(nel, false, false, 2) hbox2.PackStart(ne, false, false, 2) ab, err := gtk.ButtonNewWithLabel("Accept") check(err, "Unable to create accept button:") ab.Connect("clicked", func() { str1, _ := se.GetText() str2, _ := ne.GetText() if validateInput(window, str1, str2) { window.Destroy() } }) vbox.Add(label) vbox.Add(hbox1) vbox.Add(hbox2) vbox.Add(ab) window.Add(vbox) window.ShowAll() gtk.Main() }
#include <gtk/gtk.h> void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg; gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]); msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "You wrote '%s' and selected the number %d%s", c, (gint)v, (v==75000) ? "" : " which is wrong (75000 expected)!"); gtk_widget_show_all(GTK_WIDGET(msg)); (void)gtk_dialog_run(GTK_DIALOG(msg)); gtk_widget_destroy(GTK_WIDGET(msg)); if ( v==75000 ) gtk_main_quit(); } int main(int argc, char **argv) { GtkWindow *win; GtkEntry *entry; GtkSpinButton *spin; GtkButton *okbutton; GtkLabel *entry_l, *spin_l; GtkHBox *hbox[2]; GtkVBox *vbox; GtkWidget *widgs[2]; gtk_init(&argc, &argv); win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, "Insert values"); entry_l = (GtkLabel *)gtk_label_new("Insert a string"); spin_l = (GtkLabel *)gtk_label_new("Insert 75000"); entry = (GtkEntry *)gtk_entry_new(); spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1); widgs[0] = GTK_WIDGET(entry); widgs[1] = GTK_WIDGET(spin); okbutton = (GtkButton *)gtk_button_new_with_label("Ok"); hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1); vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin)); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Produce a functionally identical C code for the snippet given in Go.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) iy = 1.0 theta = 0 ) var cx, cy, h float64 func arrowhead(order int, length float64) { if order&1 == 0 { curve(order, length, 60) } else { turn(60) curve(order, length, -60) } drawLine(length) } func drawLine(length float64) { dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h) rads := gg.Radians(float64(theta)) cx += length * math.Cos(rads) cy += length * math.Sin(rads) } func turn(angle int) { theta = (theta + angle) % 360 } func curve(order int, length float64, angle int) { if order == 0 { drawLine(length) } else { curve(order-1, length/2, -angle) turn(angle) curve(order-1, length/2, angle) turn(angle) curve(order-1, length/2, -angle) } } func main() { dc.SetRGB(0, 0, 0) dc.Clear() order := 6 if order&1 == 0 { iy = -1 } cx, cy = width/2, height h = cx / 2 arrowhead(order, cx) dc.SetRGB255(255, 0, 255) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_arrowhead_curve.png") }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct cursor_tag { double x; double y; int angle; } cursor_t; void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; } void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, "L%g,%g\n", cursor->x, cursor->y); } void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } } void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, "<svg xmlns='http: size, size); fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n"); fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='"); fprintf(out, "M%g,%g\n", cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, "'/>\n</svg>\n"); } int main(int argc, char** argv) { const char* filename = "sierpinski_arrowhead.svg"; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, "w"); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
Translate this program into C but keep the logic exactly as in Go.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) const ( filename = "readings.txt" readings = 24 fields = readings*2 + 1 ) func main() { file, err := os.Open(filename) if err != nil { log.Fatal(err) } defer file.Close() var ( badRun, maxRun int badDate, maxDate string fileSum float64 fileAccept int ) endBadRun := func() { if badRun > maxRun { maxRun = badRun maxDate = badDate } badRun = 0 } s := bufio.NewScanner(file) for s.Scan() { f := strings.Fields(s.Text()) if len(f) != fields { log.Fatal("unexpected format,", len(f), "fields.") } var accept int var sum float64 for i := 1; i < fields; i += 2 { flag, err := strconv.Atoi(f[i+1]) if err != nil { log.Fatal(err) } if flag <= 0 { if badRun++; badRun == 1 { badDate = f[0] } } else { endBadRun() value, err := strconv.ParseFloat(f[i], 64) if err != nil { log.Fatal(err) } sum += value accept++ } } fmt.Printf("Line: %s Reject %2d Accept: %2d Line_tot:%9.3f", f[0], readings-accept, accept, sum) if accept > 0 { fmt.Printf(" Line_avg:%8.3f\n", sum/float64(accept)) } else { fmt.Println() } fileSum += sum fileAccept += accept } if err := s.Err(); err != nil { log.Fatal(err) } endBadRun() fmt.Println("\nFile =", filename) fmt.Printf("Total = %.3f\n", fileSum) fmt.Println("Readings = ", fileAccept) if fileAccept > 0 { fmt.Printf("Average =  %.3f\n", fileSum/float64(fileAccept)) } if maxRun == 0 { fmt.Println("\nAll data valid.") } else { fmt.Printf("\nMax data gap = %d, beginning on line %s.\n", maxRun, maxDate) } }
#include <stdio.h> #include <stdlib.h> #include <string.h> static int badHrs, maxBadHrs; static double hrsTot = 0.0; static int rdgsTot = 0; char bhEndDate[40]; int mungeLine( char *line, int lno, FILE *fout ) { char date[40], *tkn; int dHrs, flag, hrs2, hrs; double hrsSum; int hrsCnt = 0; double avg; tkn = strtok(line, "."); if (tkn) { int n = sscanf(tkn, "%s %d", &date, &hrs2); if (n<2) { printf("badly formated line - %d %s\n", lno, tkn); return 0; } hrsSum = 0.0; while( tkn= strtok(NULL, ".")) { n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs); if (n>=2) { if (flag > 0) { hrsSum += 1.0*hrs2 + .001*dHrs; hrsCnt += 1; if (maxBadHrs < badHrs) { maxBadHrs = badHrs; strcpy(bhEndDate, date); } badHrs = 0; } else { badHrs += 1; } hrs2 = hrs; } else { printf("bad file syntax line %d: %s\n",lno, tkn); } } avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0; fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n", date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt); hrsTot += hrsSum; rdgsTot += hrsCnt; } return 1; } int main() { FILE *infile, *outfile; int lineNo = 0; char line[512]; const char *ifilename = "readings.txt"; outfile = fopen("V0.txt", "w"); infile = fopen(ifilename, "rb"); if (!infile) { printf("Can't open %s\n", ifilename); exit(1); } while (NULL != fgets(line, 512, infile)) { lineNo += 1; if (0 == mungeLine(line, lineNo, outfile)) printf("Bad line at %d",lineNo); } fclose(infile); fprintf(outfile, "File: %s\n", ifilename); fprintf(outfile, "Total:  %.3f\n", hrsTot); fprintf(outfile, "Readings: %d\n", rdgsTot); fprintf(outfile, "Average:  %.3f\n", hrsTot/rdgsTot); fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs); fprintf(outfile, "Ends on date %s\n", bhEndDate); fclose(outfile); return 0; }
Preserve the algorithm and functionality while converting the code from Go to C.
package main import ( "crypto/md5" "fmt" ) func main() { for _, p := range [][2]string{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, {"e38ca1d920c4b8b8d3946b2c72f01680", "The quick brown fox jumped over the lazy dog's back"}, } { validate(p[0], p[1]) } } var h = md5.New() func validate(check, s string) { h.Reset() h.Write([]byte(s)) sum := fmt.Sprintf("%x", h.Sum(nil)) if sum != check { fmt.Println("MD5 fail") fmt.Println(" for string,", s) fmt.Println(" expected: ", check) fmt.Println(" got: ", sum) } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> const char *string = "The quick brown fox jumped over the lazy dog's back"; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", result[i]); printf("\n"); return EXIT_SUCCESS; }
Ensure the translated C code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Generate an equivalent C version of this Go code.
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "fmt" "time" ) const taskDate = "March 7 2009 7:30pm EST" const taskFormat = "January 2 2006 3:04pm MST" func main() { if etz, err := time.LoadLocation("US/Eastern"); err == nil { time.Local = etz } fmt.Println("Input: ", taskDate) t, err := time.Parse(taskFormat, taskDate) if err != nil { fmt.Println(err) return } t = t.Add(12 * time.Hour) fmt.Println("+12 hrs: ", t) if _, offset := t.Zone(); offset == 0 { fmt.Println("No time zone info.") return } atz, err := time.LoadLocation("US/Arizona") if err == nil { fmt.Println("+12 hrs in Arizona:", t.In(atz)) } }
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST"; strptime(d, "%B %d %Y %I:%M%p %Z", &ts); t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); return EXIT_SUCCESS; }
Generate an equivalent C version of this Go code.
package main import ( "fmt" "log" "os" "strconv" "time" ) func main() { out := make(chan uint64) for _, a := range os.Args[1:] { i, err := strconv.ParseUint(a, 10, 64) if err != nil { log.Fatal(err) } go func(n uint64) { time.Sleep(time.Duration(n) * time.Millisecond) out <- n }(i) } for _ = range os.Args[1:] { fmt.Println(<-out) } }
>>>>>,----------[++++++++ ++[->+>+<<]>+>[-<<+>>]+++ +++++[-<------>]>>+>,---- ------<<+[->>>>>+<<<<<]>> ]>>>[<<<<[<<<[->>+<<[->+> [-]<<]]>[-<+>]>[-<<<.>>>> ->>>>>[>>>>>]<-<<<<[<<<<< ]+<]<<<<]>>>>>[>>>>>]<]
Rewrite the snippet below in C so it works the same as the original Go code.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) values := make([][]int, 10) for i := range values { values[i] = make([]int, 10) for j := range values[i] { values[i][j] = rand.Intn(20) + 1 } } outerLoop: for i, row := range values { fmt.Printf("%3d)", i) for _, value := range row { fmt.Printf(" %3d", value) if value == 20 { break outerLoop } } fmt.Printf("\n") } fmt.Printf("\n") }
#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int a[10][10], i, j; srand(time(NULL)); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) a[i][j] = rand() % 20 + 1; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf(" %d", a[i][j]); if (a[i][j] == 20) goto Done; } printf("\n"); } Done: printf("\n"); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Go version.
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Produce a language-to-language conversion: from Go to C, same semantics.
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Generate a C translation of this Go snippet without changing its computational steps.
package main import "fmt" func uniq(list []int) []int { unique_set := make(map[int]bool, len(list)) for _, x := range list { unique_set[x] = true } result := make([]int, 0, len(unique_set)) for x := range unique_set { result = append(result, x) } return result } func main() { fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) }
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
Ensure the translated C code behaves exactly like the original Go snippet.
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
Write the same code in C as shown below in Go.
var intStack []int
#include <stdio.h> #include <stdlib.h> #define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ stk_##name stk_##name##_create(size_t init_size) { \ stk_##name s; if (!init_size) init_size = 4; \ s = malloc(sizeof(struct stk_##name##_t)); \ if (!s) return 0; \ s->buf = malloc(sizeof(type) * init_size); \ if (!s->buf) { free(s); return 0; } \ s->len = 0, s->alloc = init_size; \ return s; } \ int stk_##name##_push(stk_##name s, type item) { \ type *tmp; \ if (s->len >= s->alloc) { \ tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ if (!tmp) return -1; s->buf = tmp; \ s->alloc *= 2; } \ s->buf[s->len++] = item; \ return s->len; } \ type stk_##name##_pop(stk_##name s) { \ type tmp; \ if (!s->len) abort(); \ tmp = s->buf[--s->len]; \ if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ s->alloc /= 2; \ s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ return tmp; } \ void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) #define stk_size(s) ((s)->len) DECL_STACK_TYPE(int, int) int main(void) { int i; stk_int stk = stk_int_create(0); printf("pushing: "); for (i = 'a'; i <= 'z'; i++) { printf(" %c", i); stk_int_push(stk, i); } printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); printf("\npoppoing:"); while (stk_size(stk)) printf(" %c", stk_int_pop(stk)); printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); stk_int_delete(stk); return 0; }
Produce a language-to-language conversion: from Go to C, same semantics.
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { t >>= 1 } if t > 0 { n = t } else { k = -t } t = n - k } return n * s } func totient(n int) int { tot := 0 for k := 1; k <= n; k++ { if gcd(n, k) == 1 { tot++ } } return tot } func main() { fmt.Println(" n phi prime") fmt.Println("---------------") count := 0 for n := 1; n <= 25; n++ { tot := totient(n) isPrime := n-1 == tot if isPrime { count++ } fmt.Printf("%2d %2d %t\n", n, tot, isPrime) } fmt.Println("\nNumber of primes up to 25 =", count) for n := 26; n <= 100000; n++ { tot := totient(n) if tot == n-1 { count++ } if n == 100 || n == 1000 || n%10000 == 0 { fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count) } } }
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
Please provide an equivalent version of this Go code in C.
if booleanExpression { statements }
int a = 3; if (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } unless (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } switch (a) { case 2: puts ("a is 2"); break; case 3: puts ("a is 3"); break; case 4: puts ("a is 4"); break; default: puts("is neither"); }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "fmt" "log" "math/big" "os" "strconv" "strings" ) func compile(src string) ([]big.Rat, bool) { s := strings.Fields(src) r := make([]big.Rat, len(s)) for i, s1 := range s { if _, ok := r[i].SetString(s1); !ok { return nil, false } } return r, true } func exec(p []big.Rat, n *big.Int, limit int) { var q, r big.Int rule: for i := 0; i < limit; i++ { fmt.Printf("%d ", n) for j := range p { q.QuoRem(n, p[j].Denom(), &r) if r.BitLen() == 0 { n.Mul(&q, p[j].Num()) continue rule } } break } fmt.Println() } func usage() { log.Fatal("usage: ft <limit> <n> <prog>") } func main() { if len(os.Args) != 4 { usage() } limit, err := strconv.Atoi(os.Args[1]) if err != nil { usage() } var n big.Int _, ok := n.SetString(os.Args[2], 10) if !ok { usage() } p, ok := compile(os.Args[3]) if !ok { usage() } exec(p, &n, limit) }
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); else gmp_printf(" %Zd", val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf("\nhalt: %Zd has no divisors\n", val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] } if last > 1 { t := len(a) / 3 stoogesort(a[:len(a)-t]) stoogesort(a[t:]) stoogesort(a[:len(a)-t]) } }
#include <stdio.h> #define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } int main(int argc, char *argv[]) { int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; int i, n; n = sizeof(nums)/sizeof(int); StoogeSort(nums, 0, n-1); for(i = 0; i <= n-1; i++) printf("%5d", nums[i]); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) type Ball struct{ x, y int } func newBall(x, y int) *Ball { if box[y][x] != empty { panic("Tried to create a new ball in a non-empty cell. Program terminated.") } b := Ball{x, y} box[y][x] = ball return &b } func (b *Ball) doStep() { if b.y <= 0 { return } cell := box[b.y-1][b.x] switch cell { case empty: box[b.y][b.x] = empty b.y-- box[b.y][b.x] = ball case pin: box[b.y][b.x] = empty b.y-- if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty { b.x += rand.Intn(2)*2 - 1 box[b.y][b.x] = ball return } else if box[b.y][b.x-1] == empty { b.x++ } else { b.x-- } box[b.y][b.x] = ball default: } } type Cell = byte var box [boxH][boxW]Cell func initializeBox() { box[0][0] = corner box[0][boxW-1] = corner for i := 1; i < boxW-1; i++ { box[0][i] = floor } for i := 0; i < boxW; i++ { box[boxH-1][i] = box[0][i] } for r := 1; r < boxH-1; r++ { box[r][0] = wall box[r][boxW-1] = wall } for i := 1; i < boxH-1; i++ { for j := 1; j < boxW-1; j++ { box[i][j] = empty } } for nPins := 1; nPins <= pinsBaseW; nPins++ { for p := 0; p < nPins; p++ { box[boxH-2-nPins][centerH+1-nPins+p*2] = pin } } } func drawBox() { for r := boxH - 1; r >= 0; r-- { for c := 0; c < boxW; c++ { fmt.Printf("%c", box[r][c]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) initializeBox() var balls []*Ball for i := 0; i < nMaxBalls+boxH; i++ { fmt.Println("\nStep", i, ":") if i < nMaxBalls { balls = append(balls, newBall(centerH, boxH-2)) } drawBox() for _, b := range balls { b.doStep() } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b; #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts("\033[H"), i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++, putchar(' ')) printf(B(i, j) == '*' ? C(i - 1, j) ? "\033[32m%c\033[m" : "\033[31m%c\033[m" : "%c", B(i, j)); } void init() { int i, j; puts("\033[H\033[J"); b = malloc(w * h); memset(b, ' ', w * h); x = malloc(sizeof(int) * BALLS * 2); y = x + BALLS; for (i = 0; i < n; i++) for (j = -i; j <= i; j += 2) B(2 * i+2, j + w/2) = '*'; srand(time(0)); } void move(int idx) { int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0; if (yy < 0) return; if (yy == h - 1) { y[idx] = -1; return; } switch(c = B(yy + 1, xx)) { case ' ': yy++; break; case '*': sl = 1; default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1)) if (!rnd(sl++)) o = 1; if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1)) if (!rnd(sl++)) o = -1; if (!o) kill = 1; xx += o; } c = V(idx); V(idx) = ' '; idx[y] = yy, idx[x] = xx; B(yy, xx) = c; if (kill) idx[y] = -1; } int run(void) { static int step = 0; int i; for (i = 0; i < cnt; i++) move(i); if (2 == ++step && cnt < BALLS) { step = 0; x[cnt] = w/2; y[cnt] = 0; if (V(cnt) != ' ') return 0; V(cnt) = rnd(80) + 43; cnt++; } return 1; } int main(int c, char **v) { if (c < 2 || (n = atoi(v[1])) <= 3) n = 5; if (n >= 20) n = 20; w = n * 2 + 1; init(); do { show_board(), usleep(60000); } while (run()); return 0; }
Change the following Go code into C without altering its purpose.
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circleSort(a, low, low+mid, swaps) swaps = circleSort(a, low+mid+1, high, swaps) return swaps } func main() { aa := [][]int{ {6, 7, 8, 9, 2, 5, 3, 4, 1}, {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}, } for _, a := range aa { fmt.Printf("Original: %v\n", a) for circleSort(a, 0, len(a)-1, 0) != 0 { } fmt.Printf("Sorted  : %v\n\n", a) } }
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf("%d ", x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); } int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x)); return 0; }
Write the same algorithm in C as shown in this Go implementation.
package main import "fmt" type matrix [][]int func (m1 matrix) kroneckerProduct(m2 matrix) matrix { m := len(m1) n := len(m1[0]) p := len(m2) q := len(m2[0]) rtn := m * p ctn := n * q r := make(matrix, rtn) for i := range r { r[i] = make([]int, ctn) } for i := 0; i < m; i++ { for j := 0; j < n; j++ { for k := 0; k < p; k++ { for l := 0; l < q; l++ { r[p*i+k][q*j+l] = m1[i][j] * m2[k][l] } } } } return r } func (m matrix) kroneckerPower(n int) matrix { pow := m for i := 1; i < n; i++ { pow = pow.kroneckerProduct(m) } return pow } func (m matrix) print(text string) { fmt.Println(text, "fractal :\n") for i := range m { for j := range m[0] { if m[i][j] == 1 { fmt.Print("*") } else { fmt.Print(" ") } } fmt.Println() } fmt.Println() } func main() { m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}} m1.kroneckerPower(4).print("Vivsek") m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}} m2.kroneckerPower(4).print("Sierpinski carpet") }
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = fopen(inputFile,"r"); int i,j,k,l; unsigned long prod; int** matrix; cell *coreList,*tempList,*resultList; fscanf(fp,"%d%d",&ROW,&COL); matrix = (int**)malloc(ROW*sizeof(int*)); for(i=0;i<ROW;i++){ matrix[i] = (int*)malloc(COL*sizeof(int)); for(j=0;j<COL;j++){ fscanf(fp,"%d",&matrix[i][j]); if(matrix[i][j]==1) SUM++; } } coreList = (cell*)malloc(SUM*sizeof(cell)); resultList = (cell*)malloc(SUM*sizeof(cell)); k = 0; for(i=0;i<ROW;i++){ for(j=0;j<COL;j++){ if(matrix[i][j]==1){ coreList[k].row = i+1; coreList[k].col = j+1; resultList[k].row = i+1; resultList[k].col = j+1; k++; } } } prod = k; for(i=2;i<=power;i++){ tempList = (cell*)malloc(prod*k*sizeof(cell)); l = 0; for(j=0;j<prod;j++){ for(k=0;k<SUM;k++){ tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row; tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col; l++; } } free(resultList); prod *= k; resultList = (cell*)malloc(prod*sizeof(cell)); for(j=0;j<prod;j++){ resultList[j].row = tempList[j].row; resultList[j].col = tempList[j].col; } free(tempList); } return resultList; } int main(){ char fileName[100]; int power,i,length; cell* resultList; printf("Enter input file name : "); scanf("%s",fileName); printf("Enter power : "); scanf("%d",&power); resultList = kroneckerProduct(fileName,power); initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal"); length = raiseTo(SUM,power); for(i=0;i<length;i++){ putpixel(resultList[i].row,resultList[i].col,15); } getch(); closegraph(); return 0; }
Generate an equivalent C version of this Go code.
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si("FULLNAME", this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, "Sorry, something went wrong :-(\n"); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value("YES", 0); if (populate_configs(&confs)) { return 1; } printf( "Full name: %s\n" "Favorite fruit: %s\n" "Need spelling: %s\n" "Seeds removed: %s\n", confs.fullname, confs.favouritefruit, confs.needspeeling ? "True" : "False", confs.seedsremoved ? "True" : "False" ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); } #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }
Change the programming language of this snippet from Go to C without modifying what it does.
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
#include <stdlib.h> #include <string.h> #include <strings.h> int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
Port the following code from Go to C with equivalent syntax and logic.
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
#include <stdlib.h> #include <string.h> #include <strings.h> int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
Write a version of this Go function in C with identical behavior.
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func repunit(n int) *big.Int { ones := strings.Repeat("1", n) b, _ := new(big.Int).SetString(ones, 10) return b } var circs = []int{} func alreadyFound(n int) bool { for _, i := range circs { if i == n { return true } } return false } func isCircular(n int) bool { nn := n pow := 1 for nn > 0 { pow *= 10 nn /= 10 } nn = n for { nn *= 10 f := nn / pow nn += f * (1 - pow) if alreadyFound(nn) { return false } if nn == n { break } if !isPrime(nn) { return false } } return true } func main() { fmt.Println("The first 19 circular primes are:") digits := [4]int{1, 3, 7, 9} q := []int{1, 2, 3, 5, 7, 9} fq := []int{1, 2, 3, 5, 7, 9} count := 0 for { f := q[0] fd := fq[0] if isPrime(f) && isCircular(f) { circs = append(circs, f) count++ if count == 19 { break } } copy(q, q[1:]) q = q[:len(q)-1] copy(fq, fq[1:]) fq = fq[:len(fq)-1] if f == 2 || f == 5 { continue } for _, d := range digits { if d >= fd { q = append(q, f*10+d) fq = append(fq, fd) } } } fmt.Println(circs) fmt.Println("\nThe next 4 circular primes, in repunit format, are:") count = 0 var rus []string for i := 7; count < 4; i++ { if repunit(i).ProbablyPrime(10) { count++ rus = append(rus, fmt.Sprintf("R(%d)", i)) } } fmt.Println(rus) fmt.Println("\nThe following repunits are probably circular primes:") for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} { fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10)) } }
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } uint32_t cycle(uint32_t n) { uint32_t m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } bool is_circular_prime(uint32_t p) { if (!is_prime(p)) return false; uint32_t p2 = cycle(p); while (p2 != p) { if (p2 < p || !is_prime(p2)) return false; p2 = cycle(p2); } return true; } void test_repunit(uint32_t digits) { char* str = malloc(digits + 1); if (str == 0) { fprintf(stderr, "Out of memory\n"); exit(1); } memset(str, '1', digits); str[digits] = 0; mpz_t bignum; mpz_init_set_str(bignum, str, 10); free(str); if (mpz_probab_prime_p(bignum, 10)) printf("R(%u) is probably prime.\n", digits); else printf("R(%u) is not prime.\n", digits); mpz_clear(bignum); } int main() { uint32_t p = 2; printf("First 19 circular primes:\n"); for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) printf(", "); printf("%u", p); ++count; } } printf("\n"); printf("Next 4 circular primes:\n"); uint32_t repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; mpz_t bignum; mpz_init_set_ui(bignum, repunit); for (int count = 0; count < 4; ) { if (mpz_probab_prime_p(bignum, 15)) { if (count > 0) printf(", "); printf("R(%u)", digits); ++count; } ++digits; mpz_mul_ui(bignum, bignum, 10); mpz_add_ui(bignum, bignum, 1); } mpz_clear(bignum); printf("\n"); test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package main import ( "log" "time" "github.com/gdamore/tcell" ) const ( msg = "Hello World! " x0, y0 = 8, 3 shiftsPerSecond = 4 clicksToExit = 5 ) func main() { s, err := tcell.NewScreen() if err != nil { log.Fatal(err) } if err = s.Init(); err != nil { log.Fatal(err) } s.Clear() s.EnableMouse() tick := time.Tick(time.Second / shiftsPerSecond) click := make(chan bool) go func() { for { em, ok := s.PollEvent().(*tcell.EventMouse) if !ok || em.Buttons()&0xFF == tcell.ButtonNone { continue } mx, my := em.Position() if my == y0 && mx >= x0 && mx < x0+len(msg) { click <- true } } }() for inc, shift, clicks := 1, 0, 0; ; { select { case <-tick: shift = (shift + inc) % len(msg) for i, r := range msg { s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0) } s.Show() case <-click: clicks++ if clicks == clicksToExit { s.Fini() return } inc = len(msg) - inc } } }
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r = malloc(l+1); for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++) r[j] = t[i]; r[l] = 0; return r; } gboolean scroll_it(gpointer data) { if ( direction > 0 ) cx = (cx + 1) % slen; else cx = (cx + slen - 1 ) % slen; gchar *scrolled = rotateby(hello, cx, slen); gtk_label_set_text(label, scrolled); free(scrolled); return TRUE; } int main(int argc, char **argv) { GtkWidget *win; GtkButton *button; PangoFontDescription *pd; gtk_init(&argc, &argv); win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(win), "Basic Animation"); g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL); label = (GtkLabel *)gtk_label_new(hello); pd = pango_font_description_new(); pango_font_description_set_family(pd, "monospace"); gtk_widget_modify_font(GTK_WIDGET(label), pd); button = (GtkButton *)gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button)); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL); slen = strlen(hello); g_timeout_add(125, scroll_it, NULL); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Generate a C translation of this Go snippet without changing its computational steps.
package main import ( "log" "time" "github.com/gdamore/tcell" ) const ( msg = "Hello World! " x0, y0 = 8, 3 shiftsPerSecond = 4 clicksToExit = 5 ) func main() { s, err := tcell.NewScreen() if err != nil { log.Fatal(err) } if err = s.Init(); err != nil { log.Fatal(err) } s.Clear() s.EnableMouse() tick := time.Tick(time.Second / shiftsPerSecond) click := make(chan bool) go func() { for { em, ok := s.PollEvent().(*tcell.EventMouse) if !ok || em.Buttons()&0xFF == tcell.ButtonNone { continue } mx, my := em.Position() if my == y0 && mx >= x0 && mx < x0+len(msg) { click <- true } } }() for inc, shift, clicks := 1, 0, 0; ; { select { case <-tick: shift = (shift + inc) % len(msg) for i, r := range msg { s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0) } s.Show() case <-click: clicks++ if clicks == clicksToExit { s.Fini() return } inc = len(msg) - inc } } }
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r = malloc(l+1); for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++) r[j] = t[i]; r[l] = 0; return r; } gboolean scroll_it(gpointer data) { if ( direction > 0 ) cx = (cx + 1) % slen; else cx = (cx + slen - 1 ) % slen; gchar *scrolled = rotateby(hello, cx, slen); gtk_label_set_text(label, scrolled); free(scrolled); return TRUE; } int main(int argc, char **argv) { GtkWidget *win; GtkButton *button; PangoFontDescription *pd; gtk_init(&argc, &argv); win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(win), "Basic Animation"); g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL); label = (GtkLabel *)gtk_label_new(hello); pd = pango_font_description_new(); pango_font_description_set_family(pd, "monospace"); gtk_widget_modify_font(GTK_WIDGET(label), pd); button = (GtkButton *)gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button)); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL); slen = strlen(hello); g_timeout_add(125, scroll_it, NULL); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "bytes" "encoding/binary" "fmt" ) type word int32 const wordLen = 4 const highBit = -1 << 31 var data = []word{170, 45, 75, -90, -802, 24, 2, 66} func main() { buf := bytes.NewBuffer(nil) ds := make([][]byte, len(data)) for i, x := range data { binary.Write(buf, binary.LittleEndian, x^highBit) b := make([]byte, wordLen) buf.Read(b) ds[i] = b } bins := make([][][]byte, 256) for i := 0; i < wordLen; i++ { for _, b := range ds { bins[b[i]] = append(bins[b[i]], b) } j := 0 for k, bs := range bins { copy(ds[j:], bs) j += len(bs) bins[k] = bs[:0] } } fmt.Println("original:", data) var w word for i, b := range ds { buf.Write(b) binary.Read(buf, binary.LittleEndian, &w) data[i] = w^highBit } fmt.Println("sorted: ", data) }
#include <stdio.h> #include <limits.h> #include <stdlib.h> #include <time.h> #define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) #define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); static void swap(unsigned *a, unsigned *b) { unsigned tmp = *a; *a = *b; *b = tmp; } static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) { if (!bit || to < from + 1) return; unsigned *ll = from, *rr = to - 1; for (;;) { while (ll < rr && !(*ll & bit)) ll++; while (ll < rr && (*rr & bit)) rr--; if (ll >= rr) break; swap(ll, rr); } if (!(bit & *ll) && ll < to) ll++; bit >>= 1; rad_sort_u(from, ll, bit); rad_sort_u(ll, to, bit); } static void radix_sort(int *a, const size_t len) { size_t i; unsigned *x = (unsigned*) a; for (i = 0; i < len; i++) x[i] ^= INT_MIN; rad_sort_u(x, x + len, INT_MIN); for (i = 0; i < len; i++) x[i] ^= INT_MIN; } int main(void) { srand(time(NULL)); int x[16]; for (size_t i = 0; i < ARR_LEN(x); i++) x[i] = RAND_RNG(-128,127) radix_sort(x, ARR_LEN(x)); for (size_t i = 0; i < ARR_LEN(x); i++) printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); }
Write the same code in C as shown below in Go.
package main import "fmt" type ( seq []int sofs []seq ) func newSeq(start, end int) seq { if end < start { end = start } s := make(seq, end-start+1) for i := 0; i < len(s); i++ { s[i] = start + i } return s } func newSofs() sofs { return sofs{seq{}} } func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs { var s2 sofs for _, t := range expr(s, in) { if pred(t) { s2 = append(s2, t) } } return s2 } func (s sofs) build(t seq) sofs { var u sofs for _, ss := range s { for _, tt := range t { uu := make(seq, len(ss)) copy(uu, ss) uu = append(uu, tt) u = append(u, uu) } } return u } func main() { pt := newSofs() in := newSeq(1, 20) expr := func(s sofs, t seq) sofs { return s.build(t).build(t).build(t) } pred := func(t seq) bool { if len(t) != 3 { return false } return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2] } pt = pt.listComp(in, expr, pred) fmt.Println(pt) }
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
Write the same code in C as shown below in Go.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) selectionSort(a) fmt.Println("after: ", a) } func selectionSort(a []int) { last := len(a) - 1 for i := 0; i < last; i++ { aMin := a[i] iMin := i for j := i + 1; j < len(a); j++ { if a[j] < aMin { aMin = a[j] iMin = j } } a[i], a[iMin] = aMin, a[i] } }
#include <stdio.h> void selection_sort (int *a, int n) { int i, j, m, t; for (i = 0; i < n; i++) { for (j = i, m = i; j < n; j++) { if (a[j] < a[m]) { m = j; } } t = a[i]; a[i] = a[m]; a[m] = t; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); selection_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Please provide an equivalent version of this Go code in C.
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Convert this Go block to C, preserving its control flow and logic.
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Convert this Go snippet to C and keep its semantics consistent.
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
Change the following Go code into C without altering its purpose.
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
Produce a language-to-language conversion: from Go to C, same semantics.
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
#ifndef CALLBACK_H #define CALLBACK_H void map(int* array, int len, void(*callback)(int,int)); #endif
Translate this program into C but keep the logic exactly as in Go.
package main import ( "log" "math/rand" "sync" "time" ) var ( instance string once sync.Once ) func claim(color string, w *sync.WaitGroup) { time.Sleep(time.Duration(rand.Intn(1e8))) log.Println("trying to claim", color) once.Do(func() { instance = color }) log.Printf("tried %s. instance: %s", color, instance) w.Done() } func main() { rand.Seed(time.Now().Unix()) var w sync.WaitGroup w.Add(2) go claim("red", &w) go claim("blue", &w) w.Wait() log.Println("after trying both, instance =", instance) }
#ifndef SILLY_H #define SILLY_H extern void JumpOverTheDog( int numberOfTimes); extern int PlayFetchWithDog( float weightOfStick); #endif
Rewrite the snippet below in C so it works the same as the original Go code.
package main import ( "fmt" "math" ) type interval struct { lower, upper float64 } func stepAway(x float64) interval { return interval { math.Nextafter(x, math.Inf(-1)), math.Nextafter(x, math.Inf(1))} } func safeAdd(a, b float64) interval { return stepAway(a + b) } func main() { a, b := 1.2, .03 fmt.Println(a, b, safeAdd(a, b)) }
#include <fenv.h> #include <stdio.h> void safe_add(volatile double interval[2], volatile double a, volatile double b) { #pragma STDC FENV_ACCESS ON unsigned int orig; orig = fegetround(); fesetround(FE_DOWNWARD); interval[0] = a + b; fesetround(FE_UPWARD); interval[1] = a + b; fesetround(orig); } int main() { const double nums[][2] = { {1, 2}, {0.1, 0.2}, {1e100, 1e-100}, {1e308, 1e308}, }; double ival[2]; int i; for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) { safe_add(ival, nums[i][0], nums[i][1]); printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]); printf(" [%.17g, %.17g]\n", ival[0], ival[1]); printf(" size %.17g\n\n", ival[1] - ival[0]); } return 0; }
Keep all operations the same but rewrite the snippet in C.
package dogs import "fmt" var dog = "Salt" var Dog = "Pepper" var DOG = "Mustard" func PackageSees() map[*string]int { fmt.Println("Package sees:", dog, Dog, DOG) return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1} }
#include <stdio.h> static const char *dog = "Benjamin"; static const char *Dog = "Samba"; static const char *DOG = "Bernie"; int main() { printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG); return 0; }
Ensure the translated C code behaves exactly like the original Go snippet.
for i := 10; i >= 0; i-- { fmt.Println(i) }
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
Convert the following code from Go to C, ensuring the logic remains intact.
for i := 10; i >= 0; i-- { fmt.Println(i) }
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
Translate this program into C but keep the logic exactly as in Go.
import "io/ioutil" func main() { ioutil.WriteFile("path/to/your.file", []byte("data"), 0644) }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.", freopen("sample.txt","wb",stdout)); }
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import "fmt" func main() { for i := 1; i <= 5; i++ { for j := 1; j <= i; j++ { fmt.Printf("*") } fmt.Printf("\n") } }
int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) putchar('*'); puts(""); }
Rewrite this program in C while keeping its functionality equivalent to the Go version.
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
Keep all operations the same but rewrite the snippet in C.
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
Produce a functionally identical C code for the snippet given in Go.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; 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 long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; 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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", 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); sierp(size, depth + 2); return 0; }
Convert this Go snippet to C and keep its semantics consistent.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; 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 long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; 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 = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", 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); sierp(size, depth + 2); return 0; }
Produce a language-to-language conversion: from Go to C, same semantics.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPrime(sum) { c++ fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum)) } } fmt.Println() fmt.Println(c, "such prime sums found") }
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; int p; for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
Please provide an equivalent version of this Go code in C.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPrime(sum) { c++ fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum)) } } fmt.Println() fmt.Println(c, "such prime sums found") }
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; int p; for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
Preserve the algorithm and functionality while converting the code from Go to C.
package main import ( "fmt" "sort" ) func distinctSortedUnion(ll [][]int) []int { var res []int for _, l := range ll { res = append(res, l...) } set := make(map[int]bool) for _, e := range res { set[e] = true } res = res[:0] for key := range set { res = append(res, key) } sort.Ints(res) return res } func main() { ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}} fmt.Println("Distinct sorted union of", ll, "is:") fmt.Println(distinctSortedUnion(ll)) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define COUNTOF(a) (sizeof(a)/sizeof(a[0])) void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int icompare(const void* p1, const void* p2) { const int* ip1 = p1; const int* ip2 = p2; return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0); } size_t unique(int* array, size_t len) { size_t out_index = 0; int prev; for (size_t i = 0; i < len; ++i) { if (i == 0 || prev != array[i]) array[out_index++] = array[i]; prev = array[i]; } return out_index; } int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) { size_t len = 0; for (size_t i = 0; i < count; ++i) len += lengths[i]; int* array = xmalloc(len * sizeof(int)); for (size_t i = 0, offset = 0; i < count; ++i) { memcpy(array + offset, arrays[i], lengths[i] * sizeof(int)); offset += lengths[i]; } qsort(array, len, sizeof(int), icompare); *size = unique(array, len); return array; } void print(const int* array, size_t len) { printf("["); for (size_t i = 0; i < len; ++i) { if (i > 0) printf(", "); printf("%d", array[i]); } printf("]\n"); } int main() { const int a[] = {5, 1, 3, 8, 9, 4, 8, 7}; const int b[] = {3, 5, 9, 8, 4}; const int c[] = {1, 3, 7, 9}; size_t len = 0; const int* arrays[] = {a, b, c}; size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)}; int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len); print(sorted, len); free(sorted); return 0; }
Please provide an equivalent version of this Go code in C.
package main import ( "fmt" "sort" ) func distinctSortedUnion(ll [][]int) []int { var res []int for _, l := range ll { res = append(res, l...) } set := make(map[int]bool) for _, e := range res { set[e] = true } res = res[:0] for key := range set { res = append(res, key) } sort.Ints(res) return res } func main() { ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}} fmt.Println("Distinct sorted union of", ll, "is:") fmt.Println(distinctSortedUnion(ll)) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define COUNTOF(a) (sizeof(a)/sizeof(a[0])) void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int icompare(const void* p1, const void* p2) { const int* ip1 = p1; const int* ip2 = p2; return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0); } size_t unique(int* array, size_t len) { size_t out_index = 0; int prev; for (size_t i = 0; i < len; ++i) { if (i == 0 || prev != array[i]) array[out_index++] = array[i]; prev = array[i]; } return out_index; } int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) { size_t len = 0; for (size_t i = 0; i < count; ++i) len += lengths[i]; int* array = xmalloc(len * sizeof(int)); for (size_t i = 0, offset = 0; i < count; ++i) { memcpy(array + offset, arrays[i], lengths[i] * sizeof(int)); offset += lengths[i]; } qsort(array, len, sizeof(int), icompare); *size = unique(array, len); return array; } void print(const int* array, size_t len) { printf("["); for (size_t i = 0; i < len; ++i) { if (i > 0) printf(", "); printf("%d", array[i]); } printf("]\n"); } int main() { const int a[] = {5, 1, 3, 8, 9, 4, 8, 7}; const int b[] = {3, 5, 9, 8, 4}; const int c[] = {1, 3, 7, 9}; size_t len = 0; const int* arrays[] = {a, b, c}; size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)}; int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len); print(sorted, len); free(sorted); return 0; }
Rewrite the snippet below in C so it works the same as the original Go code.
package main import "fmt" const ( m = iota c cm cmc ) func ncs(s []int) [][]int { if len(s) < 3 { return nil } return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...) } var skip = []int{m, cm, cm, cmc} var incl = []int{c, c, cmc, cmc} func n2(ss, tail []int, seq int) [][]int { if len(tail) == 0 { if seq != cmc { return nil } return [][]int{ss} } return append(n2(append([]int{}, ss...), tail[1:], skip[seq]), n2(append(ss, tail[0]), tail[1:], incl[seq])...) } func main() { ss := ncs([]int{1, 2, 3, 4}) fmt.Println(len(ss), "non-continuous subsequences:") for _, s := range ss { fmt.Println(" ", s) } }
#include <assert.h> #include <stdio.h> int main(int c, char **v) { unsigned int n = 1 << (c - 1), i = n, j, k; assert(n); while (i--) { if (!(i & (i + (i & -(int)i)))) continue; for (j = n, k = 1; j >>= 1; k++) if (i & j) printf("%s ", v[k]); putchar('\n'); } return 0; }
Convert this Go block to C, preserving its control flow and logic.
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >= 1; j-- { tmp := f2.String() f2.WriteString(f1.String()) f1.Reset() f1.WriteString(tmp) } return f2.String() } func draw(dc *gg.Context, x, y, dx, dy float64, wf string) { for i, c := range wf { dc.DrawLine(x, y, x+dx, y+dy) x += dx y += dy if c == '0' { tx := dx dx = dy if i%2 == 0 { dx = -dy } dy = -tx if i%2 == 0 { dy = tx } } } } func main() { dc := gg.NewContext(450, 620) dc.SetRGB(0, 0, 0) dc.Clear() wf := wordFractal(23) draw(dc, 20, 20, 1, 0, wf) dc.SetRGB(0, 1, 0) dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("fib_wordfractal.png") }
#include <stdio.h> int main(void) { puts( "%!PS-Adobe-3.0 EPSF\n" "%%BoundingBox: -10 -10 400 565\n" "/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n" "/b{a 90 rotate}def"); char i; for (i = 'c'; i <= 'z'; i++) printf("/%c{%c %c}def\n", i, i-1, i-2); puts("0 setlinewidth z showpage\n%%EOF"); return 0; }
Write the same algorithm in C as shown in this Go implementation.
package main import "fmt" func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { c := sieve(1e10 - 1) limit := 10 start := 3 twins := 0 for i := 1; i < 11; i++ { for i := start; i < limit; i += 2 { if !c[i] && !c[i-2] { twins++ } } fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins)) start = limit + 1 limit *= 10 } }
#include <stdbool.h> #include <stdint.h> #include <stdio.h> bool isPrime(int64_t n) { int64_t i; 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; if (n % 7 == 0) return n == 7; if (n % 11 == 0) return n == 11; if (n % 13 == 0) return n == 13; if (n % 17 == 0) return n == 17; if (n % 19 == 0) return n == 19; for (i = 23; i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } int countTwinPrimes(int limit) { int count = 0; int64_t p3 = true, p2 = true, p1 = false; int64_t i; for (i = 5; i <= limit; i++) { p3 = p2; p2 = p1; p1 = isPrime(i); if (p3 && p1) { count++; } } return count; } void test(int limit) { int count = countTwinPrimes(limit); printf("Number of twin prime pairs less than %d is %d\n", limit, count); } int main() { test(10); test(100); test(1000); test(10000); test(100000); test(1000000); test(10000000); test(100000000); return 0; }
Write the same code in C as shown below in Go.
package main import ( "fmt" "math" "math/cmplx" ) func main() { for n := 2; n <= 5; n++ { fmt.Printf("%d roots of 1:\n", n) for _, r := range roots(n) { fmt.Printf(" %18.15f\n", r) } } } func roots(n int) []complex128 { r := make([]complex128, n) for i := 0; i < n; i++ { r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n)) } return r }
#include <stdio.h> #include <math.h> int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i; for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a), s = sin(a); if (c) printf("%.2g", c); printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s); printf(i == n - 1 ?"\n":", "); } return 0; }
Ensure the translated C code behaves exactly like the original Go snippet.
package main import "fmt" func d(b byte) byte { if b < '0' || b > '9' { panic("digit 0-9 expected") } return b - '0' } func add(x, y string) string { if len(y) > len(x) { x, y = y, x } b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { if i <= len(y) { c += d(y[len(y)-i]) } s := d(x[len(x)-i]) + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mulDigit(x string, y byte) string { if y == '0' { return "0" } y = d(y) b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { s := d(x[len(x)-i])*y + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mul(x, y string) string { result := mulDigit(x, y[len(y)-1]) for i, zeros := 2, ""; i <= len(y); i++ { zeros += "0" result = add(result, mulDigit(x, y[len(y)-i])+zeros) } return result } const n = "18446744073709551616" func main() { fmt.Println(mul(n, n)) }
#include <stdio.h> #include <string.h> void longmulti(const char *a, const char *b, char *c) { int i = 0, j = 0, k = 0, n, carry; int la, lb; if (!strcmp(a, "0") || !strcmp(b, "0")) { c[0] = '0', c[1] = '\0'; return; } if (a[0] == '-') { i = 1; k = !k; } if (b[0] == '-') { j = 1; k = !k; } if (i || j) { if (k) c[0] = '-'; longmulti(a + i, b + j, c + k); return; } la = strlen(a); lb = strlen(b); memset(c, '0', la + lb); c[la + lb] = '\0'; # define I(a) (a - '0') for (i = la - 1; i >= 0; i--) { for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) { n = I(a[i]) * I(b[j]) + I(c[k]) + carry; carry = n / 10; c[k] = (n % 10) + '0'; } c[k] += carry; } # undef I if (c[0] == '0') memmove(c, c + 1, la + lb); return; } int main() { char c[1024]; longmulti("-18446744073709551616", "-18446744073709551616", c); printf("%s\n", c); return 0; }
Write the same code in C as shown below in Go.
package main import ( "fmt" "math/big" ) var big1 = new(big.Int).SetUint64(1) func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1) e1 := new(big.Int).SetUint64(1) e2 := new(big.Int) f1 := new(big.Int) f2 := new(big.Int).SetUint64(1) t := new(big.Int) u := new(big.Int) a := new(big.Int) b := new(big.Int) for { t.Mul(r, z) y.Sub(t, y) t.Mul(y, y) t.Sub(n, t) z.Quo(t, z) t.Add(x, y) r.Quo(t, z) u.Set(e1) e1.Set(e2) t.Mul(r, e2) e2.Add(t, u) u.Set(f1) f1.Set(f2) t.Mul(r, f2) f2.Add(t, u) t.Mul(x, f2) a.Add(e2, t) b.Set(f2) t.Mul(a, a) u.Mul(n, b) u.Mul(u, b) t.Sub(t, u) if t.Cmp(big1) == 0 { return a, b } } } func main() { ns := []uint64{61, 109, 181, 277} for _, n := range ns { x, y := solvePell(n) fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y) } }
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { return makePair(1, 0); } else { int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } } return makePair(a, b); } } void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); } int main() { test(61); test(109); test(181); test(277); return 0; }
Change the following Go code into C without altering its purpose.
package main import ( "fmt" "math/big" ) var big1 = new(big.Int).SetUint64(1) func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1) e1 := new(big.Int).SetUint64(1) e2 := new(big.Int) f1 := new(big.Int) f2 := new(big.Int).SetUint64(1) t := new(big.Int) u := new(big.Int) a := new(big.Int) b := new(big.Int) for { t.Mul(r, z) y.Sub(t, y) t.Mul(y, y) t.Sub(n, t) z.Quo(t, z) t.Add(x, y) r.Quo(t, z) u.Set(e1) e1.Set(e2) t.Mul(r, e2) e2.Add(t, u) u.Set(f1) f1.Set(f2) t.Mul(r, f2) f2.Add(t, u) t.Mul(x, f2) a.Add(e2, t) b.Set(f2) t.Mul(a, a) u.Mul(n, b) u.Mul(u, b) t.Sub(t, u) if t.Cmp(big1) == 0 { return a, b } } } func main() { ns := []uint64{61, 109, 181, 277} for _, n := range ns { x, y := solvePell(n) fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y) } }
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { return makePair(1, 0); } else { int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } } return makePair(a, b); } } void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); } int main() { test(61); test(109); test(181); test(277); return 0; }
Write the same code in C as shown below in Go.
package main import ( "bufio" "bytes" "fmt" "math/rand" "os" "strings" "time" ) func main() { fmt.Println(`Cows and Bulls Guess four digit number of unique digits in the range 1 to 9. A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bull.`) pat := make([]byte, 4) rand.Seed(time.Now().Unix()) r := rand.Perm(9) for i := range pat { pat[i] = '1' + byte(r[i]) } valid := []byte("123456789") guess: for in := bufio.NewReader(os.Stdin); ; { fmt.Print("Guess: ") guess, err := in.ReadString('\n') if err != nil { fmt.Println("\nSo, bye.") return } guess = strings.TrimSpace(guess) if len(guess) != 4 { fmt.Println("Please guess a four digit number.") continue } var cows, bulls int for ig, cg := range guess { if strings.IndexRune(guess[:ig], cg) >= 0 { fmt.Printf("Repeated digit: %c\n", cg) continue guess } switch bytes.IndexByte(pat, byte(cg)) { case -1: if bytes.IndexByte(valid, byte(cg)) == -1 { fmt.Printf("Invalid digit: %c\n", cg) continue guess } default: cows++ case ig: bulls++ } } fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) if bulls == 4 { fmt.Println("You got it.") return } } }
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdbool.h> #include <curses.h> #include <string.h> #define MAX_NUM_TRIES 72 #define LINE_BEGIN 7 #define LAST_LINE 18 int yp=LINE_BEGIN, xp=0; char number[5]; char guess[5]; #define MAX_STR 256 void mvaddstrf(int y, int x, const char *fmt, ...) { va_list args; char buf[MAX_STR]; va_start(args, fmt); vsprintf(buf, fmt, args); move(y, x); clrtoeol(); addstr(buf); va_end(args); } void ask_for_a_number() { int i=0; char symbols[] = "123456789"; move(5,0); clrtoeol(); addstr("Enter four digits: "); while(i<4) { int c = getch(); if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) { addch(c); symbols[c-'1'] = 0; guess[i++] = c; } } } void choose_the_number() { int i=0, j; char symbols[] = "123456789"; while(i<4) { j = rand() % 9; if ( symbols[j] != 0 ) { number[i++] = symbols[j]; symbols[j] = 0; } } }
Generate a C translation of this Go snippet without changing its computational steps.
package main import "fmt" func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) bubblesort(list) fmt.Println("sorted! ", list) } func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
#include <stdio.h> void bubble_sort (int *a, int n) { int i, t, j = n, s = 1; while (s) { s = 0; for (i = 1; i < j; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } j--; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); bubble_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Please provide an equivalent version of this Go code in C.
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Go version.
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
#include <stdio.h> int main(int argc, char **argv) { FILE *in, *out; int c; in = fopen("input.txt", "r"); if (!in) { fprintf(stderr, "Error opening input.txt for reading.\n"); return 1; } out = fopen("output.txt", "w"); if (!out) { fprintf(stderr, "Error opening output.txt for writing.\n"); fclose(in); return 1; } while ((c = fgetc(in)) != EOF) { fputc(c, out); } fclose(out); fclose(in); return 0; }
Convert this Go snippet to C and keep its semantics consistent.
package main import "fmt" func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d + %d = %d\n", a, b, a+b) fmt.Printf("%d - %d = %d\n", a, b, a-b) fmt.Printf("%d * %d = %d\n", a, b, a*b) fmt.Printf("%d / %d = %d\n", a, b, a/b) fmt.Printf("%d %% %d = %d\n", a, b, a%b) }
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a, b; if (argc < 3) exit(1); b = atoi(argv[--argc]); if (b == 0) exit(2); a = atoi(argv[--argc]); printf("a+b = %d\n", a+b); printf("a-b = %d\n", a-b); printf("a*b = %d\n", a*b); printf("a/b = %d\n", a/b); printf("a%%b = %d\n", a%b); return 0; }
Ensure the translated C code behaves exactly like the original Go snippet.
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { m := mat.NewDense(2, 3, []float64{ 1, 2, 3, 4, 5, 6, }) fmt.Println(mat.Formatted(m)) fmt.Println() fmt.Println(mat.Formatted(m.T())) }
#include <stdio.h> void transpose(void *dest, void *src, int src_h, int src_w) { int i, j; double (*d)[src_h] = dest, (*s)[src_w] = src; for (i = 0; i < src_h; i++) for (j = 0; j < src_w; j++) d[j][i] = s[i][j]; } int main() { int i, j; double a[3][5] = {{ 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 1, 0, 0, 0, 42}}; double b[5][3]; transpose(b, a, 3, 5); for (i = 0; i < 5; i++) for (j = 0; j < 3; j++) printf("%g%c", b[i][j], j == 2 ? '\n' : ' '); return 0; }
Rewrite the snippet below in C so it works the same as the original Go code.
package main import "fmt" func a(k int, x1, x2, x3, x4, x5 func() int) int { var b func() int b = func() int { k-- return a(k, b, x1, x2, x3, x4) } if k <= 0 { return x4() + x5() } return b() } func main() { x := func(i int) func() int { return func() int { return i } } fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0))) }
#include <stdio.h> #include <stdlib.h> typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG; int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; } int eval(ARG* a) { return a->fn(a); } #define MAKE_ARG(...) (&(ARG){__VA_ARGS__}) #define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__) int A(ARG*); int B(ARG* a) { int k = *a->k -= 1; return A(FUN(a, a->x1, a->x2, a->x3, a->x4)); } int A(ARG* a) { return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a); } int main(int argc, char **argv) { int k = argc == 2 ? strtol(argv[1], 0, 0) : 10; printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1), MAKE_ARG(f1), MAKE_ARG(f0)))); return 0; }
Change the programming language of this snippet from Go to C without modifying what it does.
package main import "fmt" func a(v bool) bool { fmt.Print("a") return v } func b(v bool) bool { fmt.Print("b") return v } func test(i, j bool) { fmt.Printf("Testing a(%t) && b(%t)\n", i, j) fmt.Print("Trace: ") fmt.Println("\nResult:", a(i) && b(j)) fmt.Printf("Testing a(%t) || b(%t)\n", i, j) fmt.Print("Trace: ") fmt.Println("\nResult:", a(i) || b(j)) fmt.Println("") } func main() { test(false, false) test(false, true) test(true, false) test(true, true) }
#include <stdio.h> #include <stdbool.h> bool a(bool in) { printf("I am a\n"); return in; } bool b(bool in) { printf("I am b\n"); return in; } #define TEST(X,Y,O) \ do { \ x = a(X) O b(Y); \ printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \ } while(false); int main() { bool x; TEST(false, true, &&); TEST(true, false, ||); TEST(true, false, &&); TEST(false, false, ||); return 0; }
Port the provided Go code into C while preserving the original functionality.
package main import ( "flag" "fmt" "runtime/debug" ) func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) } func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }