Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
DEFINT A(1 to 4) = {1, 2, 3, 4} DEFINT B(1 to 4) = {10, 20, 30, 40} Redim A(1 to 8) as integer MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
String[] fruits = ["apples", "oranges"]; String[] grains = ["wheat", "corn"]; String[] all = fruits + grains;
Generate a Java translation of this VB snippet without changing its computational steps.
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
import java.util.Scanner; public class GetInput { public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); System.out.print("Enter a string: "); String str = s.nextLine(); System.out.print("Enter an integer: "); int i = Integer.parseInt(s.next()); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
Write a version of this VB function in Java with identical behavior.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
Translate this program into Java but keep the logic exactly as in VB.
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _ "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _ "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _ "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
package hu.pj.alg.test; import hu.pj.alg.ZeroOneKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class ZeroOneKnapsackForTourists { public ZeroOneKnapsackForTourists() { ZeroOneKnapsack zok = new ZeroOneKnapsack(400); zok.add("map", 9, 150); zok.add("compass", 13, 35); zok.add("water", 153, 200); zok.add("sandwich", 50, 160); zok.add("glucose", 15, 60); zok.add("tin", 68, 45); zok.add("banana", 27, 60); zok.add("apple", 39, 40); zok.add("cheese", 23, 30); zok.add("beer", 52, 10); zok.add("suntan cream", 11, 70); zok.add("camera", 32, 30); zok.add("t-shirt", 24, 15); zok.add("trousers", 48, 10); zok.add("umbrella", 73, 40); zok.add("waterproof trousers", 42, 70); zok.add("waterproof overclothes", 43, 75); zok.add("note-case", 22, 80); zok.add("sunglasses", 7, 20); zok.add("towel", 18, 12); zok.add("socks", 4, 50); zok.add("book", 30, 10); List<Item> itemList = zok.calcSolution(); if (zok.isCalculated()) { NumberFormat nf = NumberFormat.getInstance(); System.out.println( "Maximal weight = " + nf.format(zok.getMaxWeight() / 100.0) + " kg" ); System.out.println( "Total weight of solution = " + nf.format(zok.getSolutionWeight() / 100.0) + " kg" ); System.out.println( "Total value = " + zok.getProfit() ); System.out.println(); System.out.println( "You can carry the following materials " + "in the knapsack:" ); for (Item item : itemList) { if (item.getInKnapsack() == 1) { System.out.format( "%1$-23s %2$-3s %3$-5s %4$-15s \n", item.getName(), item.getWeight(), "dag ", "(value = " + item.getValue() + ")" ); } } } else { System.out.println( "The problem is not solved. " + "Maybe you gave wrong data." ); } } public static void main(String[] args) { new ZeroOneKnapsackForTourists(); } }
Translate the given VB code snippet into Java without altering its behavior.
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _ "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _ "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _ "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
package hu.pj.alg.test; import hu.pj.alg.ZeroOneKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class ZeroOneKnapsackForTourists { public ZeroOneKnapsackForTourists() { ZeroOneKnapsack zok = new ZeroOneKnapsack(400); zok.add("map", 9, 150); zok.add("compass", 13, 35); zok.add("water", 153, 200); zok.add("sandwich", 50, 160); zok.add("glucose", 15, 60); zok.add("tin", 68, 45); zok.add("banana", 27, 60); zok.add("apple", 39, 40); zok.add("cheese", 23, 30); zok.add("beer", 52, 10); zok.add("suntan cream", 11, 70); zok.add("camera", 32, 30); zok.add("t-shirt", 24, 15); zok.add("trousers", 48, 10); zok.add("umbrella", 73, 40); zok.add("waterproof trousers", 42, 70); zok.add("waterproof overclothes", 43, 75); zok.add("note-case", 22, 80); zok.add("sunglasses", 7, 20); zok.add("towel", 18, 12); zok.add("socks", 4, 50); zok.add("book", 30, 10); List<Item> itemList = zok.calcSolution(); if (zok.isCalculated()) { NumberFormat nf = NumberFormat.getInstance(); System.out.println( "Maximal weight = " + nf.format(zok.getMaxWeight() / 100.0) + " kg" ); System.out.println( "Total weight of solution = " + nf.format(zok.getSolutionWeight() / 100.0) + " kg" ); System.out.println( "Total value = " + zok.getProfit() ); System.out.println(); System.out.println( "You can carry the following materials " + "in the knapsack:" ); for (Item item : itemList) { if (item.getInKnapsack() == 1) { System.out.format( "%1$-23s %2$-3s %3$-5s %4$-15s \n", item.getName(), item.getWeight(), "dag ", "(value = " + item.getValue() + ")" ); } } } else { System.out.println( "The problem is not solved. " + "Maybe you gave wrong data." ); } } public static void main(String[] args) { new ZeroOneKnapsackForTourists(); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
Imports System.Math Module Module1 Const MAXPRIME = 99 Const MAXPARENT = 99 Const NBRCHILDREN = 547100 Public Primes As New Collection() Public PrimesR As New Collection() Public Ancestors As New Collection() Public Parents(MAXPARENT + 1) As Integer Public CptDescendants(MAXPARENT + 1) As Integer Public Children(NBRCHILDREN) As ChildStruct Public iChildren As Integer Public Delimiter As String = ", " Public Structure ChildStruct Public Child As Long Public pLower As Integer Public pHigher As Integer End Structure Sub Main() Dim Parent As Short Dim Sum As Short Dim i As Short Dim TotDesc As Integer = 0 Dim MidPrime As Integer If GetPrimes(Primes, MAXPRIME) = vbFalse Then Return End If For i = Primes.Count To 1 Step -1 PrimesR.Add(Primes.Item(i)) Next MidPrime = PrimesR.Item(1) / 2 For Each Prime In PrimesR Parents(Prime) = InsertChild(Parents(Prime), Prime) CptDescendants(Prime) += 1 If Prime > MidPrime Then Continue For End If For Parent = 1 To MAXPARENT Sum = Parent + Prime If Sum > MAXPARENT Then Exit For End If If Parents(Parent) Then InsertPreorder(Parents(Parent), Sum, Prime) CptDescendants(Sum) += CptDescendants(Parent) End If Next Next RemoveFalseChildren() If MAXPARENT > MAXPRIME Then If GetPrimes(Primes, MAXPARENT) = vbFalse Then Return End If End If FileOpen(1, "Ancestors.txt", OpenMode.Output) For Parent = 1 To MAXPARENT GetAncestors(Parent) PrintLine(1, "[" & Parent.ToString & "] Level: " & Ancestors.Count.ToString) If Ancestors.Count Then Print(1, "Ancestors: " & Ancestors.Item(1).ToString) For i = 2 To Ancestors.Count Print(1, ", " & Ancestors.Item(i).ToString) Next PrintLine(1) Ancestors.Clear() Else PrintLine(1, "Ancestors: None") End If If CptDescendants(Parent) Then PrintLine(1, "Descendants: " & CptDescendants(Parent).ToString) Delimiter = "" PrintDescendants(Parents(Parent)) PrintLine(1) TotDesc += CptDescendants(Parent) Else PrintLine(1, "Descendants: None") End If PrintLine(1) Next Primes.Clear() PrimesR.Clear() PrintLine(1, "Total descendants " & TotDesc.ToString) PrintLine(1) FileClose(1) End Sub Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short) Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime) If Children(_index).pLower Then InsertPreorder(Children(_index).pLower, _sum, _prime) End If If Children(_index).pHigher Then InsertPreorder(Children(_index).pHigher, _sum, _prime) End If Return Nothing End Function Function InsertChild(_index As Integer, _child As Long) As Integer If _index Then If _child <= Children(_index).Child Then Children(_index).pLower = InsertChild(Children(_index).pLower, _child) Else Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child) End If Else iChildren += 1 _index = iChildren Children(_index).Child = _child Children(_index).pLower = 0 Children(_index).pHigher = 0 End If Return _index End Function Function RemoveFalseChildren() Dim Exclusions As New Collection Exclusions.Add(4) For Each Prime In Primes Exclusions.Add(Prime) Next For Each ex In Exclusions Parents(ex) = Children(Parents(ex)).pHigher CptDescendants(ex) -= 1 Next Exclusions.Clear() Return Nothing End Function Function GetAncestors(_child As Short) Dim Child As Short = _child Dim Parent As Short = 0 For Each Prime In Primes If Child = 1 Then Exit For End If While Child Mod Prime = 0 Child /= Prime Parent += Prime End While Next If Parent = _child Or _child = 1 Then Return Nothing End If GetAncestors(Parent) Ancestors.Add(Parent) Return Nothing End Function Function PrintDescendants(_index As Integer) If Children(_index).pLower Then PrintDescendants(Children(_index).pLower) End If Print(1, Delimiter.ToString & Children(_index).Child.ToString) Delimiter = ", " If Children(_index).pHigher Then PrintDescendants(Children(_index).pHigher) End If Return Nothing End Function Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean Dim Value As Integer = 3 Dim Max As Integer Dim Prime As Integer If _maxPrime < 2 Then Return vbFalse End If _primes.Add(2) While Value <= _maxPrime Max = Floor(Sqrt(Value)) For Each Prime In _primes If Prime > Max Then _primes.Add(Value) Exit For End If If Value Mod Prime = 0 Then Exit For End If Next Value += 2 End While Return vbTrue End Function End Module
import java.io.*; import java.util.*; public class PrimeDescendants { public static void main(String[] args) { try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) { printPrimeDesc(writer, 100); } catch (IOException ex) { ex.printStackTrace(); } } private static void printPrimeDesc(Writer writer, int limit) throws IOException { List<Long> primes = findPrimes(limit); List<Long> ancestor = new ArrayList<>(limit); List<List<Long>> descendants = new ArrayList<>(limit); for (int i = 0; i < limit; ++i) { ancestor.add(Long.valueOf(0)); descendants.add(new ArrayList<Long>()); } for (Long prime : primes) { int p = prime.intValue(); descendants.get(p).add(prime); for (int i = 0; i + p < limit; ++i) { int s = i + p; for (Long n : descendants.get(i)) { Long prod = n * p; descendants.get(s).add(prod); if (prod < limit) ancestor.set(prod.intValue(), Long.valueOf(s)); } } } int totalDescendants = 0; for (int i = 1; i < limit; ++i) { List<Long> ancestors = getAncestors(ancestor, i); writer.write("[" + i + "] Level: " + ancestors.size() + "\n"); writer.write("Ancestors: "); Collections.sort(ancestors); print(writer, ancestors); writer.write("Descendants: "); List<Long> desc = descendants.get(i); if (!desc.isEmpty()) { Collections.sort(desc); if (desc.get(0) == i) desc.remove(0); } writer.write(desc.size() + "\n"); totalDescendants += desc.size(); if (!desc.isEmpty()) print(writer, desc); writer.write("\n"); } writer.write("Total descendants: " + totalDescendants + "\n"); } private static List<Long> findPrimes(int limit) { boolean[] isprime = new boolean[limit]; Arrays.fill(isprime, true); isprime[0] = isprime[1] = false; for (int p = 2; p * p < limit; ++p) { if (isprime[p]) { for (int i = p * p; i < limit; i += p) isprime[i] = false; } } List<Long> primes = new ArrayList<>(); for (int p = 2; p < limit; ++p) { if (isprime[p]) primes.add(Long.valueOf(p)); } return primes; } private static List<Long> getAncestors(List<Long> ancestor, int n) { List<Long> result = new ArrayList<>(); for (Long a = ancestor.get(n); a != 0 && a != n; ) { n = a.intValue(); a = ancestor.get(n); result.add(Long.valueOf(n)); } return result; } private static void print(Writer writer, List<Long> list) throws IOException { if (list.isEmpty()) { writer.write("none\n"); return; } int i = 0; writer.write(String.valueOf(list.get(i++))); for (; i != list.size(); ++i) writer.write(", " + list.get(i)); writer.write("\n"); } }
Maintain the same structure and functionality when rewriting this code in Java.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.of; import static java.util.stream.Collectors.toList; import java.util.List; public class CartesianProduct { public List<?> product(List<?>... a) { if (a.length >= 2) { List<?> product = a[0]; for (int i = 1; i < a.length; i++) { product = product(product, a[i]); } return product; } return emptyList(); } private <A, B> List<?> product(List<A> a, List<B> b) { return of(a.stream() .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList())) .flatMap(List::stream) .collect(toList())).orElse(emptyList()); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.of; import static java.util.stream.Collectors.toList; import java.util.List; public class CartesianProduct { public List<?> product(List<?>... a) { if (a.length >= 2) { List<?> product = a[0]; for (int i = 1; i < a.length; i++) { product = product(product, a[i]); } return product; } return emptyList(); } private <A, B> List<?> product(List<A> a, List<B> b) { return of(a.stream() .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList())) .flatMap(List::stream) .collect(toList())).orElse(emptyList()); } }
Generate a Java translation of this VB snippet without changing its computational steps.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.of; import static java.util.stream.Collectors.toList; import java.util.List; public class CartesianProduct { public List<?> product(List<?>... a) { if (a.length >= 2) { List<?> product = a[0]; for (int i = 1; i < a.length; i++) { product = product(product, a[i]); } return product; } return emptyList(); } private <A, B> List<?> product(List<A> a, List<B> b) { return of(a.stream() .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList())) .flatMap(List::stream) .collect(toList())).orElse(emptyList()); } }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
dim _proper_divisors(100) sub proper_divisors(n) dim i dim _proper_divisors_count = 0 if n <> 1 then for i = 1 to (n \ 2) if n %% i = 0 then _proper_divisors_count = _proper_divisors_count + 1 _proper_divisors(_proper_divisors_count) = i end if next end if return _proper_divisors_count end sub sub show_proper_divisors(n, tabbed) dim cnt = proper_divisors(n) print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) "; dim j for j = 1 to cnt if tabbed then print str$(_proper_divisors(j)), else print str$(_proper_divisors(j)); end if if (j < cnt) then print ","; next print end sub dim i for i = 1 to 10 show_proper_divisors(i, false) next dim c dim maxindex = 0 dim maxlength = 0 for t = 1 to 20000 c = proper_divisors(t) if c > maxlength then maxindex = t maxlength = c end if next print "A maximum at "; show_proper_divisors(maxindex, false)
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Proper{ public static List<Integer> properDivs(int n){ List<Integer> divs = new LinkedList<Integer>(); if(n == 1) return divs; divs.add(1); for(int x = 2; x < n; x++){ if(n % x == 0) divs.add(x); } Collections.sort(divs); return divs; } public static void main(String[] args){ for(int x = 1; x <= 10; x++){ System.out.println(x + ": " + properDivs(x)); } int x = 0, count = 0; for(int n = 1; n <= 20000; n++){ if(properDivs(n).size() > count){ x = n; count = properDivs(n).size(); } } System.out.println(x + ": " + count); } }
Maintain the same structure and functionality when rewriting this code in Java.
Module XMLOutput Sub Main() Dim charRemarks As New Dictionary(Of String, String) charRemarks.Add("April", "Bubbly: I charRemarks.Add("Tam O charRemarks.Add("Emily", "Short & shrift") Dim xml = <CharacterRemarks> <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %> </CharacterRemarks> Console.WriteLine(xml) End Sub End Module
import java.io.StringWriter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class XmlCreation { private static final String[] names = {"April", "Tam O'Shanter", "Emily"}; private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"}; public static void main(String[] args) { try { final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); final Element root = doc.createElement("CharacterRemarks"); doc.appendChild(root); for(int i = 0; i < names.length; i++) { final Element character = doc.createElement("Character"); root.appendChild(character); character.setAttribute("name", names[i]); character.appendChild(doc.createTextNode(remarks[i])); } final Source source = new DOMSource(doc); final StringWriter buffer = new StringWriter(); final Result result = new StreamResult(buffer); final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent", "yes"); transformer.transform(source, result); System.out.println(buffer.toString()); } catch (Exception e) { e.printStackTrace(); } } }
Port the provided VB code into Java while preserving the original functionality.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; import javax.swing.JFrame; public class Plot2d extends JApplet { double[] xi; double[] yi; public Plot2d(double[] x, double[] y) { this.xi = x; this.yi = y; } public static double max(double[] t) { double maximum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] > maximum) { maximum = t[i]; } } return maximum; } public static double min(double[] t) { double minimum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] < minimum) { minimum = t[i]; } } return minimum; } public void init() { setBackground(Color.white); setForeground(Color.white); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.black); int x0 = 70; int y0 = 10; int xm = 670; int ym = 410; int xspan = xm - x0; int yspan = ym - y0; double xmax = max(xi); double xmin = min(xi); double ymax = max(yi); double ymin = min(yi); g2.draw(new Line2D.Double(x0, ym, xm, ym)); g2.draw(new Line2D.Double(x0, ym, x0, y0)); for (int j = 0; j < 5; j++) { int interv = 4; g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20); g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)), ym - j * yspan / interv + y0 - 5); g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5)); g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0)); } for (int i = 0; i < xi.length; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); g2.drawString("o", x0 + f - 3, h + 14); } for (int i = 0; i < xi.length - 1; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin)); g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0)); } } public static void main(String args[]) { JFrame f = new JFrame("ShapesDemo2D"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09}; JApplet applet = new Plot2d(r, t); f.getContentPane().add("Center", applet); applet.init(); f.pack(); f.setSize(new Dimension(720, 480)); f.show(); } }
Please provide an equivalent version of this VB code in Java.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; import javax.swing.JFrame; public class Plot2d extends JApplet { double[] xi; double[] yi; public Plot2d(double[] x, double[] y) { this.xi = x; this.yi = y; } public static double max(double[] t) { double maximum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] > maximum) { maximum = t[i]; } } return maximum; } public static double min(double[] t) { double minimum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] < minimum) { minimum = t[i]; } } return minimum; } public void init() { setBackground(Color.white); setForeground(Color.white); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.black); int x0 = 70; int y0 = 10; int xm = 670; int ym = 410; int xspan = xm - x0; int yspan = ym - y0; double xmax = max(xi); double xmin = min(xi); double ymax = max(yi); double ymin = min(yi); g2.draw(new Line2D.Double(x0, ym, xm, ym)); g2.draw(new Line2D.Double(x0, ym, x0, y0)); for (int j = 0; j < 5; j++) { int interv = 4; g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20); g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)), ym - j * yspan / interv + y0 - 5); g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5)); g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0)); } for (int i = 0; i < xi.length; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); g2.drawString("o", x0 + f - 3, h + 14); } for (int i = 0; i < xi.length - 1; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin)); g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0)); } } public static void main(String args[]) { JFrame f = new JFrame("ShapesDemo2D"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09}; JApplet applet = new Plot2d(r, t); f.getContentPane().add("Center", applet); applet.init(); f.pack(); f.setSize(new Dimension(720, 480)); f.show(); } }
Generate a Java translation of this VB snippet without changing its computational steps.
text = "I need more coffee!!!" Set regex = New RegExp regex.Global = True regex.Pattern = "\s" If regex.Test(text) Then WScript.StdOut.Write regex.Replace(text,vbCrLf) Else WScript.StdOut.Write "No matching pattern" End If
String str = "I am a string"; if (str.matches(".*string")) { System.out.println("ends with 'string'"); }
Convert this VB block to Java, preserving its control flow and logic.
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
import java.util.HashMap; public static void main(String[] args){ String[] keys= {"a", "b", "c"}; int[] vals= {1, 2, 3}; HashMap<String, Integer> hash= new HashMap<String, Integer>(); for(int i= 0; i < keys.length; i++){ hash.put(keys[i], vals[i]); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
Public Class Main Inherits System.Windows.Forms.Form Public Sub New() Me.FormBorderStyle = FormBorderStyle.None Me.WindowState = FormWindowState.Maximized End Sub Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load Dim Index As Integer Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White} Dim Height = (Me.ClientSize.Height / 4) + 1 For y = 1 To 4 Dim Top = Me.ClientSize.Height / 4 * (y - 1) For x = 0 To Me.ClientSize.Width Step y If Index = 6 Then Index = 0 Else Index += 1 Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)}) Next Next End Sub End Class
import java.awt.*; import static java.awt.Color.*; import javax.swing.*; public class ColourPinstripeDisplay extends JPanel { final static Color[] palette = {black, red, green, blue, magenta,cyan, yellow, white}; final int bands = 4; public ColourPinstripeDisplay() { setPreferredSize(new Dimension(900, 600)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int h = getHeight(); for (int b = 1; b <= bands; b++) { for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) { g.setColor(palette[colIndex % palette.length]); g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands)); } } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("ColourPinstripeDisplay"); f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Maintain the same structure and functionality when rewriting this code in Java.
Function cocktailShakerSort(ByVal A As Variant) As Variant beginIdx = LBound(A) endIdx = UBound(A) - 1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newEndIdx = ii End If Next ii endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newBeginIdx = ii End If Next ii beginIdx = newBeginIdx + 1 Loop cocktailShakerSort = A End Function Public Sub main() Dim B(20) As Variant For i = LBound(B) To UBound(B) B(i) = Int(Rnd() * 100) Next i Debug.Print Join(B, ", ") Debug.Print Join(cocktailShakerSort(B), ", ") End Sub
import java.util.*; public class CocktailSort { public static void main(String[] args) { Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 }; System.out.println("before: " + Arrays.toString(array)); cocktailSort(array); System.out.println("after: " + Arrays.toString(array)); } public static void cocktailSort(Object[] array) { int begin = 0; int end = array.length; if (end == 0) return; for (--end; begin < end; ) { int new_begin = end; int new_end = begin; for (int i = begin; i < end; ++i) { Comparable c1 = (Comparable)array[i]; Comparable c2 = (Comparable)array[i + 1]; if (c1.compareTo(c2) > 0) { swap(array, i, i + 1); new_end = i; } } end = new_end; for (int i = end; i > begin; --i) { Comparable c1 = (Comparable)array[i - 1]; Comparable c2 = (Comparable)array[i]; if (c1.compareTo(c2) > 0) { swap(array, i, i - 1); new_begin = i; } } begin = new_begin; } } private static void swap(Object[] array, int i, int j) { Object tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
Keep all operations the same but rewrite the snippet in Java.
option explicit const dt = 0.15 const length=23 dim ans0:ans0=chr(27)&"[" dim Veloc,Accel,angle,olr,olc,r,c const r0=1 const c0=40 cls angle=0.7 while 1 wscript.sleep(50) Accel = -.9 * sin(Angle) Veloc = Veloc + Accel * dt Angle = Angle + Veloc * dt r = r0 + int(cos(Angle) * Length) c = c0+ int(2*sin(Angle) * Length) cls draw_line r,c,r0,c0 toxy r,c,"O" olr=r :olc=c wend sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub Sub draw_line(r1,c1, r2,c2) Dim x,y,xf,yf,dx,dy,sx,sy,err,err2 x =r1 : y =c1 xf=r2 : yf=c2 dx=Abs(xf-x) : dy=Abs(yf-y) If x<xf Then sx=+1: Else sx=-1 If y<yf Then sy=+1: Else sy=-1 err=dx-dy Do toxy x,y,"." If x=xf And y=yf Then Exit Do err2=err+err If err2>-dy Then err=err-dy: x=x+sx If err2< dx Then err=err+dx: y=y+sy Loop End Sub
import java.awt.*; import javax.swing.*; public class Pendulum extends JPanel implements Runnable { private double angle = Math.PI / 2; private int length; public Pendulum(int length) { this.length = length; setDoubleBuffered(true); } @Override public void paint(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.BLACK); int anchorX = getWidth() / 2, anchorY = getHeight() / 4; int ballX = anchorX + (int) (Math.sin(angle) * length); int ballY = anchorY + (int) (Math.cos(angle) * length); g.drawLine(anchorX, anchorY, ballX, ballY); g.fillOval(anchorX - 3, anchorY - 4, 7, 7); g.fillOval(ballX - 7, ballY - 7, 14, 14); } public void run() { double angleAccel, angleVelocity = 0, dt = 0.1; while (true) { angleAccel = -9.81 / length * Math.sin(angle); angleVelocity += angleAccel * dt; angle += angleVelocity * dt; repaint(); try { Thread.sleep(15); } catch (InterruptedException ex) {} } } @Override public Dimension getPreferredSize() { return new Dimension(2 * length + 50, length / 2 * 3); } public static void main(String[] args) { JFrame f = new JFrame("Pendulum"); Pendulum p = new Pendulum(200); f.add(p); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); new Thread(p).start(); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
public class Gray { public static long grayEncode(long n){ return n ^ (n >>> 1); } public static long grayDecode(long n) { long p = n; while ((n >>>= 1) != 0) p ^= n; return p; } public static void main(String[] args){ System.out.println("i\tBinary\tGray\tDecoded"); for(int i = -1; i < 32;i++){ System.out.print(i +"\t"); System.out.print(Integer.toBinaryString(i) + "\t"); System.out.print(Long.toBinaryString(grayEncode(i))+ "\t"); System.out.println(grayDecode(grayEncode(i))); } } }
Port the provided VB code into Java while preserving the original functionality.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
public class Gray { public static long grayEncode(long n){ return n ^ (n >>> 1); } public static long grayDecode(long n) { long p = n; while ((n >>>= 1) != 0) p ^= n; return p; } public static void main(String[] args){ System.out.println("i\tBinary\tGray\tDecoded"); for(int i = -1; i < 32;i++){ System.out.print(i +"\t"); System.out.print(Integer.toBinaryString(i) + "\t"); System.out.print(Long.toBinaryString(grayEncode(i))+ "\t"); System.out.println(grayDecode(grayEncode(i))); } } }
Convert this VB block to Java, preserving its control flow and logic.
class playingcard dim suit dim pips end class class carddeck private suitnames private pipnames private cardno private deck(52) private nTop sub class_initialize dim suit dim pips suitnames = split("H,D,C,S",",") pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") cardno = 0 for suit = 1 to 4 for pips = 1 to 13 set deck(cardno) = new playingcard deck(cardno).suit = suitnames(suit-1) deck(cardno).pips = pipnames(pips-1) cardno = cardno + 1 next next nTop = 0 end sub public sub showdeck dim a redim a(51-nTop) for i = nTop to 51 a(i) = deck(i).pips & deck(i).suit next wscript.echo join( a, ", ") end sub public sub shuffle dim r randomize timer for i = nTop to 51 r = int( rnd * ( 52 - nTop ) ) if r <> i then objswap deck(i),deck(r) end if next end sub public function deal() set deal = deck( nTop ) nTop = nTop + 1 end function public property get cardsRemaining cardsRemaining = 52 - nTop end property private sub objswap( a, b ) dim tmp set tmp = a set a = b set b = tmp end sub end class
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
Translate the given VB code snippet into Java without altering its behavior.
Option Base {0|1}
Int[] literalArray = [1,2,3]; Int[] fixedLengthArray = new Int[10]; Int[] variableArray = new Int[]; assert literalArray.size == 3; Int n = literalArray[2]; fixedLengthArray[4] = 12345; fixedLengthArray += 6789; variableArray += 6789;
Convert this VB block to Java, preserving its control flow and logic.
Const Order = 4 Function InCarpet(ByVal x As Integer, ByVal y As Integer) Do While x <> 0 And y <> 0 If x Mod 3 = 1 And y Mod 3 = 1 Then InCarpet = " " Exit Function End If x = x \ 3 y = y \ 3 Loop InCarpet = "#" End Function Public Sub sierpinski_carpet() Dim i As Integer, j As Integer For i = 0 To 3 ^ Order - 1 For j = 0 To 3 ^ Order - 1 Debug.Print InCarpet(i, j); Next j Debug.Print Next i End Sub
public static boolean inCarpet(long x, long y) { while (x!=0 && y!=0) { if (x % 3 == 1 && y % 3 == 1) return false; x /= 3; y /= 3; } return true; } public static void carpet(final int n) { final double power = Math.pow(3,n); for(long i = 0; i < power; i++) { for(long j = 0; j < power; j++) { System.out.print(inCarpet(i, j) ? "*" : " "); } System.out.println(); } }
Convert the following code from VB to Java, ensuring the logic remains intact.
Private Function Knuth(a As Variant) As Variant Dim t As Variant, i As Integer If Not IsMissing(a) Then For i = UBound(a) To LBound(a) + 1 Step -1 j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a)) t = a(i) a(i) = a(j) a(j) = t Next i End If Knuth = a End Function Private Function inOrder(s As Variant) i = 2 Do While i <= UBound(s) If s(i) < s(i - 1) Then inOrder = False Exit Function End If i = i + 1 Loop inOrder = True End Function Private Function bogosort(ByVal s As Variant) As Variant Do While Not inOrder(s) Debug.Print Join(s, ", ") s = Knuth(s) Loop bogosort = s End Function Public Sub main() Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ") End Sub
public class BogoSort { public static void main(String[] args) { int[] arr={4,5,6,0,7,8,9,1,2,3}; BogoSort now=new BogoSort(); System.out.print("Unsorted: "); now.display1D(arr); now.bogo(arr); System.out.print("Sorted: "); now.display1D(arr); } void bogo(int[] arr) { int shuffle=1; for(;!isSorted(arr);shuffle++) shuffle(arr); System.out.println("This took "+shuffle+" shuffles."); } void shuffle(int[] arr) { int i=arr.length-1; while(i>0) swap(arr,i--,(int)(Math.random()*i)); } void swap(int[] arr,int i,int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } boolean isSorted(int[] arr) { for(int i=1;i<arr.length;i++) if(arr[i]<arr[i-1]) return false; return true; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } }
Convert the following code from VB to Java, ensuring the logic remains intact.
Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer) Dim t As Integer Debug.Print " Step "; step; ": ", Do While t <= end_t If t Mod 10 = 0 Then Debug.Print Format(y, "0.000"), y = y + step * Application.Run(f, y) t = t + step Loop Debug.Print End Sub Sub analytic() Debug.Print " Time: ", For t = 0 To 100 Step 10 Debug.Print " "; t, Next t Debug.Print Debug.Print "Analytic: ", For t = 0 To 100 Step 10 Debug.Print Format(20 + 80 * Exp(-0.07 * t), "0.000"), Next t Debug.Print End Sub Private Function cooling(temp As Double) As Double cooling = -0.07 * (temp - 20) End Function Public Sub euler_method() Dim r_cooling As String r_cooling = "cooling" analytic ivp_euler r_cooling, 100, 2, 100 ivp_euler r_cooling, 100, 5, 100 ivp_euler r_cooling, 100, 10, 100 End Sub
public class Euler { private static void euler (Callable f, double y0, int a, int b, int h) { int t = a; double y = y0; while (t < b) { System.out.println ("" + t + " " + y); t += h; y += h * f.compute (t, y); } System.out.println ("DONE"); } public static void main (String[] args) { Callable cooling = new Cooling (); int[] steps = {2, 5, 10}; for (int stepSize : steps) { System.out.println ("Step size: " + stepSize); euler (cooling, 100.0, 0, 100, stepSize); } } } interface Callable { public double compute (int time, double t); } class Cooling implements Callable { public double compute (int time, double t) { return -0.07 * (t - 20); } }
Write the same code in Java as shown below in VB.
Sub Main() Dim i&, c&, j#, s$ Const N& = 1000000 s = "values for n in the range 1 to 22 : " For i = 1 To 22 s = s & ns(i) & ", " Next For i = 1 To N j = Sqr(ns(i)) If j = CInt(j) Then c = c + 1 Next Debug.Print s Debug.Print c & " squares less than " & N End Sub Private Function ns(l As Long) As Long ns = l + Int(1 / 2 + Sqr(l)) End Function
public class SeqNonSquares { public static int nonsqr(int n) { return n + (int)Math.round(Math.sqrt(n)); } public static void main(String[] args) { for (int i = 1; i < 23; i++) System.out.print(nonsqr(i) + " "); System.out.println(); for (int i = 1; i < 1000000; i++) { double j = Math.sqrt(nonsqr(i)); assert j != Math.floor(j); } } }
Convert this VB snippet to Java and keep its semantics consistent.
Public Sub substring() sentence = "the last thing the man said was the" n = 10: m = 5 Debug.Print Mid(sentence, n, 5) Debug.Print Right(sentence, Len(sentence) - n + 1) Debug.Print Left(sentence, Len(sentence) - 1) k = InStr(1, sentence, "m") Debug.Print Mid(sentence, k, 5) k = InStr(1, sentence, "aid") Debug.Print Mid(sentence, k, 5) End Sub
public static String Substring(String str, int n, int m){ return str.substring(n, n+m); } public static String Substring(String str, int n){ return str.substring(n); } public static String Substring(String str){ return str.substring(0, str.length()-1); } public static String Substring(String str, char c, int m){ return str.substring(str.indexOf(c), str.indexOf(c)+m+1); } public static String Substring(String str, String sub, int m){ return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1); }
Write the same code in Java as shown below in VB.
Public Sub substring() sentence = "the last thing the man said was the" n = 10: m = 5 Debug.Print Mid(sentence, n, 5) Debug.Print Right(sentence, Len(sentence) - n + 1) Debug.Print Left(sentence, Len(sentence) - 1) k = InStr(1, sentence, "m") Debug.Print Mid(sentence, k, 5) k = InStr(1, sentence, "aid") Debug.Print Mid(sentence, k, 5) End Sub
public static String Substring(String str, int n, int m){ return str.substring(n, n+m); } public static String Substring(String str, int n){ return str.substring(n); } public static String Substring(String str){ return str.substring(0, str.length()-1); } public static String Substring(String str, char c, int m){ return str.substring(str.indexOf(c), str.indexOf(c)+m+1); } public static String Substring(String str, String sub, int m){ return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1); }
Change the programming language of this snippet from VB to Java without modifying what it does.
Function JortSort(s) JortSort = True arrPreSort = Split(s,",") Set arrSorted = CreateObject("System.Collections.ArrayList") For i = 0 To UBound(arrPreSort) arrSorted.Add(arrPreSort(i)) Next arrSorted.Sort() For j = 0 To UBound(arrPreSort) If arrPreSort(j) <> arrSorted(j) Then JortSort = False Exit For End If Next End Function WScript.StdOut.Write JortSort("1,2,3,4,5") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("1,2,3,5,4") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,b,c") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,c,b")
public class JortSort { public static void main(String[] args) { System.out.println(jortSort(new int[]{1, 2, 3})); } static boolean jortSort(int[] arr) { return true; } }
Convert this VB block to Java, preserving its control flow and logic.
Public Function Leap_year(year As Integer) As Boolean Leap_year = (Month(DateSerial(year, 2, 29)) = 2) End Function
import java.util.GregorianCalendar; import java.text.MessageFormat; public class Leapyear{ public static void main(String[] argv){ int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100}; GregorianCalendar cal = new GregorianCalendar(); for(int year : yrs){ System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.", year, cal.isLeapYear(year), isLeapYear(year))); } } public static boolean isLeapYear(int year){ return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0); } }
Maintain the same structure and functionality when rewriting this code in Java.
dim i,j Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12" for i=1 to 12 for j=1 to i Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60" for i=10 to 60 step 10 for j=1 to i step i\5 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & comb(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Permutations from 5000 to 15000" for i=5000 to 15000 step 5000 for j=10 to 70 step 20 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & perm(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Combinations from 200 to 1000" for i=200 to 1000 step 200 for j=20 to 100 step 20 Wscript.StdOut.Write "P(" & i & "," & j & ")=" & comb(i,j) & " " next Wscript.StdOut.WriteLine "" next function perm(x,y) dim i,z z=1 for i=x-y+1 to x z=z*i next perm=z end function function fact(x) dim i,z z=1 for i=2 to x z=z*i next fact=z end function function comb(byval x,byval y) if y>x then comb=0 elseif x=y then comb=1 else if x-y<y then y=x-y comb=perm(x,y)/fact(y) end if end function
import java.math.BigInteger; public class CombinationsAndPermutations { public static void main(String[] args) { System.out.println(Double.MAX_VALUE); System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:"); for ( int n = 1 ; n <= 12 ; n++ ) { int k = n / 2; System.out.printf("%d P %d = %s%n", n, k, permutation(n, k)); } System.out.println(); System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:"); for ( int n = 10 ; n <= 60 ; n += 5 ) { int k = n / 2; System.out.printf("%d C %d = %s%n", n, k, combination(n, k)); } System.out.println(); System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:"); System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50)); for ( int n = 1000 ; n <= 15000 ; n += 1000 ) { int k = n / 2; System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50)); } System.out.println(); System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:"); for ( int n = 100 ; n <= 1000 ; n += 100 ) { int k = n / 2; System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50)); } } private static String display(BigInteger val, int precision) { String s = val.toString(); precision = Math.min(precision, s.length()); StringBuilder sb = new StringBuilder(); sb.append(s.substring(0, 1)); sb.append("."); sb.append(s.substring(1, precision)); sb.append(" * 10^"); sb.append(s.length()-1); return sb.toString(); } public static BigInteger combination(int n, int k) { if ( n-k < k ) { k = n-k; } BigInteger result = permutation(n, k); while ( k > 0 ) { result = result.divide(BigInteger.valueOf(k)); k--; } return result; } public static BigInteger permutation(int n, int k) { BigInteger result = BigInteger.ONE; for ( int i = n ; i >= n-k+1 ; i-- ) { result = result.multiply(BigInteger.valueOf(i)); } return result; } }
Write a version of this VB function in Java with identical behavior.
Public Function sortlexicographically(N As Integer) Dim arrList As Object Set arrList = CreateObject("System.Collections.ArrayList") For i = 1 To N arrList.Add CStr(i) Next i arrList.Sort Dim item As Variant For Each item In arrList Debug.Print item & ", "; Next End Function Public Sub main() Call sortlexicographically(13) End Sub
import java.util.List; import java.util.stream.*; public class LexicographicalNumbers { static List<Integer> lexOrder(int n) { int first = 1, last = n; if (n < 1) { first = n; last = 1; } return IntStream.rangeClosed(first, last) .mapToObj(Integer::toString) .sorted() .map(Integer::valueOf) .collect(Collectors.toList()); } public static void main(String[] args) { System.out.println("In lexicographical order:\n"); int[] ints = {0, 5, 13, 21, -22}; for (int n : ints) { System.out.printf("%3d: %s\n", n, lexOrder(n)); } } }
Keep all operations the same but rewrite the snippet in Java.
Public twenties As Variant Public decades As Variant Public orders As Variant Private Sub init() twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}] decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}] orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}] End Sub Private Function Twenty(N As Variant) Twenty = twenties(N Mod 20 + 1) End Function Private Function Decade(N As Variant) Decade = decades(N Mod 10 - 1) End Function Private Function Hundred(N As Variant) If N < 20 Then Hundred = Twenty(N) Exit Function Else If N Mod 10 = 0 Then Hundred = Decade((N \ 10) Mod 10) Exit Function End If End If Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10) End Function Private Function Thousand(N As Variant, withand As String) If N < 100 Then Thousand = withand & Hundred(N) Exit Function Else If N Mod 100 = 0 Then Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred" Exit Function End If End If Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100) End Function Private Function Triplet(N As Variant) Dim Order, High As Variant, Low As Variant Dim Name As String, res As String For i = 1 To UBound(orders) Order = orders(i, 1) Name = orders(i, 2) High = WorksheetFunction.Floor_Precise(N / Order) Low = N - High * Order If High <> 0 Then res = res & Thousand(High, "") & " " & Name End If N = Low If Low = 0 Then Exit For If Len(res) And High <> 0 Then res = res & ", " End If Next i If N <> 0 Or res = "" Then res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and ")) N = N - Int(N) If N > 0.000001 Then res = res & " point" For i = 1 To 10 n_ = WorksheetFunction.Floor_Precise(N * 10.0000001) res = res & " " & twenties(n_ + 1) N = N * 10 - n_ If Abs(N) < 0.000001 Then Exit For Next i End If End If Triplet = res End Function Private Function spell(N As Variant) Dim res As String If N < 0 Then res = "minus " N = -N End If res = res & Triplet(N) spell = res End Function Private Function smartp(N As Variant) Dim res As String If N = WorksheetFunction.Floor_Precise(N) Then smartp = CStr(N) Exit Function End If res = CStr(N) If InStr(1, res, ".") Then res = Left(res, InStr(1, res, ".")) End If smartp = res End Function Sub Main() Dim si As Variant init Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}] Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}] For i = 1 To UBound(Samples1) si = Samples1(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i For i = 1 To UBound(Samples2) si = Samples2(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i End Sub
module NumberNames { void run() { @Inject Console console; Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000, 123456789000, 0x123456789ABCDEF]; for (Int test : tests) { console.print($"{test} = {toEnglish(test)}"); } } static String[] digits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; static String[] teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; static String[] tens = ["zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; static String[] ten3rd = ["?", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion"]; static String toEnglish(Int n) { StringBuffer buf = new StringBuffer(); if (n < 0) { "negative ".appendTo(buf); n = -n; } format3digits(n, buf); return buf.toString(); } static void format3digits(Int n, StringBuffer buf, Int nested=0) { (Int left, Int right) = n /% 1000; if (left != 0) { format3digits(left, buf, nested+1); } if (right != 0 || (left == 0 && nested==0)) { if (right >= 100) { (left, right) = (right /% 100); digits[left].appendTo(buf); " hundred ".appendTo(buf); if (right != 0) { format2digits(right, buf); } } else { format2digits(right, buf); } if (nested > 0) { ten3rd[nested].appendTo(buf).add(' '); } } } static void format2digits(Int n, StringBuffer buf) { switch (n) { case 0..9: digits[n].appendTo(buf).add(' '); break; case 10..19: teens[n-10].appendTo(buf).add(' '); break; default: (Int left, Int right) = n /% 10; tens[left].appendTo(buf); if (right == 0) { buf.add(' '); } else { buf.add('-'); digits[right].appendTo(buf).add(' '); } break; } } }
Write the same algorithm in Java as shown in this VB implementation.
Sub arrShellSort(ByVal arrData As Variant) Dim lngHold, lngGap As Long Dim lngCount, lngMin, lngMax As Long Dim varItem As Variant lngMin = LBound(arrData) lngMax = UBound(arrData) lngGap = lngMin Do While (lngGap < lngMax) lngGap = 3 * lngGap + 1 Loop Do While (lngGap > 1) lngGap = lngGap \ 3 For lngCount = lngGap + lngMin To lngMax varItem = arrData(lngCount) lngHold = lngCount Do While ((arrData(lngHold - lngGap) > varItem)) arrData(lngHold) = arrData(lngHold - lngGap) lngHold = lngHold - lngGap If (lngHold < lngMin + lngGap) Then Exit Do Loop arrData(lngHold) = varItem Next Loop arrShellSort = arrData End Sub
public static void shell(int[] a) { int increment = a.length / 2; while (increment > 0) { for (int i = increment; i < a.length; i++) { int j = i; int temp = a[i]; while (j >= increment && a[j - increment] > temp) { a[j] = a[j - increment]; j = j - increment; } a[j] = temp; } if (increment == 2) { increment = 1; } else { increment *= (5.0 / 11); } } }
Write a version of this VB function in Java with identical behavior.
Public Class DoubleLinkList(Of T) Private m_Head As Node(Of T) Private m_Tail As Node(Of T) Public Sub AddHead(ByVal value As T) Dim node As New Node(Of T)(Me, value) If m_Head Is Nothing Then m_Head = Node m_Tail = m_Head Else node.Next = m_Head m_Head = node End If End Sub Public Sub AddTail(ByVal value As T) Dim node As New Node(Of T)(Me, value) If m_Tail Is Nothing Then m_Head = node m_Tail = m_Head Else node.Previous = m_Tail m_Tail = node End If End Sub Public ReadOnly Property Head() As Node(Of T) Get Return m_Head End Get End Property Public ReadOnly Property Tail() As Node(Of T) Get Return m_Tail End Get End Property Public Sub RemoveTail() If m_Tail Is Nothing Then Return If m_Tail.Previous Is Nothing Then m_Head = Nothing m_Tail = Nothing Else m_Tail = m_Tail.Previous m_Tail.Next = Nothing End If End Sub Public Sub RemoveHead() If m_Head Is Nothing Then Return If m_Head.Next Is Nothing Then m_Head = Nothing m_Tail = Nothing Else m_Head = m_Head.Next m_Head.Previous = Nothing End If End Sub End Class Public Class Node(Of T) Private ReadOnly m_Value As T Private m_Next As Node(Of T) Private m_Previous As Node(Of T) Private ReadOnly m_Parent As DoubleLinkList(Of T) Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T) m_Parent = parent m_Value = value End Sub Public Property [Next]() As Node(Of T) Get Return m_Next End Get Friend Set(ByVal value As Node(Of T)) m_Next = value End Set End Property Public Property Previous() As Node(Of T) Get Return m_Previous End Get Friend Set(ByVal value As Node(Of T)) m_Previous = value End Set End Property Public ReadOnly Property Value() As T Get Return m_Value End Get End Property Public Sub InsertAfter(ByVal value As T) If m_Next Is Nothing Then m_Parent.AddTail(value) ElseIf m_Previous Is Nothing Then m_Parent.AddHead(value) Else Dim node As New Node(Of T)(m_Parent, value) node.Previous = Me node.Next = Me.Next Me.Next.Previous = node Me.Next = node End If End Sub Public Sub Remove() If m_Next Is Nothing Then m_Parent.RemoveTail() ElseIf m_Previous Is Nothing Then m_Parent.RemoveHead() Else m_Previous.Next = Me.Next m_Next.Previous = Me.Previous End If End Sub End Class
import java.util.LinkedList; public class DoublyLinkedList { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addFirst("Add First"); list.addLast("Add Last 1"); list.addLast("Add Last 2"); list.addLast("Add Last 1"); traverseList(list); list.removeFirstOccurrence("Add Last 1"); traverseList(list); } private static void traverseList(LinkedList<String> list) { System.out.println("Traverse List:"); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); } System.out.println(); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
TYPE regChar Character AS STRING * 3 Count AS LONG END TYPE DIM iChar AS INTEGER DIM iCL AS INTEGER DIM iCountChars AS INTEGER DIM iFile AS INTEGER DIM i AS INTEGER DIM lMUC AS LONG DIM iMUI AS INTEGER DIM lLUC AS LONG DIM iLUI AS INTEGER DIM iMaxIdx AS INTEGER DIM iP AS INTEGER DIM iPause AS INTEGER DIM iPMI AS INTEGER DIM iPrint AS INTEGER DIM lHowMany AS LONG DIM lTotChars AS LONG DIM sTime AS SINGLE DIM strFile AS STRING DIM strTxt AS STRING DIM strDate AS STRING DIM strTime AS STRING DIM strKey AS STRING CONST LngReg = 256 CONST Letters = 1 CONST FALSE = 0 CONST TRUE = NOT FALSE strDate = DATE$ strTime = TIME$ iFile = FREEFILE DO CLS PRINT "This program counts letters or characters in a text file." PRINT INPUT "File to open: ", strFile OPEN strFile FOR BINARY AS #iFile IF LOF(iFile) > 0 THEN PRINT "Count: 1) Letters 2) Characters (1 or 2)"; DO strKey = INKEY$ LOOP UNTIL strKey = "1" OR strKey = "2" PRINT ". Option selected: "; strKey iCL = VAL(strKey) sTime = TIMER iP = POS(0) lHowMany = LOF(iFile) strTxt = SPACE$(LngReg) IF iCL = Letters THEN iMaxIdx = 26 ELSE iMaxIdx = 255 END IF IF iMaxIdx <> iPMI THEN iPMI = iMaxIdx REDIM rChar(0 TO iMaxIdx) AS regChar FOR i = 0 TO iMaxIdx IF iCL = Letters THEN strTxt = CHR$(i + 65) IF i = 26 THEN strTxt = CHR$(165) ELSE SELECT CASE i CASE 0: strTxt = "nul" CASE 7: strTxt = "bel" CASE 9: strTxt = "tab" CASE 10: strTxt = "lf" CASE 11: strTxt = "vt" CASE 12: strTxt = "ff" CASE 13: strTxt = "cr" CASE 28: strTxt = "fs" CASE 29: strTxt = "gs" CASE 30: strTxt = "rs" CASE 31: strTxt = "us" CASE 32: strTxt = "sp" CASE ELSE: strTxt = CHR$(i) END SELECT END IF rChar(i).Character = strTxt NEXT i ELSE FOR i = 0 TO iMaxIdx rChar(i).Count = 0 NEXT i END IF PRINT "Looking for "; IF iCL = Letters THEN PRINT "letters."; ELSE PRINT "characters."; PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7) DO WHILE LOC(iFile) < LOF(iFile) IF LOC(iFile) + LngReg > LOF(iFile) THEN strTxt = SPACE$(LOF(iFile) - LOC(iFile)) END IF GET #iFile, , strTxt FOR i = 1 TO LEN(strTxt) IF iCL = Letters THEN iChar = ASC(UCASE$(MID$(strTxt, i, 1))) SELECT CASE iChar CASE 164: iChar = 165 CASE 160: iChar = 65 CASE 130, 144: iChar = 69 CASE 161: iChar = 73 CASE 162: iChar = 79 CASE 163, 129: iChar = 85 END SELECT iChar = iChar - 65 IF iChar >= 0 AND iChar <= 25 THEN rChar(iChar).Count = rChar(iChar).Count + 1 ELSEIF iChar = 100 THEN rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1 END IF ELSE iChar = ASC(MID$(strTxt, i, 1)) rChar(iChar).Count = rChar(iChar).Count + 1 END IF NEXT i LOOP CLOSE #iFile lMUC = 0 iMUI = 0 lLUC = 2147483647 iLUI = 0 iPrint = FALSE lTotChars = 0 iCountChars = 0 iPause = FALSE CLS IF iCL = Letters THEN PRINT "Letters found: "; ELSE PRINT "Characters found: "; FOR i = 0 TO iMaxIdx IF lMUC < rChar(i).Count THEN lMUC = rChar(i).Count iMUI = i END IF IF rChar(i).Count > 0 THEN strTxt = "" IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character)) strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count)) iP = POS(0) IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN PRINT "," IF CSRLIN >= 23 AND NOT iPause THEN iPause = TRUE PRINT "Press a key to continue..." DO strKey = INKEY$ LOOP UNTIL strKey <> "" END IF strTxt = MID$(strTxt, 3) END IF PRINT strTxt; lTotChars = lTotChars + rChar(i).Count iCountChars = iCountChars + 1 IF lLUC > rChar(i).Count THEN lLUC = rChar(i).Count iLUI = i END IF END IF NEXT i PRINT "." PRINT PRINT "File analyzed....................: "; strFile PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters" PRINT "Total characters in file.........:"; lHowMany PRINT "Total characters counted.........:"; lTotChars IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1 PRINT "Most used character was..........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lMUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)" PRINT "Least used character was.........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lLUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)" PRINT "Time spent in the process........:"; TIMER - sTime; "seconds" ELSE CLOSE #iFile KILL strFile PRINT PRINT "File does not exist." END IF PRINT PRINT "Again? (Y/n)" DO strTxt = UCASE$(INKEY$) LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27) LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27) CLS PRINT "End of execution." PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "." END
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; public class LetterFreq { public static int[] countLetters(String filename) throws IOException{ int[] freqs = new int[26]; BufferedReader in = new BufferedReader(new FileReader(filename)); String line; while((line = in.readLine()) != null){ line = line.toUpperCase(); for(char ch:line.toCharArray()){ if(Character.isLetter(ch)){ freqs[ch - 'A']++; } } } in.close(); return freqs; } public static void main(String[] args) throws IOException{ System.out.println(Arrays.toString(countLetters("filename.txt"))); } }
Change the programming language of this snippet from VB to Java without modifying what it does.
Dim s As String = "123" s = CStr(CInt("123") + 1) s = (CInt("123") + 1).ToString
String s = "12345"; IntLiteral lit1 = new IntLiteral(s); IntLiteral lit2 = 6789; ++lit1; ++lit2;
Port the following code from VB to Java with equivalent syntax and logic.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
class StripChars { public static String stripChars(String inString, String toStrip) { return inString.replaceAll("[" + toStrip + "]", ""); } public static void main(String[] args) { String sentence = "She was a soul stripper. She took my heart!"; String chars = "aei"; System.out.println("sentence: " + sentence); System.out.println("to strip: " + chars); System.out.println("stripped: " + stripChars(sentence, chars)); } }
Translate the given VB code snippet into Java without altering its behavior.
Private Function mean(v() As Double, ByVal leng As Integer) As Variant Dim sum As Double, i As Integer sum = 0: i = 0 For i = 0 To leng - 1 sum = sum + vv Next i If leng = 0 Then mean = CVErr(xlErrDiv0) Else mean = sum / leng End If End Function Public Sub main() Dim v(4) As Double Dim i As Integer, leng As Integer v(0) = 1# v(1) = 2# v(2) = 2.178 v(3) = 3# v(4) = 3.142 For leng = 5 To 0 Step -1 Debug.Print "mean["; For i = 0 To leng - 1 Debug.Print IIf(i, "; " & v(i), "" & v(i)); Next i Debug.Print "] = "; mean(v, leng) Next leng End Sub
public static double avg(double... arr) { double sum = 0.0; for (double x : arr) { sum += x; } return sum / arr.length; }
Write the same code in Java as shown below in VB.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
import java.util.*; public class Abbreviations { public static void main(String[] args) { CommandList commands = new CommandList(commandTable); String input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; System.out.println(" input: " + input); System.out.println("output: " + test(commands, input)); } private static String test(CommandList commands, String input) { StringBuilder output = new StringBuilder(); Scanner scanner = new Scanner(input); while (scanner.hasNext()) { String word = scanner.next(); if (output.length() > 0) output.append(' '); Command cmd = commands.findCommand(word); if (cmd != null) output.append(cmd.cmd); else output.append("*error*"); } return output.toString(); } private static String commandTable = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; private static class Command { private Command(String cmd, int minLength) { this.cmd = cmd; this.minLength = minLength; } private boolean match(String str) { int olen = str.length(); return olen >= minLength && olen <= cmd.length() && cmd.regionMatches(true, 0, str, 0, olen); } private String cmd; private int minLength; } private static Integer parseInteger(String word) { try { return Integer.valueOf(word); } catch (NumberFormatException ex) { return null; } } private static class CommandList { private CommandList(String table) { Scanner scanner = new Scanner(table); List<String> words = new ArrayList<>(); while (scanner.hasNext()) { String word = scanner.next(); words.add(word.toUpperCase()); } for (int i = 0, n = words.size(); i < n; ++i) { String word = words.get(i); int len = word.length(); if (i + 1 < n) { Integer number = parseInteger(words.get(i + 1)); if (number != null) { len = number.intValue(); ++i; } } commands.add(new Command(word, len)); } } private Command findCommand(String word) { for (Command command : commands) { if (command.match(word)) return command; } return null; } private List<Command> commands = new ArrayList<>(); } }
Preserve the algorithm and functionality while converting the code from VB to Java.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
import java.util.*; public class Abbreviations { public static void main(String[] args) { CommandList commands = new CommandList(commandTable); String input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; System.out.println(" input: " + input); System.out.println("output: " + test(commands, input)); } private static String test(CommandList commands, String input) { StringBuilder output = new StringBuilder(); Scanner scanner = new Scanner(input); while (scanner.hasNext()) { String word = scanner.next(); if (output.length() > 0) output.append(' '); Command cmd = commands.findCommand(word); if (cmd != null) output.append(cmd.cmd); else output.append("*error*"); } return output.toString(); } private static String commandTable = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; private static class Command { private Command(String cmd, int minLength) { this.cmd = cmd; this.minLength = minLength; } private boolean match(String str) { int olen = str.length(); return olen >= minLength && olen <= cmd.length() && cmd.regionMatches(true, 0, str, 0, olen); } private String cmd; private int minLength; } private static Integer parseInteger(String word) { try { return Integer.valueOf(word); } catch (NumberFormatException ex) { return null; } } private static class CommandList { private CommandList(String table) { Scanner scanner = new Scanner(table); List<String> words = new ArrayList<>(); while (scanner.hasNext()) { String word = scanner.next(); words.add(word.toUpperCase()); } for (int i = 0, n = words.size(); i < n; ++i) { String word = words.get(i); int len = word.length(); if (i + 1 < n) { Integer number = parseInteger(words.get(i + 1)); if (number != null) { len = number.intValue(); ++i; } } commands.add(new Command(word, len)); } } private Command findCommand(String word) { for (Command command : commands) { if (command.match(word)) return command; } return null; } private List<Command> commands = new ArrayList<>(); } }
Translate the given VB code snippet into Java without altering its behavior.
Private Function tokenize(s As String, sep As String, esc As String) As Collection Dim ret As New Collection Dim this As String Dim skip As Boolean If Len(s) <> 0 Then For i = 1 To Len(s) si = Mid(s, i, 1) If skip Then this = this & si skip = False Else If si = esc Then skip = True Else If si = sep Then ret.Add this this = "" Else this = this & si End If End If End If Next i ret.Add this End If Set tokenize = ret End Function Public Sub main() Dim out As Collection Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") Dim outstring() As String ReDim outstring(out.Count - 1) For i = 0 To out.Count - 1 outstring(i) = out(i + 1) Next i Debug.Print Join(outstring, ", ") End Sub
import java.util.*; public class TokenizeStringWithEscaping { public static void main(String[] args) { String sample = "one^|uno||three^^^^|four^^^|^cuatro|"; char separator = '|'; char escape = '^'; System.out.println(sample); try { System.out.println(tokenizeString(sample, separator, escape)); } catch (Exception e) { System.out.println(e); } } public static List<String> tokenizeString(String s, char sep, char escape) throws Exception { List<String> tokens = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean inEscape = false; for (char c : s.toCharArray()) { if (inEscape) { inEscape = false; } else if (c == escape) { inEscape = true; continue; } else if (c == sep) { tokens.add(sb.toString()); sb.setLength(0); continue; } sb.append(c); } if (inEscape) throw new Exception("Invalid terminal escape"); tokens.add(sb.toString()); return tokens; } }
Convert the following code from VB to Java, ensuring the logic remains intact.
Public Sub hello_world_text Debug.Print "Hello World!" End Sub
module HelloWorld { void run() { @Inject Console console; console.print("Hello World!"); } }
Produce a functionally identical Java code for the snippet given in VB.
Public Sub hello_world_text Debug.Print "Hello World!" End Sub
module HelloWorld { void run() { @Inject Console console; console.print("Hello World!"); } }
Preserve the algorithm and functionality while converting the code from VB to Java.
Module ForwardDifference Sub Main() Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}) For i As UInteger = 0 To 9 Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray())) Next Console.ReadKey() End Sub Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer) If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers") For i As Integer = 1 To Level Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _ Select Numbers(n + 1) - Numbers(n)).ToList() Next Return Numbers End Function End Module
import java.util.Arrays; public class FD { public static void main(String args[]) { double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; System.out.println(Arrays.toString(dif(a, 1))); System.out.println(Arrays.toString(dif(a, 2))); System.out.println(Arrays.toString(dif(a, 9))); System.out.println(Arrays.toString(dif(a, 10))); System.out.println(Arrays.toString(dif(a, 11))); System.out.println(Arrays.toString(dif(a, -1))); System.out.println(Arrays.toString(dif(a, 0))); } public static double[] dif(double[] a, int n) { if (n < 0) return null; for (int i = 0; i < n && a.length > 0; i++) { double[] b = new double[a.length - 1]; for (int j = 0; j < b.length; j++){ b[j] = a[j+1] - a[j]; } a = b; } return a; } }
Maintain the same structure and functionality when rewriting this code in Java.
Option Explicit Sub FirstTwentyPrimes() Dim count As Integer, i As Long, t(19) As String Do i = i + 1 If IsPrime(i) Then t(count) = i count = count + 1 End If Loop While count <= UBound(t) Debug.Print Join(t, ", ") End Sub Function IsPrime(Nb As Long) As Boolean If Nb = 2 Then IsPrime = True ElseIf Nb < 2 Or Nb Mod 2 = 0 Then Exit Function Else Dim i As Long For i = 3 To Sqr(Nb) Step 2 If Nb Mod i = 0 Then Exit Function Next IsPrime = True End If End Function
public static boolean prime(long a){ if(a == 2){ return true; }else if(a <= 1 || a % 2 == 0){ return false; } long max = (long)Math.sqrt(a); for(long n= 3; n <= max; n+= 2){ if(a % n == 0){ return false; } } return true; }
Write a version of this VB function in Java with identical behavior.
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
public class Binomial { private static long binomialInt(int n, int k) { if (k > n - k) k = n - k; long binom = 1; for (int i = 1; i <= k; i++) binom = binom * (n + 1 - i) / i; return binom; } private static Object binomialIntReliable(int n, int k) { if (k > n - k) k = n - k; long binom = 1; for (int i = 1; i <= k; i++) { try { binom = Math.multiplyExact(binom, n + 1 - i) / i; } catch (ArithmeticException e) { return "overflow"; } } return binom; } private static double binomialFloat(int n, int k) { if (k > n - k) k = n - k; double binom = 1.0; for (int i = 1; i <= k; i++) binom = binom * (n + 1 - i) / i; return binom; } private static BigInteger binomialBigInt(int n, int k) { if (k > n - k) k = n - k; BigInteger binom = BigInteger.ONE; for (int i = 1; i <= k; i++) { binom = binom.multiply(BigInteger.valueOf(n + 1 - i)); binom = binom.divide(BigInteger.valueOf(i)); } return binom; } private static void demo(int n, int k) { List<Object> data = Arrays.asList( n, k, binomialInt(n, k), binomialIntReliable(n, k), binomialFloat(n, k), binomialBigInt(n, k)); System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t"))); } public static void main(String[] args) { demo(5, 3); demo(1000, 300); } }
Rewrite the snippet below in Java so it works the same as the original VB code.
Dim coll As New Collection coll.Add "apple" coll.Add "banana"
List arrayList = new ArrayList(); arrayList.add(new Integer(0)); arrayList.add(0); List<Integer> myarrlist = new ArrayList<Integer>(); int sum; for(int i = 0; i < 10; i++) { myarrlist.add(i); }
Generate an equivalent Java version of this VB code.
Private Sub Iterate(ByVal list As LinkedList(Of Integer)) Dim node = list.First Do Until node Is Nothing node = node.Next Loop End Sub
LinkedList<Type> list = new LinkedList<Type>(); for(Type i: list){ System.out.println(i); }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
Ensure the translated Java code behaves exactly like the original VB snippet.
Option Explicit Sub DeleteFileOrDirectory() Dim myPath As String myPath = "C:\Users\surname.name\Desktop\Docs" Kill myPath & "\input.txt" RmDir myPath End Sub
import java.io.File; public class FileDeleteTest { public static boolean deleteFile(String filename) { boolean exists = new File(filename).delete(); return exists; } public static void test(String type, String filename) { System.out.println("The following " + type + " called " + filename + (deleteFile(filename) ? " was deleted." : " could not be deleted.") ); } public static void main(String args[]) { test("file", "input.txt"); test("file", File.seperator + "input.txt"); test("directory", "docs"); test("directory", File.seperator + "docs" + File.seperator); } }
Port the following code from VB to Java with equivalent syntax and logic.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
import java.util.HashSet; import java.util.Random; import java.util.Set; public class AverageLoopLength { private static final int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.nextInt(n); } Set<Integer> seen = new HashSet<>(n); int current = 0; int length = 0; while (seen.add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void main(String[] args) { System.out.println(" N average analytical (error)"); System.out.println("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { double avg = average(i); double ana = analytical(i); System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100))); } } }
Transform the following VB implementation into Java, maintaining the same output and logic.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
import java.util.HashSet; import java.util.Random; import java.util.Set; public class AverageLoopLength { private static final int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.nextInt(n); } Set<Integer> seen = new HashSet<>(n); int current = 0; int length = 0; while (seen.add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void main(String[] args) { System.out.println(" N average analytical (error)"); System.out.println("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { double avg = average(i); double ana = analytical(i); System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100))); } } }
Generate an equivalent Java version of this VB code.
Dim name as String = "J. Doe" Dim balance as Double = 123.45 Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance) Console.WriteLine(prompt)
String original = "Mary had a X lamb"; String little = "little"; String replaced = original.replace("X", little); System.out.println(replaced); System.out.printf("Mary had a %s lamb.", little); String formatted = String.format("Mary had a %s lamb.", little); System.out.println(formatted);
Write the same code in Java as shown below in VB.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant  : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
Generate an equivalent Java version of this VB code.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant  : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
void bitwise(int a, int b) { printf("a and b: %d\n", a & b); printf("a or b: %d\n", a | b); printf("a xor b: %d\n", a ^ b); printf("not a: %d\n", ~a); printf("a << n: %d\n", a << b); printf("a >> n: %d\n", a >> b); unsigned int c = a; printf("c >> b: %d\n", c >> b); return 0; }
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) const sep = 512 const depth = 14 var s = math.Sqrt2 / 2 var sin = []float64{0, s, 1, s, 0, -s, -1, -s} var cos = []float64{1, s, 0, -s, -1, -s, 0, s} var p = color.NRGBA{64, 192, 96, 255} var b *image.NRGBA func main() { width := sep * 11 / 6 height := sep * 4 / 3 bounds := image.Rect(0, 0, width, height) b = image.NewNRGBA(bounds) draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src) dragon(14, 0, 1, sep, sep/2, sep*5/6) f, err := os.Create("dragon.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, b); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } } func dragon(n, a, t int, d, x, y float64) { if n <= 1 { x1 := int(x + .5) y1 := int(y + .5) x2 := int(x + d*cos[a] + .5) y2 := int(y + d*sin[a] + .5) xInc := 1 if x1 > x2 { xInc = -1 } yInc := 1 if y1 > y2 { yInc = -1 } for x, y := x1, y1; ; x, y = x+xInc, y+yInc { b.Set(x, y, p) if x == x2 { break } } return } d *= s a1 := (a - t) & 7 a2 := (a + t) & 7 dragon(n-1, a1, 1, d, x, y) dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1]) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { long long tmp = dx - dy; dy = dx + dy; dx = tmp; scale *= 2; x *= 2; y *= 2; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / scale; double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long tmp; # define LEFT tmp = -dy; dy = dx; dx = tmp # define RIGHT tmp = dy; dy = -dx; dx = tmp while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("X+YF+", d - 1); continue; case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; case '+': RIGHT; continue; case '-': LEFT; continue; case 'F': clen ++; h_rgb(x/scale, y/scale); x += dx; y += dy; continue; } } } void dragon(long leng, int depth) { long i, d = leng / 3 + 1; long h = leng + 3, w = leng + d * 3 / 2 + 2; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = d; dx = leng; dy = 0; scale = 1; clen = 0; for (i = 0; i < depth; i++) sc_up(); iter_string("FX", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); dragon(size, depth * 2); return 0; }
Generate a C translation of this Go snippet without changing its computational steps.
package main import ( "bufio" "fmt" "log" "os" ) func init() { log.SetFlags(log.Lshortfile) } func main() { inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) } defer inputFile.Close() scanner := bufio.NewScanner(inputFile) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(scanner.Err()) } }
#include <conio.h> #include <stdio.h> int main() { int n1, n2, n3; printf( "\n Introduzca el primer n%cmero (entero): ", 163 ); scanf( "%d", &n1 ); printf( "\n Introduzca el segundo n%cmero (entero): ", 163 ); scanf( "%d", &n2 ); printf( "\n Introduzca el tercer n%cmero (entero): ", 163 ); scanf( "%d", &n3 ); if ( n1 >= n2 && n1 >= n3 ) printf( "\n %d es el mayor.", n1 ); else if ( n2 > n3 ) printf( "\n %d es el mayor.", n2 ); else printf( "\n %d es el mayor.", n3 ); getch(); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) }
void insert(link* anchor, link* newlink) { newlink->next = anchor->next; newlink->prev = anchor; (newlink->next)->prev = newlink; anchor->next = newlink; }
Generate an equivalent C version of this Go code.
package main import ( "fmt" "math/big" ) var b = new(big.Int) func isSPDSPrime(n uint64) bool { nn := n for nn > 0 { r := nn % 10 if r != 2 && r != 3 && r != 5 && r != 7 { return false } nn /= 10 } b.SetUint64(n) if b.ProbablyPrime(0) { return true } return false } func listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 { count := countFrom for n := startFrom; ; n += 2 { if isSPDSPrime(n) { count++ if !printOne { fmt.Printf("%2d. %d\n", count, n) } if count == countTo { if printOne { fmt.Println(n) } return n } } } } func main() { fmt.Println("The first 25 terms of the Smarandache prime-digital sequence are:") fmt.Println(" 1. 2") n := listSPDSPrimes(3, 1, 25, false) fmt.Println("\nHigher terms:") indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000} for i := 1; i < len(indices); i++ { fmt.Printf("%6d. ", indices[i]) n = listSPDSPrimes(n+2, indices[i-1], indices[i], true) } }
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> typedef uint32_t integer; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; } } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; static const integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (int i = 0; i < 8; ++i) { if (p * p > n) return true; if (n % p == 0) return false; p += wheel[i]; } } } int main() { setlocale(LC_ALL, ""); const integer limit = 1000000000; integer n = 0, max = 0; printf("First 25 SPDS primes:\n"); for (int i = 0; n < limit; ) { n = next_prime_digit_number(n); if (!is_prime(n)) continue; if (i < 25) { if (i > 0) printf(" "); printf("%'u", n); } else if (i == 25) printf("\n"); ++i; if (i == 100) printf("Hundredth SPDS prime: %'u\n", n); else if (i == 1000) printf("Thousandth SPDS prime: %'u\n", n); else if (i == 10000) printf("Ten thousandth SPDS prime: %'u\n", n); max = n; } printf("Largest SPDS prime less than %'u: %'u\n", limit, max); return 0; }
Transform the following Go implementation into C, maintaining the same output and logic.
package main import "fmt" func quickselect(list []int, k int) int { for { px := len(list) / 2 pv := list[px] last := len(list) - 1 list[px], list[last] = list[last], list[px] i := 0 for j := 0; j < last; j++ { if list[j] < pv { list[i], list[j] = list[j], list[i] i++ } } if i == k { return pv } if k < i { list = list[:i] } else { list[i], list[last] = list[last], list[i] list = list[i+1:] k -= i + 1 } } } func main() { for i := 0; ; i++ { v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4} if i == len(v) { return } fmt.Println(quickselect(v, i)) } }
#include <stdio.h> #include <string.h> int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v, st, k) : qselect(v + st, len - st, k - st); } int main(void) { # define N (sizeof(x)/sizeof(x[0])) int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; int y[N]; int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); printf("%d: %d\n", i, qselect(y, 10, i)); } return 0; }
Produce a functionally identical C code for the snippet given in Go.
package main import ( "fmt" "math/big" "strconv" ) func main () { s := strconv.FormatInt(26, 16) fmt.Println(s) i, err := strconv.ParseInt("1a", 16, 64) if err == nil { fmt.Println(i) } b, ok := new(big.Int).SetString("1a", 16) if ok { fmt.Println(b) } }
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> char *to_base(int64_t num, int base) { char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[66] = {'\0'}; char *out; uint64_t n; int i, len = 0, neg = 0; if (base > 36) { fprintf(stderr, "base %d too large\n", base); return 0; } n = ((neg = num < 0)) ? (~num) + 1 : num; do { buf[len++] = tbl[n % base]; } while(n /= base); out = malloc(len + neg + 1); for (i = neg; len > 0; i++) out[i] = buf[--len]; if (neg) out[0] = '-'; return out; } long from_base(const char *num_str, int base) { char *endptr; int result = strtol(num_str, &endptr, base); return result; } int main() { int64_t x; x = ~(1LL << 63) + 1; printf("%lld in base 2: %s\n", x, to_base(x, 2)); x = 383; printf("%lld in base 16: %s\n", x, to_base(x, 16)); return 0; }
Translate this program into C but keep the logic exactly as in Go.
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Go version.
package main import "fmt" type sBox [8][16]byte type gost struct { k87, k65, k43, k21 [256]byte enc []byte } func newGost(s *sBox) *gost { var g gost for i := range g.k87 { g.k87[i] = s[7][i>>4]<<4 | s[6][i&15] g.k65[i] = s[5][i>>4]<<4 | s[4][i&15] g.k43[i] = s[3][i>>4]<<4 | s[2][i&15] g.k21[i] = s[1][i>>4]<<4 | s[0][i&15] } g.enc = make([]byte, 8) return &g } func (g *gost) f(x uint32) uint32 { x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 | uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255]) return x<<11 | x>>(32-11) } var cbrf = sBox{ {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3}, {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9}, {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11}, {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3}, {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2}, {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14}, {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12}, {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12}, } func u32(b []byte) uint32 { return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 } func b4(u uint32, b []byte) { b[0] = byte(u) b[1] = byte(u >> 8) b[2] = byte(u >> 16) b[3] = byte(u >> 24) } func (g *gost) mainStep(input []byte, key []byte) { key32 := u32(key) input1 := u32(input[:4]) input2 := u32(input[4:]) b4(g.f(key32+input1)^input2, g.enc[:4]) copy(g.enc[4:], input[:4]) } func main() { input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04} key := []byte{0xF9, 0x04, 0xC1, 0xE2} g := newGost(&cbrf) g.mainStep(input, key) for _, b := range g.enc { fmt.Printf("[%02x]", b) } fmt.Println() }
static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }; static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }; static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }; static unsigned char const k5[16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }; static unsigned char const k4[16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }; static unsigned char const k3[16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }; static unsigned char const k2[16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }; static unsigned char const k1[16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }; static unsigned char k87[256]; static unsigned char k65[256]; static unsigned char k43[256]; static unsigned char k21[256]; void kboxinit(void) { int i; for (i = 0; i < 256; i++) { k87[i] = k8[i >> 4] << 4 | k7[i & 15]; k65[i] = k6[i >> 4] << 4 | k5[i & 15]; k43[i] = k4[i >> 4] << 4 | k3[i & 15]; k21[i] = k2[i >> 4] << 4 | k1[i & 15]; } } static word32 f(word32 x) { x = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255]; return x<<11 | x>>(32-11); }
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import ( "fmt" "unicode" ) var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"} func main() { play(states) play(append(states, "New Kory", "Wen Kory", "York New", "Kory New", "New Kory")) } func play(states []string) { fmt.Println(len(states), "states:") set := make(map[string]bool, len(states)) for _, s := range states { set[s] = true } s := make([]string, len(set)) h := make([][26]byte, len(set)) var i int for us := range set { s[i] = us for _, c := range us { if u := uint(unicode.ToLower(c)) - 'a'; u < 26 { h[i][u]++ } } i++ } type pair struct { i1, i2 int } m := make(map[string][]pair) b := make([]byte, 26) for i1, h1 := range h { for i2 := i1 + 1; i2 < len(h); i2++ { for i := range b { b[i] = h1[i] + h[i2][i] } k := string(b) for _, x := range m[k] { if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 { fmt.Printf("%s, %s = %s, %s\n", s[i1], s[i2], s[x.i1], s[x.i2]) } } m[k] = append(m[k], pair{i1, i2}) } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define USE_FAKES 1 const char *states[] = { #if USE_FAKES "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" }; int n_states = sizeof(states)/sizeof(*states); typedef struct { unsigned char c[26]; const char *name[2]; } letters; void count_letters(letters *l, const char *s) { int c; if (!l->name[0]) l->name[0] = s; else l->name[1] = s; while ((c = *s++)) { if (c >= 'a' && c <= 'z') l->c[c - 'a']++; if (c >= 'A' && c <= 'Z') l->c[c - 'A']++; } } int lcmp(const void *aa, const void *bb) { int i; const letters *a = aa, *b = bb; for (i = 0; i < 26; i++) if (a->c[i] > b->c[i]) return 1; else if (a->c[i] < b->c[i]) return -1; return 0; } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } void no_dup() { int i, j; qsort(states, n_states, sizeof(const char*), scmp); for (i = j = 0; i < n_states;) { while (++i < n_states && !strcmp(states[i], states[j])); if (i < n_states) states[++j] = states[i]; } n_states = j + 1; } void find_mix() { int i, j, n; letters *l, *p; no_dup(); n = n_states * (n_states - 1) / 2; p = l = calloc(n, sizeof(letters)); for (i = 0; i < n_states; i++) for (j = i + 1; j < n_states; j++, p++) { count_letters(p, states[i]); count_letters(p, states[j]); } qsort(l, n, sizeof(letters), lcmp); for (j = 0; j < n; j++) { for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) { if (l[j].name[0] == l[i].name[0] || l[j].name[1] == l[i].name[0] || l[j].name[1] == l[i].name[1]) continue; printf("%s + %s => %s + %s\n", l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]); } } free(l); } int main(void) { find_mix(); return 0; }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
#include <stdio.h> #include <string.h> #include <zlib.h> int main() { const char *s = "The quick brown fox jumps over the lazy dog"; printf("%lX\n", crc32(0, (const void*)s, strlen(s))); return 0; }
Produce a language-to-language conversion: from Go to C, same semantics.
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
#include <stdio.h> #include <string.h> #include <zlib.h> int main() { const char *s = "The quick brown fox jumps over the lazy dog"; printf("%lX\n", crc32(0, (const void*)s, strlen(s))); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Go version.
package main import ( "bytes" "encoding/csv" "fmt" "html/template" "strings" ) var c = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!` func main() { if h, err := csvToHtml(c); err != nil { fmt.Println(err) } else { fmt.Print(h) } } func csvToHtml(c string) (string, error) { data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll() if err != nil { return "", err } var b strings.Builder err = template.Must(template.New("").Parse(`<table> {{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr> {{end}}</table> `)).Execute(&b, data) return b.String(), err }
#include <stdio.h> const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "bytes" "encoding/csv" "fmt" "html/template" "strings" ) var c = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!` func main() { if h, err := csvToHtml(c); err != nil { fmt.Println(err) } else { fmt.Print(h) } } func csvToHtml(c string) (string, error) { data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll() if err != nil { return "", err } var b strings.Builder err = template.Must(template.New("").Parse(`<table> {{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr> {{end}}</table> `)).Execute(&b, data) return b.String(), err }
#include <stdio.h> const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
Produce a language-to-language conversion: from Go to C, same semantics.
package main import "fmt" type picnicBasket struct { nServings int corkscrew bool } func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew } func newPicnicBasket(nPeople int) *picnicBasket { return &picnicBasket{nPeople, nPeople > 0} } func main() { var pb picnicBasket pbl := picnicBasket{} pbp := &picnicBasket{} pbn := new(picnicBasket) forTwo := newPicnicBasket(2) forToo := &picnicBasket{nServings: 2, corkscrew: true} fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
#include <stdlib.h> typedef struct sMyClass { int variable; } *MyClass; MyClass MyClass_new() { MyClass pthis = malloc(sizeof *pthis); pthis->variable = 0; return pthis; } void MyClass_delete(MyClass* pthis) { if (pthis) { free(*pthis); *pthis = NULL; } } void MyClass_someMethod(MyClass pthis) { pthis->variable = 1; } MyClass obj = MyClass_new(); MyClass_someMethod(obj); MyClass_delete(&obj);
Produce a functionally identical C code for the snippet given in Go.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
Preserve the algorithm and functionality while converting the code from Go to C.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
Write a version of this Go function in C with identical behavior.
package main import ( "fmt" "log" "strings" ) func compress(uncompressed string) []int { dictSize := 256 dictionary := make(map[string]int, dictSize) for i := 0; i < dictSize; i++ { dictionary[string([]byte{byte(i)})] = i } var result []int var w []byte for i := 0; i < len(uncompressed); i++ { c := uncompressed[i] wc := append(w, c) if _, ok := dictionary[string(wc)]; ok { w = wc } else { result = append(result, dictionary[string(w)]) dictionary[string(wc)] = dictSize dictSize++ wc[0] = c w = wc[:1] } } if len(w) > 0 { result = append(result, dictionary[string(w)]) } return result } type BadSymbolError int func (e BadSymbolError) Error() string { return fmt.Sprint("Bad compressed symbol ", int(e)) } func decompress(compressed []int) (string, error) { dictSize := 256 dictionary := make(map[int][]byte, dictSize) for i := 0; i < dictSize; i++ { dictionary[i] = []byte{byte(i)} } var result strings.Builder var w []byte for _, k := range compressed { var entry []byte if x, ok := dictionary[k]; ok { entry = x[:len(x):len(x)] } else if k == dictSize && len(w) > 0 { entry = append(w, w[0]) } else { return result.String(), BadSymbolError(k) } result.Write(entry) if len(w) > 0 { w = append(w, entry[0]) dictionary[dictSize] = w dictSize++ } w = entry } return result.String(), nil } func main() { compressed := compress("TOBEORNOTTOBEORTOBEORNOT") fmt.Println(compressed) decompressed, err := decompress(compressed) if err != nil { log.Fatal(err) } fmt.Println(decompressed) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> void* mem_alloc(size_t item_size, size_t n_item) { size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size); x[0] = item_size; x[1] = n_item; return x + 2; } void* mem_extend(void *m, size_t new_n) { size_t *x = (size_t*)m - 2; x = realloc(x, sizeof(size_t) * 2 + *x * new_n); if (new_n > x[1]) memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1])); x[1] = new_n; return x + 2; } inline void _clear(void *m) { size_t *x = (size_t*)m - 2; memset(m, 0, x[0] * x[1]); } #define _new(type, n) mem_alloc(sizeof(type), n) #define _del(m) { free((size_t*)(m) - 2); m = 0; } #define _len(m) *((size_t*)m - 1) #define _setsize(m, n) m = mem_extend(m, n) #define _extend(m) m = mem_extend(m, _len(m) * 2) typedef uint8_t byte; typedef uint16_t ushort; #define M_CLR 256 #define M_EOD 257 #define M_NEW 258 typedef struct { ushort next[256]; } lzw_enc_t; typedef struct { ushort prev, back; byte c; } lzw_dec_t; byte* lzw_encode(byte *in, int max_bits) { int len = _len(in), bits = 9, next_shift = 512; ushort code, c, nc, next_code = M_NEW; lzw_enc_t *d = _new(lzw_enc_t, 512); if (max_bits > 15) max_bits = 15; if (max_bits < 9 ) max_bits = 12; byte *out = _new(ushort, 4); int out_len = 0, o_bits = 0; uint32_t tmp = 0; inline void write_bits(ushort x) { tmp = (tmp << bits) | x; o_bits += bits; if (_len(out) <= out_len) _extend(out); while (o_bits >= 8) { o_bits -= 8; out[out_len++] = tmp >> o_bits; tmp &= (1 << o_bits) - 1; } } for (code = *(in++); --len; ) { c = *(in++); if ((nc = d[code].next[c])) code = nc; else { write_bits(code); nc = d[code].next[c] = next_code++; code = c; } if (next_code == next_shift) { if (++bits > max_bits) { write_bits(M_CLR); bits = 9; next_shift = 512; next_code = M_NEW; _clear(d); } else _setsize(d, next_shift *= 2); } } write_bits(code); write_bits(M_EOD); if (tmp) write_bits(tmp); _del(d); _setsize(out, out_len); return out; } byte* lzw_decode(byte *in) { byte *out = _new(byte, 4); int out_len = 0; inline void write_out(byte c) { while (out_len >= _len(out)) _extend(out); out[out_len++] = c; } lzw_dec_t *d = _new(lzw_dec_t, 512); int len, j, next_shift = 512, bits = 9, n_bits = 0; ushort code, c, t, next_code = M_NEW; uint32_t tmp = 0; inline void get_code() { while(n_bits < bits) { if (len > 0) { len --; tmp = (tmp << 8) | *(in++); n_bits += 8; } else { tmp = tmp << (bits - n_bits); n_bits = bits; } } n_bits -= bits; code = tmp >> n_bits; tmp &= (1 << n_bits) - 1; } inline void clear_table() { _clear(d); for (j = 0; j < 256; j++) d[j].c = j; next_code = M_NEW; next_shift = 512; bits = 9; }; clear_table(); for (len = _len(in); len;) { get_code(); if (code == M_EOD) break; if (code == M_CLR) { clear_table(); continue; } if (code >= next_code) { fprintf(stderr, "Bad sequence\n"); _del(out); goto bail; } d[next_code].prev = c = code; while (c > 255) { t = d[c].prev; d[t].back = c; c = t; } d[next_code - 1].c = c; while (d[c].back) { write_out(d[c].c); t = d[c].back; d[c].back = 0; c = t; } write_out(d[c].c); if (++next_code >= next_shift) { if (++bits > 16) { fprintf(stderr, "Too many bits\n"); _del(out); goto bail; } _setsize(d, next_shift *= 2); } } if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr); _setsize(out, out_len); bail: _del(d); return out; } int main() { int i, fd = open("unixdict.txt", O_RDONLY); if (fd == -1) { fprintf(stderr, "Can't read file\n"); return 1; }; struct stat st; fstat(fd, &st); byte *in = _new(char, st.st_size); read(fd, in, st.st_size); _setsize(in, st.st_size); close(fd); printf("input size: %d\n", _len(in)); byte *enc = lzw_encode(in, 9); printf("encoded size: %d\n", _len(enc)); byte *dec = lzw_decode(enc); printf("decoded size: %d\n", _len(dec)); for (i = 0; i < _len(dec); i++) if (dec[i] != in[i]) { printf("bad decode at %d\n", i); break; } if (i == _len(dec)) printf("Decoded ok\n"); _del(in); _del(enc); _del(dec); return 0; }
Convert this Go block to C, preserving its control flow and logic.
package main import "fmt" var ffr, ffs func(int) int func init() { r := []int{0, 1} s := []int{0, 2} ffr = func(n int) int { for len(r) <= n { nrk := len(r) - 1 rNxt := r[nrk] + s[nrk] r = append(r, rNxt) for sn := r[nrk] + 2; sn < rNxt; sn++ { s = append(s, sn) } s = append(s, rNxt+1) } return r[n] } ffs = func(n int) int { for len(s) <= n { ffr(len(r)) } return s[n] } } func main() { for n := 1; n <= 10; n++ { fmt.Printf("r(%d): %d\n", n, ffr(n)) } var found [1001]int for n := 1; n <= 40; n++ { found[ffr(n)]++ } for n := 1; n <= 960; n++ { found[ffs(n)]++ } for i := 1; i <= 1000; i++ { if found[i] != 1 { fmt.Println("task 4: FAIL") return } } fmt.Println("task 4: PASS") }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Rewrite the snippet below in C so it works the same as the original Go code.
package main import "fmt" var ffr, ffs func(int) int func init() { r := []int{0, 1} s := []int{0, 2} ffr = func(n int) int { for len(r) <= n { nrk := len(r) - 1 rNxt := r[nrk] + s[nrk] r = append(r, rNxt) for sn := r[nrk] + 2; sn < rNxt; sn++ { s = append(s, sn) } s = append(s, rNxt+1) } return r[n] } ffs = func(n int) int { for len(s) <= n { ffr(len(r)) } return s[n] } } func main() { for n := 1; n <= 10; n++ { fmt.Printf("r(%d): %d\n", n, ffr(n)) } var found [1001]int for n := 1; n <= 40; n++ { found[ffr(n)]++ } for n := 1; n <= 960; n++ { found[ffs(n)]++ } for i := 1; i <= 1000; i++ { if found[i] != 1 { fmt.Println("task 4: FAIL") return } } fmt.Println("task 4: PASS") }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Change the programming language of this snippet from Go to C without modifying what it does.
package main import ( "fmt" "log" ) func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m } func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
Port the following code from Go to C with equivalent syntax and logic.
package main import ( "fmt" "log" ) func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m } func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "log" "os/exec" ) func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x } func yellowstone(n int) []int { m := make(map[int]bool) a := make([]int, n+1) for i := 1; i < 4; i++ { a[i] = i m[i] = true } min := 4 for c := 4; c <= n; c++ { for i := min; ; i++ { if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 { a[c] = i m[i] = true if i == min { min++ } break } } } return a[1:] } func check(err error) { if err != nil { log.Fatal(err) } } func main() { x := make([]int, 100) for i := 0; i < 100; i++ { x[i] = i + 1 } y := yellowstone(100) fmt.Println("The first 30 Yellowstone numbers are:") fmt.Println(y[:30]) g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() check(err) check(g.Start()) fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %d\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Convert the following code from Go to C, ensuring the logic remains intact.
package main import ( "fmt" "log" "os/exec" ) func gcd(x, y int) int { for y != 0 { x, y = y, x%y } return x } func yellowstone(n int) []int { m := make(map[int]bool) a := make([]int, n+1) for i := 1; i < 4; i++ { a[i] = i m[i] = true } min := 4 for c := 4; c <= n; c++ { for i := min; ; i++ { if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 { a[c] = i m[i] = true if i == min { min++ } break } } } return a[1:] } func check(err error) { if err != nil { log.Fatal(err) } } func main() { x := make([]int, 100) for i := 0; i < 100; i++ { x[i] = i + 1 } y := yellowstone(100) fmt.Println("The first 30 Yellowstone numbers are:") fmt.Println(y[:30]) g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() check(err) check(g.Start()) fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %d\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Transform the following Go implementation into C, maintaining the same output and logic.
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d := range dir { if grid[t+next[i]] == 0 { walk(y+d[0], x+d[1]) } } grid[t]-- grid[last-t]-- } func solve(hh, ww, recur int) int { h = hh w = ww if h&1 != 0 { h, w = w, h } switch { case h&1 == 1: return 0 case w == 1: return 1 case w == 2: return h case h == 2: return w } cy := h / 2 cx := w / 2 grid = make([]byte, (h+1)*(w+1)) last = len(grid) - 1 next[0] = -1 next[1] = -w - 1 next[2] = 1 next[3] = w + 1 if recur != 0 { cnt = 0 } for x := cx + 1; x < w; x++ { t := cy*(w+1) + x grid[t] = 1 grid[last-t] = 1 walk(cy-1, x) } cnt++ if h == w { cnt *= 2 } else if w&1 == 0 && recur != 0 { solve(w, h, 0) } return cnt } func main() { for y := 1; y <= 10; y++ { for x := 1; x <= y; x++ { if x&1 == 0 || y&1 == 0 { fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1)) } } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
Rewrite the snippet below in C so it works the same as the original Go code.
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d := range dir { if grid[t+next[i]] == 0 { walk(y+d[0], x+d[1]) } } grid[t]-- grid[last-t]-- } func solve(hh, ww, recur int) int { h = hh w = ww if h&1 != 0 { h, w = w, h } switch { case h&1 == 1: return 0 case w == 1: return 1 case w == 2: return h case h == 2: return w } cy := h / 2 cx := w / 2 grid = make([]byte, (h+1)*(w+1)) last = len(grid) - 1 next[0] = -1 next[1] = -w - 1 next[2] = 1 next[3] = w + 1 if recur != 0 { cnt = 0 } for x := cx + 1; x < w; x++ { t := cy*(w+1) + x grid[t] = 1 grid[last-t] = 1 walk(cy-1, x) } cnt++ if h == w { cnt *= 2 } else if w&1 == 0 && recur != 0 { solve(w, h, 0) } return cnt } func main() { for y := 1; y <= 10; y++ { for x := 1; x <= y; x++ { if x&1 == 0 || y&1 == 0 { fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1)) } } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
Change the programming language of this snippet from Go to C without modifying what it does.
package main import "fmt" func mertens(to int) ([]int, int, int) { if to < 1 { to = 1 } merts := make([]int, to+1) primes := []int{2} var sum, zeros, crosses int for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break } if j%p == 0 { j /= p cp++ } if j%p == 0 { spf = true break } } if cp == 0 && i > 2 { cp = 1 primes = append(primes, i) } if !spf { if cp%2 == 0 { sum++ } else { sum-- } } merts[i] = sum if sum == 0 { zeros++ if i > 1 && merts[i-1] != 0 { crosses++ } } } return merts, zeros, crosses } func main() { merts, zeros, crosses := mertens(1000) fmt.Println("Mertens sequence - First 199 terms:") for i := 0; i < 200; i++ { if i == 0 { fmt.Print(" ") continue } if i%20 == 0 { fmt.Println() } fmt.Printf("  % d", merts[i]) } fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000") fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000") }
#include <stdio.h> #include <stdlib.h> int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main() { const int max = 1000; int* mertens = mertens_numbers(max); if (mertens == NULL) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 199 Mertens numbers:\n"); const int count = 200; for (int i = 0, column = 0; i < count; ++i) { if (column > 0) printf(" "); if (i == 0) printf(" "); else printf("%2d", mertens[i]); ++column; if (column == 20) { printf("\n"); column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { int m = mertens[i]; if (m == 0) { ++zero; if (previous != 0) ++cross; } previous = m; } free(mertens); printf("M(n) is zero %d times for 1 <= n <= %d.\n", zero, max); printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max); return 0; }
Write a version of this Go function in C with identical behavior.
package main import ( "fmt" "sort" "strings" ) var count int = 0 func interactiveCompare(s1, s2 string) bool { count++ fmt.Printf("(%d) Is %s < %s? ", count, s1, s2) var response string _, err := fmt.Scanln(&response) return err == nil && strings.HasPrefix(response, "y") } func main() { items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"} var sortedItems []string for _, item := range items { fmt.Printf("Inserting '%s' into %s\n", item, sortedItems) spotToInsert := sort.Search(len(sortedItems), func(i int) bool { return interactiveCompare(item, sortedItems[i]) }) sortedItems = append(sortedItems[:spotToInsert], append([]string{item}, sortedItems[spotToInsert:]...)...) } fmt.Println(sortedItems) }
#include <stdio.h> #include <string.h> #include <stdlib.h> int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int response; scanf("%d", &response); return response; } void printOrder(const char *items[], int len) { printf("{ "); for (int i = 0; i < len; ++i) printf("%s ", items[i]); printf("}\n"); } int main(void) { const char *items[] = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }; qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare); printOrder(items, sizeof(items)/sizeof(*items)); return 0; }
Convert this Go block to C, preserving its control flow and logic.
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Change the following Go code into C without altering its purpose.
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Write the same algorithm in C as shown in this Go implementation.
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m == 30) && s == 0 { bell := 0 if m == 30 { bell = 1 } bells := (h*2 + bell) % 8 watch := h/4 + 1 if bells == 0 { bells = 8 watch-- } sound := strings.Repeat("\a", bells) pl := "s" if bells == 1 { pl = " " } w := watches[watch] + " watch" if watch == 5 { if bells < 5 { w = "First " + w } else { w = "Last " + w } } fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w) } time.Sleep(1 * time.Second) } }
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
Change the following Go code into C without altering its purpose.
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m == 30) && s == 0 { bell := 0 if m == 30 { bell = 1 } bells := (h*2 + bell) % 8 watch := h/4 + 1 if bells == 0 { bells = 8 watch-- } sound := strings.Repeat("\a", bells) pl := "s" if bells == 1 { pl = " " } w := watches[watch] + " watch" if watch == 5 { if bells < 5 { w = "First " + w } else { w = "Last " + w } } fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w) } time.Sleep(1 * time.Second) } }
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
Ensure the translated C code behaves exactly like the original Go snippet.
package main import "fmt" func main() { for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} { f, ok := arFib(n) if ok { fmt.Printf("fib %d = %d\n", n, f) } else { fmt.Println("fib undefined for negative numbers") } } } func arFib(n int) (int, bool) { switch { case n < 0: return 0, false case n < 2: return n, true } return yc(func(recurse fn) fn { return func(left, term1, term2 int) int { if left == 0 { return term1+term2 } return recurse(left-1, term1+term2, term1) } })(n-2, 1, 0), true } type fn func(int, int, int) int type ff func(fn) fn type fx func(fx) fn func yc(f ff) fn { return func(x fx) fn { return x(x) }(func(x fx) fn { return f(func(a1, a2, a3 int) int { return x(x)(a1, a2, a3) }) }) }
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
Preserve the algorithm and functionality while converting the code from Go to C.
package main import ( "errors" "fmt" "log" "math/rand" "time" termbox "github.com/nsf/termbox-go" ) func main() { rand.Seed(time.Now().UnixNano()) score, err := playSnake() if err != nil { log.Fatal(err) } fmt.Println("Final score:", score) } type snake struct { body []position heading direction width, height int cells []termbox.Cell } type position struct { X int Y int } type direction int const ( North direction = iota East South West ) func (p position) next(d direction) position { switch d { case North: p.Y-- case East: p.X++ case South: p.Y++ case West: p.X-- } return p } func playSnake() (int, error) { err := termbox.Init() if err != nil { return 0, err } defer termbox.Close() termbox.Clear(fg, bg) termbox.HideCursor() s := &snake{ body: make([]position, 0, 32), cells: termbox.CellBuffer(), } s.width, s.height = termbox.Size() s.drawBorder() s.startSnake() s.placeFood() s.flush() moveCh, errCh := s.startEventLoop() const delay = 125 * time.Millisecond for t := time.NewTimer(delay); ; t.Reset(delay) { var move direction select { case err = <-errCh: return len(s.body), err case move = <-moveCh: if !t.Stop() { <-t.C } case <-t.C: move = s.heading } if s.doMove(move) { time.Sleep(1 * time.Second) break } } return len(s.body), err } func (s *snake) startEventLoop() (<-chan direction, <-chan error) { moveCh := make(chan direction) errCh := make(chan error, 1) go func() { defer close(errCh) for { switch ev := termbox.PollEvent(); ev.Type { case termbox.EventKey: switch ev.Ch { case 'w', 'W', 'k', 'K': moveCh <- North case 'a', 'A', 'h', 'H': moveCh <- West case 's', 'S', 'j', 'J': moveCh <- South case 'd', 'D', 'l', 'L': moveCh <- East case 0: switch ev.Key { case termbox.KeyArrowUp: moveCh <- North case termbox.KeyArrowDown: moveCh <- South case termbox.KeyArrowLeft: moveCh <- West case termbox.KeyArrowRight: moveCh <- East case termbox.KeyEsc: return } } case termbox.EventResize: errCh <- errors.New("terminal resizing unsupported") return case termbox.EventError: errCh <- ev.Err return case termbox.EventInterrupt: return } } }() return moveCh, errCh } func (s *snake) flush() { termbox.Flush() s.cells = termbox.CellBuffer() } func (s *snake) getCellRune(p position) rune { i := p.Y*s.width + p.X return s.cells[i].Ch } func (s *snake) setCell(p position, c termbox.Cell) { i := p.Y*s.width + p.X s.cells[i] = c } func (s *snake) drawBorder() { for x := 0; x < s.width; x++ { s.setCell(position{x, 0}, border) s.setCell(position{x, s.height - 1}, border) } for y := 0; y < s.height-1; y++ { s.setCell(position{0, y}, border) s.setCell(position{s.width - 1, y}, border) } } func (s *snake) placeFood() { for { x := rand.Intn(s.width-2) + 1 y := rand.Intn(s.height-2) + 1 foodp := position{x, y} r := s.getCellRune(foodp) if r != ' ' { continue } s.setCell(foodp, food) return } } func (s *snake) startSnake() { x := rand.Intn(s.width/2) + s.width/4 y := rand.Intn(s.height/2) + s.height/4 head := position{x, y} s.setCell(head, snakeHead) s.body = append(s.body[:0], head) s.heading = direction(rand.Intn(4)) } func (s *snake) doMove(move direction) bool { head := s.body[len(s.body)-1] s.setCell(head, snakeBody) head = head.next(move) s.heading = move s.body = append(s.body, head) r := s.getCellRune(head) s.setCell(head, snakeHead) gameOver := false switch r { case food.Ch: s.placeFood() case border.Ch, snakeBody.Ch: gameOver = true fallthrough case empty.Ch: s.setCell(s.body[0], empty) s.body = s.body[1:] default: panic(r) } s.flush() return gameOver } const ( fg = termbox.ColorWhite bg = termbox.ColorBlack ) var ( empty = termbox.Cell{Ch: ' ', Bg: bg, Fg: fg} border = termbox.Cell{Ch: '+', Bg: bg, Fg: termbox.ColorBlue} snakeBody = termbox.Cell{Ch: '#', Bg: bg, Fg: termbox.ColorGreen} snakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold} food = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed} )
char nonblocking_getch(); void positional_putch(int x, int y, char ch); void millisecond_sleep(int n); void init_screen(); void update_screen(); void close_screen(); #ifdef __linux__ #define _POSIX_C_SOURCE 200809L #include <time.h> #include <ncurses.h> char nonblocking_getch() { return getch(); } void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); } void millisecond_sleep(int n) { struct timespec t = { 0, n * 1000000 }; nanosleep(&t, 0); } void update_screen() { refresh(); } void init_screen() { initscr(); noecho(); cbreak(); nodelay(stdscr, TRUE); } void close_screen() { endwin(); } #endif #ifdef _WIN32 #error "not implemented" #endif #include <time.h> #include <stdlib.h> #define w 80 #define h 40 int board[w * h]; int head; enum Dir { N, E, S, W } dir; int quit; enum State { SPACE=0, FOOD=1, BORDER=2 }; void age() { int i; for(i = 0; i < w * h; ++i) if(board[i] < 0) ++board[i]; } void plant() { int r; do r = rand() % (w * h); while(board[r] != SPACE); board[r] = FOOD; } void start(void) { int i; for(i = 0; i < w; ++i) board[i] = board[i + (h - 1) * w] = BORDER; for(i = 0; i < h; ++i) board[i * w] = board[i * w + w - 1] = BORDER; head = w * (h - 1 - h % 2) / 2; board[head] = -5; dir = N; quit = 0; srand(time(0)); plant(); } void step() { int len = board[head]; switch(dir) { case N: head -= w; break; case S: head += w; break; case W: --head; break; case E: ++head; break; } switch(board[head]) { case SPACE: board[head] = len - 1; age(); break; case FOOD: board[head] = len - 1; plant(); break; default: quit = 1; } } void show() { const char * symbol = " @."; int i; for(i = 0; i < w * h; ++i) positional_putch(i / w, i % w, board[i] < 0 ? '#' : symbol[board[i]]); update_screen(); } int main (int argc, char * argv[]) { init_screen(); start(); do { show(); switch(nonblocking_getch()) { case 'i': dir = N; break; case 'j': dir = W; break; case 'k': dir = S; break; case 'l': dir = E; break; case 'q': quit = 1; break; } step(); millisecond_sleep(100); } while(!quit); millisecond_sleep(999); close_screen(); return 0; }
Transform the following Go implementation into C, maintaining the same output and logic.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
Produce a functionally identical C code for the snippet given in Go.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
Rewrite the snippet below in C so it works the same as the original Go code.
package main import ( "fmt" "log" "math" "rcu" ) func cantorPair(x, y int) int { if x < 0 || y < 0 { log.Fatal("Arguments must be non-negative integers.") } return (x*x + 3*x + 2*x*y + y + y*y) / 2 } func pi(n int) int { if n < 2 { return 0 } if n == 2 { return 1 } primes := rcu.Primes(int(math.Sqrt(float64(n)))) a := len(primes) memoPhi := make(map[int]int) var phi func(x, a int) int phi = func(x, a int) int { if a < 1 { return x } if a == 1 { return x - (x >> 1) } pa := primes[a-1] if x <= pa { return 1 } key := cantorPair(x, a) if v, ok := memoPhi[key]; ok { return v } memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1) return memoPhi[key] } return phi(n, a) + a - 1 } func main() { for i, n := 0, 1; i <= 9; i, n = i+1, n*10 { fmt.Printf("10^%d %d\n", i, pi(n)) } }
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <stdint.h> #include <time.h> const uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128}; #define half(n) ((int64_t)((n) - 1) >> 1) #define divide(nm, d) ((uint64_t)((double)nm / (double)d)) int64_t countPrimes(uint64_t n) { if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2; uint64_t rtlmt = (uint64_t)sqrt((double)n); int64_t mxndx = (int64_t)((rtlmt - 1) / 2); int arrlen = (int)(mxndx + 1); uint32_t *smalls = malloc(arrlen * 4); uint32_t *roughs = malloc(arrlen * 4); int64_t *larges = malloc(arrlen * 8); for (int i = 0; i < arrlen; ++i) { smalls[i] = (uint32_t)i; roughs[i] = (uint32_t)(i + i + 1); larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2); } int cullbuflen = (int)((mxndx + 8) / 8); uint8_t *cullbuf = calloc(cullbuflen, 1); int64_t nbps = 0; int rilmt = arrlen; for (int64_t i = 1; ; ++i) { int64_t sqri = (i + i) * (i + 1); if (sqri > mxndx) break; if (cullbuf[i >> 3] & masks[i & 7]) continue; cullbuf[i >> 3] |= masks[i & 7]; uint64_t bp = (uint64_t)(i + i + 1); for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) { cullbuf[c >> 3] |= masks[c & 7]; } int nri = 0; for (int ori = 0; ori < rilmt; ++ori) { uint32_t r = roughs[ori]; int64_t rci = (int64_t)(r >> 1); if (cullbuf[rci >> 3] & masks[rci & 7]) continue; uint64_t d = (uint64_t)r * bp; int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] : (int64_t)smalls[half(divide(n, d))]; larges[nri] = larges[ori] - t + nbps; roughs[nri] = r; nri++; } int64_t si = mxndx; for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) { uint32_t c = smalls[pm >> 1]; uint64_t e = (pm * bp) >> 1; for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps; } rilmt = nri; nbps++; } int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2); int ri, sri; for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri]; for (ri = 1; ; ++ri) { uint64_t p = (uint64_t)roughs[ri]; uint64_t m = n / p; int ei = (int)smalls[half((uint64_t)m/p)] - nbps; if (ei <= ri) break; ans -= (int64_t)((ei - ri) * (nbps + ri - 1)); for (sri = ri + 1; sri < ei + 1; ++sri) { ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))]; } } free(smalls); free(roughs); free(larges); free(cullbuf); return ans + 1; } int main() { uint64_t n; int i; clock_t start = clock(); for (i = 0, n = 1; i < 10; ++i, n *= 10) { printf("10^%d %ld\n", i, countPrimes(n)); } clock_t end = clock(); printf("\nTook %f seconds\n", (double) (end - start) / CLOCKS_PER_SEC); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package main import "C" import "unsafe" func main() { C.Run() } const msg = "Here am I" func Query(cbuf *C.char, csiz *C.size_t) C.int { if int(*csiz) <= len(msg) { return 0 } pbuf := uintptr(unsafe.Pointer(cbuf)) for i := 0; i < len(msg); i++ { *((*byte)(unsafe.Pointer(pbuf))) = msg[i] pbuf++ } *((*byte)(unsafe.Pointer(pbuf))) = 0 *csiz = C.size_t(len(msg) + 1) return 1 }
#include <stdio.h> extern int Query (char * Data, size_t * Length); int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer); if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } }
Generate a C translation of this Go snippet without changing its computational steps.
package main import ( "bufio" "os" ) func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { recover() defer func() { recover() }() _ = blankLine[0] func() { defer func() { recover() }() _ = s[len(longest)] longest = s }() longest = printLongest(longest) func() { defer func() { recover() os.Stdout.WriteString(s) }() _ = longest[len(s)] s = "" }() }() _ = err.(error) os.Stdout.WriteString(blankLine) blankLine = "" return } printLongest("") }
#include <stdio.h> #include <string.h> int cmp(const char *p, const char *q) { while (*p && *q) p = &p[1], q = &q[1]; return *p; } int main() { char line[65536]; char buf[1000000] = {0}; char *last = buf; char *next = buf; while (gets(line)) { strcat(line, "\n"); if (cmp(last, line)) continue; if (cmp(line, last)) next = buf; last = next; strcpy(next, line); while (*next) next = &next[1]; } printf("%s", buf); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package turing type Symbol byte type Motion byte const ( Left Motion = 'L' Right Motion = 'R' Stay Motion = 'N' ) type Tape struct { data []Symbol pos, left int blank Symbol } func NewTape(blank Symbol, start int, data []Symbol) *Tape { t := &Tape{ data: data, blank: blank, } if start < 0 { t.Left(-start) } t.Right(start) return t } func (t *Tape) Stay() {} func (t *Tape) Data() []Symbol { return t.data[t.left:] } func (t *Tape) Read() Symbol { return t.data[t.pos] } func (t *Tape) Write(s Symbol) { t.data[t.pos] = s } func (t *Tape) Dup() *Tape { t2 := &Tape{ data: make([]Symbol, len(t.Data())), blank: t.blank, } copy(t2.data, t.Data()) t2.pos = t.pos - t.left return t2 } func (t *Tape) String() string { s := "" for i := t.left; i < len(t.data); i++ { b := t.data[i] if i == t.pos { s += "[" + string(b) + "]" } else { s += " " + string(b) + " " } } return s } func (t *Tape) Move(a Motion) { switch a { case Left: t.Left(1) case Right: t.Right(1) case Stay: t.Stay() } } const minSz = 16 func (t *Tape) Left(n int) { t.pos -= n if t.pos < 0 { var sz int for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) newl := len(newd) - cap(t.data[t.left:]) n := copy(newd[newl:], t.data[t.left:]) t.data = newd[:newl+n] t.pos += newl - t.left t.left = newl } if t.pos < t.left { if t.blank != 0 { for i := t.pos; i < t.left; i++ { t.data[i] = t.blank } } t.left = t.pos } } func (t *Tape) Right(n int) { t.pos += n if t.pos >= cap(t.data) { var sz int for sz = minSz; t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) n := copy(newd[t.left:], t.data[t.left:]) t.data = newd[:t.left+n] } if i := len(t.data); t.pos >= i { t.data = t.data[:t.pos+1] if t.blank != 0 { for ; i < len(t.data); i++ { t.data[i] = t.blank } } } } type State string type Rule struct { State Symbol Write Symbol Motion Next State } func (i *Rule) key() key { return key{i.State, i.Symbol} } func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} } type key struct { State Symbol } type action struct { write Symbol Motion next State } type Machine struct { tape *Tape start, state State transition map[key]action l func(string, ...interface{}) } func NewMachine(rules []Rule) *Machine { m := &Machine{transition: make(map[key]action, len(rules))} if len(rules) > 0 { m.start = rules[0].State } for _, r := range rules { m.transition[r.key()] = r.action() } return m } func (m *Machine) Run(input *Tape) (int, *Tape) { m.tape = input.Dup() m.state = m.start for cnt := 0; ; cnt++ { if m.l != nil { m.l("%3d %4s: %v\n", cnt, m.state, m.tape) } sym := m.tape.Read() act, ok := m.transition[key{m.state, sym}] if !ok { return cnt, m.tape } m.tape.Write(act.write) m.tape.Move(act.Motion) m.state = act.next } }
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> enum { LEFT, RIGHT, STAY }; typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t; typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; }; typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t; int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; } int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; } void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } } turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; } void print_state (turing_t *t) { printf("%-10s ", t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf("[%c]", t->symbols[tape->symbol]); } else { printf(" %c ", t->symbols[tape->symbol]); } tape = tape->right; } printf("\n"); } void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } } int main () { printf("Simple incrementer\n"); turing_t *t = create( 2, "q0", "qf", 1, "qf", 2, 'B', '1', 'B', "q0", 3, '1', '1', '1', 2, "q0", '1', '1', RIGHT, "q0", "q0", 'B', '1', STAY, "qf" ); run(t); printf("\nThree-state busy beaver\n"); t = create( 4, "a", "b", "c", "halt", 1, "halt", 2, '0', '1', '0', "a", 0, 6, "a", '0', '1', RIGHT, "b", "a", '1', '1', LEFT, "c", "b", '0', '1', LEFT, "a", "b", '1', '1', RIGHT, "b", "c", '0', '1', LEFT, "b", "c", '1', '1', STAY, "halt" ); run(t); return 0; printf("\nFive-state two-symbol probable busy beaver\n"); t = create( 6, "A", "B", "C", "D", "E", "H", 1, "H", 2, '0', '1', '0', "A", 0, 10, "A", '0', '1', RIGHT, "B", "A", '1', '1', LEFT, "C", "B", '0', '1', RIGHT, "C", "B", '1', '1', RIGHT, "B", "C", '0', '1', RIGHT, "D", "C", '1', '0', LEFT, "E", "D", '0', '1', LEFT, "A", "D", '1', '1', LEFT, "D", "E", '0', '1', STAY, "H", "E", '1', '0', LEFT, "A" ); run(t); }
Change the programming language of this snippet from Go to C without modifying what it does.
package turing type Symbol byte type Motion byte const ( Left Motion = 'L' Right Motion = 'R' Stay Motion = 'N' ) type Tape struct { data []Symbol pos, left int blank Symbol } func NewTape(blank Symbol, start int, data []Symbol) *Tape { t := &Tape{ data: data, blank: blank, } if start < 0 { t.Left(-start) } t.Right(start) return t } func (t *Tape) Stay() {} func (t *Tape) Data() []Symbol { return t.data[t.left:] } func (t *Tape) Read() Symbol { return t.data[t.pos] } func (t *Tape) Write(s Symbol) { t.data[t.pos] = s } func (t *Tape) Dup() *Tape { t2 := &Tape{ data: make([]Symbol, len(t.Data())), blank: t.blank, } copy(t2.data, t.Data()) t2.pos = t.pos - t.left return t2 } func (t *Tape) String() string { s := "" for i := t.left; i < len(t.data); i++ { b := t.data[i] if i == t.pos { s += "[" + string(b) + "]" } else { s += " " + string(b) + " " } } return s } func (t *Tape) Move(a Motion) { switch a { case Left: t.Left(1) case Right: t.Right(1) case Stay: t.Stay() } } const minSz = 16 func (t *Tape) Left(n int) { t.pos -= n if t.pos < 0 { var sz int for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) newl := len(newd) - cap(t.data[t.left:]) n := copy(newd[newl:], t.data[t.left:]) t.data = newd[:newl+n] t.pos += newl - t.left t.left = newl } if t.pos < t.left { if t.blank != 0 { for i := t.pos; i < t.left; i++ { t.data[i] = t.blank } } t.left = t.pos } } func (t *Tape) Right(n int) { t.pos += n if t.pos >= cap(t.data) { var sz int for sz = minSz; t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) n := copy(newd[t.left:], t.data[t.left:]) t.data = newd[:t.left+n] } if i := len(t.data); t.pos >= i { t.data = t.data[:t.pos+1] if t.blank != 0 { for ; i < len(t.data); i++ { t.data[i] = t.blank } } } } type State string type Rule struct { State Symbol Write Symbol Motion Next State } func (i *Rule) key() key { return key{i.State, i.Symbol} } func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} } type key struct { State Symbol } type action struct { write Symbol Motion next State } type Machine struct { tape *Tape start, state State transition map[key]action l func(string, ...interface{}) } func NewMachine(rules []Rule) *Machine { m := &Machine{transition: make(map[key]action, len(rules))} if len(rules) > 0 { m.start = rules[0].State } for _, r := range rules { m.transition[r.key()] = r.action() } return m } func (m *Machine) Run(input *Tape) (int, *Tape) { m.tape = input.Dup() m.state = m.start for cnt := 0; ; cnt++ { if m.l != nil { m.l("%3d %4s: %v\n", cnt, m.state, m.tape) } sym := m.tape.Read() act, ok := m.transition[key{m.state, sym}] if !ok { return cnt, m.tape } m.tape.Write(act.write) m.tape.Move(act.Motion) m.state = act.next } }
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> enum { LEFT, RIGHT, STAY }; typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t; typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; }; typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t; int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; } int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; } void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } } turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; } void print_state (turing_t *t) { printf("%-10s ", t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf("[%c]", t->symbols[tape->symbol]); } else { printf(" %c ", t->symbols[tape->symbol]); } tape = tape->right; } printf("\n"); } void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } } int main () { printf("Simple incrementer\n"); turing_t *t = create( 2, "q0", "qf", 1, "qf", 2, 'B', '1', 'B', "q0", 3, '1', '1', '1', 2, "q0", '1', '1', RIGHT, "q0", "q0", 'B', '1', STAY, "qf" ); run(t); printf("\nThree-state busy beaver\n"); t = create( 4, "a", "b", "c", "halt", 1, "halt", 2, '0', '1', '0', "a", 0, 6, "a", '0', '1', RIGHT, "b", "a", '1', '1', LEFT, "c", "b", '0', '1', LEFT, "a", "b", '1', '1', RIGHT, "b", "c", '0', '1', LEFT, "b", "c", '1', '1', STAY, "halt" ); run(t); return 0; printf("\nFive-state two-symbol probable busy beaver\n"); t = create( 6, "A", "B", "C", "D", "E", "H", 1, "H", 2, '0', '1', '0', "A", 0, 10, "A", '0', '1', RIGHT, "B", "A", '1', '1', LEFT, "C", "B", '0', '1', RIGHT, "C", "B", '1', '1', RIGHT, "B", "C", '0', '1', RIGHT, "D", "C", '1', '0', LEFT, "E", "D", '0', '1', LEFT, "A", "D", '1', '1', LEFT, "D", "E", '0', '1', STAY, "H", "E", '1', '0', LEFT, "A" ); run(t); }
Preserve the algorithm and functionality while converting the code from Go to C.
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
#include <stdio.h> int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
package main import ( "fmt" "strconv" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func commatize(n int) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { fmt.Println("The first 35 unprimeable numbers are:") count := 0 var firstNum [10]int outer: for i, countFirst := 100, 0; countFirst < 10; i++ { if isPrime(i) { continue } s := strconv.Itoa(i) le := len(s) b := []byte(s) for j := 0; j < le; j++ { for k := byte('0'); k <= '9'; k++ { if s[j] == k { continue } b[j] = k n, _ := strconv.Atoi(string(b)) if isPrime(n) { continue outer } } b[j] = s[j] } lastDigit := s[le-1] - '0' if firstNum[lastDigit] == 0 { firstNum[lastDigit] = i countFirst++ } count++ if count <= 35 { fmt.Printf("%d ", i) } if count == 35 { fmt.Print("\n\nThe 600th unprimeable number is: ") } if count == 600 { fmt.Printf("%s\n\n", commatize(i)) } } fmt.Println("The first unprimeable number that ends in:") for i := 0; i < 10; i++ { fmt.Printf(" %d is: %9s\n", i, commatize(firstNum[i])) } }
#include <assert.h> #include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> typedef struct bit_array_tag { uint32_t size; uint32_t* array; } bit_array; bool bit_array_create(bit_array* b, uint32_t size) { uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t)); if (array == NULL) return false; b->size = size; b->array = array; return true; } void bit_array_destroy(bit_array* b) { free(b->array); b->array = NULL; } void bit_array_set(bit_array* b, uint32_t index, bool value) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); if (value) *p |= bit; else *p &= ~bit; } bool bit_array_get(const bit_array* b, uint32_t index) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); return (*p & bit) != 0; } typedef struct sieve_tag { uint32_t limit; bit_array not_prime; } sieve; bool sieve_create(sieve* s, uint32_t limit) { if (!bit_array_create(&s->not_prime, limit/2)) return false; for (uint32_t p = 3; p * p <= limit; p += 2) { if (bit_array_get(&s->not_prime, p/2 - 1) == false) { uint32_t inc = 2 * p; for (uint32_t q = p * p; q <= limit; q += inc) bit_array_set(&s->not_prime, q/2 - 1, true); } } s->limit = limit; return true; } void sieve_destroy(sieve* s) { bit_array_destroy(&s->not_prime); } bool is_prime(const sieve* s, uint32_t n) { assert(n <= s->limit); if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; return bit_array_get(&s->not_prime, n/2 - 1) == false; } uint32_t count_digits(uint32_t n) { uint32_t digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) { uint32_t p = 1; uint32_t changed = 0; for (; index > 0; p *= 10, n /= 10, --index) changed += p * (n % 10); changed += (10 * (n/10) + new_digit) * p; return changed; } bool unprimeable(const sieve* s, uint32_t n) { if (is_prime(s, n)) return false; uint32_t d = count_digits(n); for (uint32_t i = 0; i < d; ++i) { for (uint32_t j = 0; j <= 9; ++j) { uint32_t m = change_digit(n, i, j); if (m != n && is_prime(s, m)) return false; } } return true; } int main() { const uint32_t limit = 10000000; setlocale(LC_ALL, ""); sieve s = { 0 }; if (!sieve_create(&s, limit)) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 35 unprimeable numbers:\n"); uint32_t n = 100; uint32_t lowest[10] = { 0 }; for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) { if (unprimeable(&s, n)) { if (count < 35) { if (count != 0) printf(", "); printf("%'u", n); } ++count; if (count == 600) printf("\n600th unprimeable number: %'u\n", n); uint32_t last_digit = n % 10; if (lowest[last_digit] == 0) { lowest[last_digit] = n; ++found; } } } sieve_destroy(&s); for (uint32_t i = 0; i < 10; ++i) printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]); return 0; }