Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
public class MagicSquareDoublyEven { public static void main(String[] args) { int n = 8; for (int[] row : magicSquareDoublyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } static int[][] magicSquareDoublyEven(final int n) { if (n < 4 || n % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[][] result = new int[n][n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } }
n=8 pattern="1001011001101001" size=n*n: w=len(size) mult=n\4 wscript.echo "Magic square : " & n & " x " & n i=0 For r=0 To n-1 l="" For c=0 To n-1 bit=Mid(pattern, c\mult+(r\mult)*4+1, 1) If bit="1" Then t=i+1 Else t=size-i l=l & Right(Space(w) & t, w) & " " i=i+1 Next wscript.echo l Next wscript.echo "Magic constant=" & (n*n+1)*n/2
Please provide an equivalent version of this Java code in VB.
import java.util.LinkedList; import java.util.List; public class MTF{ public static List<Integer> encode(String msg, String symTable){ List<Integer> output = new LinkedList<Integer>(); StringBuilder s = new StringBuilder(symTable); for(char c : msg.toCharArray()){ int idx = s.indexOf("" + c); output.add(idx); s = s.deleteCharAt(idx).insert(0, c); } return output; } public static String decode(List<Integer> idxs, String symTable){ StringBuilder output = new StringBuilder(); StringBuilder s = new StringBuilder(symTable); for(int idx : idxs){ char c = s.charAt(idx); output = output.append(c); s = s.deleteCharAt(idx).insert(0, c); } return output.toString(); } private static void test(String toEncode, String symTable){ List<Integer> encoded = encode(toEncode, symTable); System.out.println(toEncode + ": " + encoded); String decoded = decode(encoded, symTable); System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded); } public static void main(String[] args){ String symTable = "abcdefghijklmnopqrstuvwxyz"; test("broood", symTable); test("bananaaa", symTable); test("hiphophiphop", symTable); } }
Function mtf_encode(s) Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 1 To Len(s) char = Mid(s,i,1) If i = Len(s) Then output = output & symbol_table.IndexOf(char,0) symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char Else output = output & symbol_table.IndexOf(char,0) & " " symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_encode = output End Function Function mtf_decode(s) code = Split(s," ") Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 0 To UBound(code) char = symbol_table(code(i)) output = output & char If code(i) <> 0 Then symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_decode = output End Function wordlist = Array("broood","bananaaa","hiphophiphop") For Each word In wordlist WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_ mtf_decode(mtf_encode(word)) & "." WScript.StdOut.WriteBlankLines(1) Next
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.util.Scanner; import java.io.*; public class Program { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec("cmd /C dir"); Scanner sc = new Scanner(p.getInputStream()); while (sc.hasNext()) System.out.println(sc.nextLine()); } catch (IOException e) { System.out.println(e.getMessage()); } } }
Set objShell = CreateObject("WScript.Shell") objShell.Run "%comspec% /K dir",3,True
Translate this program into VB but keep the logic exactly as in Java.
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import javax.xml.ws.Holder; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class XmlValidation { public static void main(String... args) throws MalformedURLException { URL schemaLocation = new URL("http: URL documentLocation = new URL("http: if (validate(schemaLocation, documentLocation)) { System.out.println("document is valid"); } else { System.out.println("document is invalid"); } } public static boolean minimalValidate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.validate(new StreamSource(documentLocation.toString())); return true; } catch (Exception e) { return false; } } public static boolean validate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); final Holder<Boolean> valid = new Holder<>(true); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.setErrorHandler(new ErrorHandler(){ @Override public void warning(SAXParseException exception) { System.out.println("warning: " + exception.getMessage()); } @Override public void error(SAXParseException exception) { System.out.println("error: " + exception.getMessage()); valid.value = false; } @Override public void fatalError(SAXParseException exception) throws SAXException { System.out.println("fatal error: " + exception.getMessage()); throw exception; }}); validator.validate(new StreamSource(documentLocation.toString())); return valid.value; } catch (SAXException e) { return false; } catch (Exception e) { System.err.println(e); return false; } } }
Option explicit Function fileexists(fn) fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn) End Function Function xmlvalid(strfilename) Dim xmldoc,xmldoc2,objSchemas Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0") If fileexists(Replace(strfilename,".xml",".dtd")) Then xmlDoc.setProperty "ProhibitDTD", False xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then xmlDoc.setProperty "ProhibitDTD", True xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0") xmlDoc2.validateOnParse = True xmlDoc2.async = False xmlDoc2.load(Replace (strfilename,".xml",".xsd")) Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0") objSchemas.Add "", xmlDoc2 Else Set xmlvalid= Nothing:Exit Function End If Set xmlvalid=xmldoc.parseError End Function Sub displayerror (parserr) Dim strresult If parserr is Nothing Then strresult= "could not find dtd or xsd for " & strFileName Else With parserr Select Case .errorcode Case 0 strResult = "Valid: " & strFileName & vbCr Case Else strResult = vbCrLf & "ERROR! Failed to validate " & _ strFileName & vbCrLf &.reason & vbCr & _ "Error code: " & .errorCode & ", Line: " & _ .line & ", Character: " & _ .linepos & ", Source: """ & _ .srcText & """ - " & vbCrLf End Select End With End If WScript.Echo strresult End Sub Dim strfilename strfilename="shiporder.xml" displayerror xmlvalid (strfilename)
Write a version of this Java function in VB with identical behavior.
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>(); for (E x : n) { Node<E> node = new Node<E>(); node.value = x; int i = Collections.binarySearch(pileTops, node); if (i < 0) i = ~i; if (i != 0) node.pointer = pileTops.get(i-1); if (i != pileTops.size()) pileTops.set(i, node); else pileTops.add(node); } List<E> result = new ArrayList<E>(); for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1); node != null; node = node.pointer) result.add(node.value); Collections.reverse(result); return result; } private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> { public E value; public Node<E> pointer; public int compareTo(Node<E> y) { return value.compareTo(y.value); } } public static void main(String[] args) { List<Integer> d = Arrays.asList(3,2,6,4,5,1); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); } }
Function LIS(arr) n = UBound(arr) Dim p() ReDim p(n) Dim m() ReDim m(n) l = 0 For i = 0 To n lo = 1 hi = l Do While lo <= hi middle = Int((lo+hi)/2) If arr(m(middle)) < arr(i) Then lo = middle + 1 Else hi = middle - 1 End If Loop newl = lo p(i) = m(newl-1) m(newl) = i If newL > l Then l = newl End If Next Dim s() ReDim s(l) k = m(l) For i = l-1 To 0 Step - 1 s(i) = arr(k) k = p(k) Next LIS = Join(s,",") End Function WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1)) WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
Keep all operations the same but rewrite the snippet in VB.
import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import javafx.scene.transform.Rotate; import javafx.stage.Stage; public class DeathStar extends Application { private static final int DIVISION = 200; float radius = 300; @Override public void start(Stage primaryStage) throws Exception { Point3D otherSphere = new Point3D(-radius, 0, -radius * 1.5); final TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere); MeshView a = new MeshView(triangleMesh); a.setTranslateY(radius); a.setTranslateX(radius); a.setRotationAxis(Rotate.Y_AXIS); Scene scene = new Scene(new Group(a)); primaryStage.setScene(scene); primaryStage.show(); } static TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) { Rotate rotate = new Rotate(180, centerOtherSphere); final int div2 = division / 2; final int nPoints = division * (div2 - 1) + 2; final int nTPoints = (division + 1) * (div2 - 1) + division * 2; final int nFaces = division * (div2 - 2) * 2 + division * 2; final float rDiv = 1.f / division; float points[] = new float[nPoints * 3]; float tPoints[] = new float[nTPoints * 2]; int faces[] = new int[nFaces * 6]; int pPos = 0, tPos = 0; for (int y = 0; y < div2 - 1; ++y) { float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI; float sin_va = (float) Math.sin(va); float cos_va = (float) Math.cos(va); float ty = 0.5f + sin_va * 0.5f; for (int i = 0; i < division; ++i) { double a = rDiv * i * 2 * (float) Math.PI; float hSin = (float) Math.sin(a); float hCos = (float) Math.cos(a); points[pPos + 0] = hSin * cos_va * radius; points[pPos + 2] = hCos * cos_va * radius; points[pPos + 1] = sin_va * radius; final Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]); double distance = centerOtherSphere.distance(point3D); if (distance <= radius) { Point3D subtract = centerOtherSphere.subtract(point3D); Point3D transform = rotate.transform(subtract); points[pPos + 0] = (float) transform.getX(); points[pPos + 1] = (float) transform.getY(); points[pPos + 2] = (float) transform.getZ(); } tPoints[tPos + 0] = 1 - rDiv * i; tPoints[tPos + 1] = ty; pPos += 3; tPos += 2; } tPoints[tPos + 0] = 0; tPoints[tPos + 1] = ty; tPos += 2; } points[pPos + 0] = 0; points[pPos + 1] = -radius; points[pPos + 2] = 0; points[pPos + 3] = 0; points[pPos + 4] = radius; points[pPos + 5] = 0; pPos += 6; int pS = (div2 - 1) * division; float textureDelta = 1.f / 256; for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = textureDelta; tPos += 2; } for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = 1 - textureDelta; tPos += 2; } int fIndex = 0; for (int y = 0; y < div2 - 2; ++y) { for (int x = 0; x < division; ++x) { int p0 = y * division + x; int p1 = p0 + 1; int p2 = p0 + division; int p3 = p1 + division; int t0 = p0 + y; int t1 = t0 + 1; int t2 = t0 + division + 1; int t3 = t1 + division + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2; faces[fIndex + 5] = t2; fIndex += 6; faces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3; faces[fIndex + 1] = t3; faces[fIndex + 2] = p2; faces[fIndex + 3] = t2; faces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 5] = t1; fIndex += 6; } } int p0 = pS; int tB = (div2 - 1) * (division + 1); for (int x = 0; x < division; ++x) { int p2 = x, p1 = x + 1, t0 = tB + x; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 == division ? 0 : p1; faces[fIndex + 3] = p1; faces[fIndex + 4] = p2; faces[fIndex + 5] = p2; fIndex += 6; } p0 = p0 + 1; tB = tB + division; int pB = (div2 - 2) * division; for (int x = 0; x < division; ++x) { int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x; int t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2; faces[fIndex + 5] = t2; fIndex += 6; } TriangleMesh m = new TriangleMesh(); m.getPoints().setAll(points); m.getTexCoords().setAll(tPoints); m.getFaces().setAll(faces); return m; } public static void main(String[] args) { launch(args); } }
option explicit const x_=0 const y_=1 const z_=2 const r_=3 function clamp(x,b,t) if x<b then clamp=b elseif x>t then clamp =t else clamp=x end if end function function dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function function normal (byval v) dim ilen:ilen=1/sqr(dot(v,v)): v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen: normal=v: end function function hittest(s,x,y) dim z z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2 if z>=0 then z=sqr(z) hittest=array(s(z_)-z,s(z_)+z) else hittest=0 end if end function sub deathstar(pos, neg, sun, k, amb) dim x,y,shades,result,shade,hp,hn,xx,b shades=array(" ",".",":","!","*","o","e","&","#","%","@") for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5 hp=hittest (pos, x, y) hn=hittest(neg,x,y) if not isarray(hp) then result=0 elseif not isarray(hn) then result=1 elseif hn(0)>hp(0) then result=1 elseif hn(1)>hp(1) then result=0 elseif hn(1)>hp(0) then result=2 else result=1 end if shade=-1 select case result case 0 shade=0 case 1 xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_))) case 2 xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1))) end select if shade <>0 then b=dot(sun,xx)^k+amb shade=clamp((1-b) *ubound(shades),1,ubound(shades)) end if wscript.stdout.write string(2,shades(shade)) next wscript.stdout.write vbcrlf next end sub deathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1
Port the following code from Java to VB with equivalent syntax and logic.
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma; public class Test { static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2)); return sqs / avg; } static double x2Prob(double dof, double distance) { return Gamma.regularizedGammaQ(dof / 2, distance / 2); } static boolean x2IsUniform(double[] data, double significance) { return x2Prob(data.length - 1.0, x2Dist(data)) > significance; } public static void main(String[] a) { double[][] dataSets = {{199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}}; System.out.printf(" %4s %12s %12s %8s %s%n", "dof", "distance", "probability", "Uniform?", "dataset"); for (double[] ds : dataSets) { int dof = ds.length - 1; double dist = x2Dist(ds); double prob = x2Prob(dof, dist); System.out.printf("%4d %12.3f %12.8f %5s %6s%n", dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO", Arrays.toString(ds)); } } }
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print " Chi-squared test for given frequencies" Debug.Print "X-squared ="; ChiSquared; ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Public Sub test() Dim O() As Variant O = [{199809,200665,199607,200270,199649}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" O = [{522573,244456,139979,71531,21461}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" End Sub
Translate this program into VB but keep the logic exactly as in Java.
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) { System.out.println(); expand(s); } } public static void expand(String s) { expandR("", s, ""); } private static void expandR(String pre, String s, String suf) { int i1 = -1, i2 = 0; String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " "); StringBuilder sb = null; outer: while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) { i2 = i1 + 1; sb = new StringBuilder(s); for (int depth = 1; i2 < s.length() && depth > 0; i2++) { char c = noEscape.charAt(i2); depth = (c == '{') ? ++depth : depth; depth = (c == '}') ? --depth : depth; if (c == ',' && depth == 1) { sb.setCharAt(i2, '\u0000'); } else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1) break outer; } } if (i1 == -1) { if (suf.length() > 0) expandR(pre + s, suf, ""); else System.out.printf("%s%s%s%n", pre, s, suf); } else { for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1)) expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf); } } }
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If String.IsNullOrEmpty(s) Then Exit While End If out.AddRange(g) If s(0) = "}" Then If comma Then Return Tuple.Create(out, s.Substring(1)) End If Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1)) End If If s(0) = "," Then comma = True s = s.Substring(1) End If End While Return Nothing End Function Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String) Dim out As New List(Of String) From {""} While Not String.IsNullOrEmpty(s) Dim c = s(0) If depth > 0 AndAlso (c = "," OrElse c = "}") Then Return Tuple.Create(out, s) End If If c = "{" Then Dim x = GetGroup(s.Substring(1), depth + 1) If Not IsNothing(x) Then Dim tout As New List(Of String) For Each a In out For Each b In x.Item1 tout.Add(a + b) Next Next out = tout s = x.Item2 Continue While End If End If If c = "\" AndAlso s.Length > 1 Then c += s(1) s = s.Substring(1) End If out = out.Select(Function(a) a + c).ToList() s = s.Substring(1) End While Return Tuple.Create(out, s) End Function Sub Main() For Each s In { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\, again\, }}more }cowbell!", "{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" } Dim fmt = "{0}" + vbNewLine + vbTab + "{1}" Dim parts = GetItem(s) Dim res = String.Join(vbNewLine + vbTab, parts.Item1) Console.WriteLine(fmt, s, res) Next End Sub End Module
Port the following code from Java to VB with equivalent syntax and logic.
foo(); Int x = bar();
Function no_arguments() As String no_arguments = "ok" End Function Function fixed_number(argument1 As Integer, argument2 As Integer) fixed_number = argument1 + argument2 End Function Function optional_parameter(Optional argument1 = 1) As Integer optional_parameter = argument1 End Function Function variable_number(arguments As Variant) As Integer variable_number = UBound(arguments) End Function Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer named_arguments = argument1 + argument2 End Function Function statement() As String Debug.Print "function called as statement" statement = "ok" End Function Function return_value() As String return_value = "ok" End Function Sub foo() Debug.Print "subroutine", End Sub Function bar() As String bar = "function" End Function Function passed_by_value(ByVal s As String) As String s = "written over" passed_by_value = "passed by value" End Function Function passed_by_reference(ByRef s As String) As String s = "written over" passed_by_reference = "passed by reference" End Function Sub no_parentheses(myargument As String) Debug.Print myargument, End Sub Public Sub calling_a_function() Debug.Print "no arguments", , no_arguments Debug.Print "no arguments", , no_arguments() Debug.Print "fixed_number", , fixed_number(1, 1) Debug.Print "optional parameter", optional_parameter Debug.Print "optional parameter", optional_parameter(2) Debug.Print "variable number", variable_number([{"hello", "there"}]) Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1) statement s = "no_arguments" Debug.Print "first-class context", Application.Run(s) returnvalue = return_value Debug.Print "obtained return value", returnvalue foo Debug.Print , bar Dim t As String t = "unaltered" Debug.Print passed_by_value(t), t Debug.Print passed_by_reference(t), t no_parentheses "calling a subroutine" Debug.Print "does not require parentheses" Call no_parentheses("deprecated use") Debug.Print "of parentheses" End Sub
Write a version of this Java function in VB with identical behavior.
foo(); Int x = bar();
Function no_arguments() As String no_arguments = "ok" End Function Function fixed_number(argument1 As Integer, argument2 As Integer) fixed_number = argument1 + argument2 End Function Function optional_parameter(Optional argument1 = 1) As Integer optional_parameter = argument1 End Function Function variable_number(arguments As Variant) As Integer variable_number = UBound(arguments) End Function Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer named_arguments = argument1 + argument2 End Function Function statement() As String Debug.Print "function called as statement" statement = "ok" End Function Function return_value() As String return_value = "ok" End Function Sub foo() Debug.Print "subroutine", End Sub Function bar() As String bar = "function" End Function Function passed_by_value(ByVal s As String) As String s = "written over" passed_by_value = "passed by value" End Function Function passed_by_reference(ByRef s As String) As String s = "written over" passed_by_reference = "passed by reference" End Function Sub no_parentheses(myargument As String) Debug.Print myargument, End Sub Public Sub calling_a_function() Debug.Print "no arguments", , no_arguments Debug.Print "no arguments", , no_arguments() Debug.Print "fixed_number", , fixed_number(1, 1) Debug.Print "optional parameter", optional_parameter Debug.Print "optional parameter", optional_parameter(2) Debug.Print "variable number", variable_number([{"hello", "there"}]) Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1) statement s = "no_arguments" Debug.Print "first-class context", Application.Run(s) returnvalue = return_value Debug.Print "obtained return value", returnvalue foo Debug.Print , bar Dim t As String t = "unaltered" Debug.Print passed_by_value(t), t Debug.Print passed_by_reference(t), t no_parentheses "calling a subroutine" Debug.Print "does not require parentheses" Call no_parentheses("deprecated use") Debug.Print "of parentheses" End Sub
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class Interact extends JFrame{ final JTextField numberField; final JButton incButton, randButton; public Interact(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); numberField = new JTextField(); incButton = new JButton("Increment"); randButton = new JButton("Random"); numberField.setText("0"); numberField.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if(!Character.isDigit(e.getKeyChar())){ e.consume(); } } @Override public void keyReleased(KeyEvent e){} @Override public void keyPressed(KeyEvent e){} }); incButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = numberField.getText(); if(text.isEmpty()){ numberField.setText("1"); }else{ numberField.setText((Long.valueOf(text) + 1) + ""); } } }); randButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if(JOptionPane.showConfirmDialog(null, "Are you sure?") == JOptionPane.YES_OPTION){ numberField.setText(Long.toString((long)(Math.random() * Long.MAX_VALUE))); } } }); setLayout(new GridLayout(2, 1)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); buttonPanel.add(incButton); buttonPanel.add(randButton); add(numberField); add(buttonPanel); pack(); } public static void main(String[] args){ new Interact().setVisible(true); } }
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub Form_Load() Randomize Timer End Sub Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 Case Else KeyAscii = 0 End Select End Sub
Generate a VB translation of this Java snippet without changing its computational steps.
import java.util.Arrays; import java.util.Random; public class OneOfNLines { static Random rand; public static int oneOfN(int n) { int choice = 0; for(int i = 1; i < n; i++) { if(rand.nextInt(i+1) == 0) choice = i; } return choice; } public static void main(String[] args) { int n = 10; int trials = 1000000; int[] bins = new int[n]; rand = new Random(); for(int i = 0; i < trials; i++) bins[oneOfN(n)]++; System.out.println(Arrays.toString(bins)); } }
Dim chosen(10) For j = 1 To 1000000 c = one_of_n(10) chosen(c) = chosen(c) + 1 Next For k = 1 To 10 WScript.StdOut.WriteLine k & ". " & chosen(k) Next Function one_of_n(n) Randomize For i = 1 To n If Rnd(1) < 1/i Then one_of_n = i End If Next End Function
Port the following code from Java to VB with equivalent syntax and logic.
import java.util.HashMap; import java.util.Map; public class SpellingOfOrdinalNumbers { public static void main(String[] args) { for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) { System.out.printf("%d = %s%n", test, toOrdinal(test)); } } private static Map<String,String> ordinalMap = new HashMap<>(); static { ordinalMap.put("one", "first"); ordinalMap.put("two", "second"); ordinalMap.put("three", "third"); ordinalMap.put("five", "fifth"); ordinalMap.put("eight", "eighth"); ordinalMap.put("nine", "ninth"); ordinalMap.put("twelve", "twelfth"); } private static String toOrdinal(long n) { String spelling = numToString(n); String[] split = spelling.split(" "); String last = split[split.length - 1]; String replace = ""; if ( last.contains("-") ) { String[] lastSplit = last.split("-"); String lastWithDash = lastSplit[1]; String lastReplace = ""; if ( ordinalMap.containsKey(lastWithDash) ) { lastReplace = ordinalMap.get(lastWithDash); } else if ( lastWithDash.endsWith("y") ) { lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth"; } else { lastReplace = lastWithDash + "th"; } replace = lastSplit[0] + "-" + lastReplace; } else { if ( ordinalMap.containsKey(last) ) { replace = ordinalMap.get(last); } else if ( last.endsWith("y") ) { replace = last.substring(0, last.length() - 1) + "ieth"; } else { replace = last + "th"; } } split[split.length - 1] = replace; return String.join(" ", split); } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String numToString(long n) { return numToStringHelper(n); } private static final String numToStringHelper(long n) { if ( n < 0 ) { return "negative " + numToStringHelper(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : ""); } }
Private Function ordinal(s As String) As String Dim irregs As New Collection irregs.Add "first", "one" irregs.Add "second", "two" irregs.Add "third", "three" irregs.Add "fifth", "five" irregs.Add "eighth", "eight" irregs.Add "ninth", "nine" irregs.Add "twelfth", "twelve" Dim i As Integer For i = Len(s) To 1 Step -1 ch = Mid(s, i, 1) If ch = " " Or ch = "-" Then Exit For Next i On Error GoTo 1 ord = irregs(Right(s, Len(s) - i)) ordinal = Left(s, i) & ord Exit Function 1: If Right(s, 1) = "y" Then s = Left(s, Len(s) - 1) & "ieth" Else s = s & "th" End If ordinal = s End Function Public Sub ordinals() tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}] init For i = 1 To UBound(tests) Debug.Print ordinal(spell(tests(i))) Next i End Sub
Generate a VB translation of this Java snippet without changing its computational steps.
public class SelfDescribingNumbers{ public static boolean isSelfDescribing(int a){ String s = Integer.toString(a); for(int i = 0; i < s.length(); i++){ String s0 = s.charAt(i) + ""; int b = Integer.parseInt(s0); int count = 0; for(int j = 0; j < s.length(); j++){ int temp = Integer.parseInt(s.charAt(j) + ""); if(temp == i){ count++; } if (count > b) return false; } if(count != b) return false; } return true; } public static void main(String[] args){ for(int i = 0; i < 100000000; i++){ if(isSelfDescribing(i)){ System.out.println(i); } } } }
Function IsSelfDescribing(n) IsSelfDescribing = False Set digit = CreateObject("Scripting.Dictionary") For i = 1 To Len(n) k = Mid(n,i,1) If digit.Exists(k) Then digit.Item(k) = digit.Item(k) + 1 Else digit.Add k,1 End If Next c = 0 For j = 0 To Len(n)-1 l = Mid(n,j+1,1) If digit.Exists(CStr(j)) Then If digit.Item(CStr(j)) = CInt(l) Then c = c + 1 End If ElseIf l = 0 Then c = c + 1 Else Exit For End If Next If c = Len(n) Then IsSelfDescribing = True End If End Function start_time = Now s = "" For m = 1 To 100000000 If IsSelfDescribing(m) Then WScript.StdOut.WriteLine m End If Next end_time = Now WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
Translate this program into VB but keep the logic exactly as in Java.
public class AdditionChains { private static class Pair { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1]; result[0] = n; System.arraycopy(seq, 0, result, 1, seq.length); return result; } private static Pair check_seq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Pair(min_len, 0); else if (seq[0] == n) return new Pair(pos, 1); else if (pos < min_len) return try_perm(0, pos, seq, n, min_len); else return new Pair(min_len, 0); } private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Pair(min_len, 0); Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len); Pair res2 = try_perm(i + 1, pos, seq, n, res1.f); if (res2.f < res1.f) return res2; else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s); else throw new RuntimeException("Try_perm exception"); } private static Pair init_try_perm(int x) { return try_perm(0, 0, new int[]{1}, x, 12); } private static void find_brauer(int num) { Pair res = init_try_perm(num); System.out.println(); System.out.println("N = " + num); System.out.println("Minimum length of chains: L(n)= " + res.f); System.out.println("Number of minimum length Brauer chains: " + res.s); } public static void main(String[] args) { int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; for (int i : nums) { find_brauer(i); } } }
Module Module1 Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer) Dim result As New List(Of Integer) From { n } result.AddRange(seq) Return result End Function Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If pos > min_len OrElse seq(0) > n Then Return Tuple.Create(min_len, 0) End If If seq(0) = n Then Return Tuple.Create(pos, 1) End If If pos < min_len Then Return TryPerm(0, pos, seq, n, min_len) End If Return Tuple.Create(min_len, 0) End Function Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If i > pos Then Return Tuple.Create(min_len, 0) End If Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len) Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1) If res2.Item1 < res1.Item1 Then Return res2 End If If res2.Item1 = res1.Item1 Then Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2) End If Throw New Exception("TryPerm exception") End Function Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer) Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12) End Function Sub FindBrauer(num As Integer) Dim res = InitTryPerm(num) Console.WriteLine("N = {0}", num) Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1) Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2) Console.WriteLine() End Sub Sub Main() Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} Array.ForEach(nums, Sub(n) FindBrauer(n)) End Sub End Module
Change the programming language of this snippet from Java to VB without modifying what it does.
public class AdditionChains { private static class Pair { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1]; result[0] = n; System.arraycopy(seq, 0, result, 1, seq.length); return result; } private static Pair check_seq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Pair(min_len, 0); else if (seq[0] == n) return new Pair(pos, 1); else if (pos < min_len) return try_perm(0, pos, seq, n, min_len); else return new Pair(min_len, 0); } private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Pair(min_len, 0); Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len); Pair res2 = try_perm(i + 1, pos, seq, n, res1.f); if (res2.f < res1.f) return res2; else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s); else throw new RuntimeException("Try_perm exception"); } private static Pair init_try_perm(int x) { return try_perm(0, 0, new int[]{1}, x, 12); } private static void find_brauer(int num) { Pair res = init_try_perm(num); System.out.println(); System.out.println("N = " + num); System.out.println("Minimum length of chains: L(n)= " + res.f); System.out.println("Number of minimum length Brauer chains: " + res.s); } public static void main(String[] args) { int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; for (int i : nums) { find_brauer(i); } } }
Module Module1 Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer) Dim result As New List(Of Integer) From { n } result.AddRange(seq) Return result End Function Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If pos > min_len OrElse seq(0) > n Then Return Tuple.Create(min_len, 0) End If If seq(0) = n Then Return Tuple.Create(pos, 1) End If If pos < min_len Then Return TryPerm(0, pos, seq, n, min_len) End If Return Tuple.Create(min_len, 0) End Function Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If i > pos Then Return Tuple.Create(min_len, 0) End If Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len) Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1) If res2.Item1 < res1.Item1 Then Return res2 End If If res2.Item1 = res1.Item1 Then Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2) End If Throw New Exception("TryPerm exception") End Function Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer) Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12) End Function Sub FindBrauer(num As Integer) Dim res = InitTryPerm(num) Console.WriteLine("N = {0}", num) Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1) Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2) Console.WriteLine() End Sub Sub Main() Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} Array.ForEach(nums, Sub(n) FindBrauer(n)) End Sub End Module
Produce a functionally identical VB code for the snippet given in Java.
import java.util.function.Consumer; import java.util.stream.IntStream; public class Repeat { public static void main(String[] args) { repeat(3, (x) -> System.out.println("Example " + x)); } static void repeat (int n, Consumer<Integer> fun) { IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); } }
Private Sub Repeat(rid As String, n As Integer) For i = 1 To n Application.Run rid Next i End Sub Private Sub Hello() Debug.Print "Hello" End Sub Public Sub main() Repeat "Hello", 5 End Sub
Rewrite the snippet below in VB so it works the same as the original Java code.
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; now.display1D(arr1); System.out.println(now.getSparkline(arr1)); } public void display1D(float[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public String getSparkline(float[] arr) { float min=Integer.MAX_VALUE; float max=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } float range=max-min; int num=bars.length()-1; String line=""; for(int i=0;i<arr.length;i++) { line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num))); } return line; } }
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_ chrw(&h2586)&chrw(&h2587)&chrw(&h2588) nn=8 end sub public function bg (s) a=split(replace(replace(s,","," ")," "," ")," ") mn=999999:mx=-999999:cnt=ubound(a)+1 for i=0 to ubound(a) a(i)=cdbl(trim(a(i))) if a(i)>mx then mx=a(i) if a(i)<mn then mn=a(i) next ss="Data: " for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next ss=ss+vbcrlf + "sparkline: " for i=0 to ubound(a) x=scale(a(i)) ss=ss & string(6,mid(bar,x,1)) next bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _ " cnt: "& ubound(a)+1 &vbcrlf end function private function scale(x) if x=<mn then scale=1 elseif x>=mx then scale=nn else scale=int(nn* (x-mn)/(mx-mn)+1) end if end function end class ensure_cscript set b=new bargraph wscript.stdout.writeblanklines 2 wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1") wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") wscript.echo b.bg("0, 1, 19, 20") wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999") set b=nothing wscript.echo "If bars don "font to DejaVu Sans Mono or any other that has the bargrph characters" & _ vbcrlf wscript.stdout.write "Press any key.." : wscript.stdin.read 1
Translate the given Java code snippet into VB without altering its behavior.
System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
Private Function mul_inv(a As Long, n As Long) As Variant If n < 0 Then n = -n If a < 0 Then a = n - ((-a) Mod n) Dim t As Long: t = 0 Dim nt As Long: nt = 1 Dim r As Long: r = n Dim nr As Long: nr = a Dim q As Long Do While nr <> 0 q = r \ nr tmp = t t = nt nt = tmp - q * nt tmp = r r = nr nr = tmp - q * nr Loop If r > 1 Then mul_inv = "a is not invertible" Else If t < 0 Then t = t + n mul_inv = t End If End Function Public Sub mi() Debug.Print mul_inv(42, 2017) Debug.Print mul_inv(40, 1) Debug.Print mul_inv(52, -217) Debug.Print mul_inv(-486, 217) Debug.Print mul_inv(40, 2018) End Sub
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class HelloWorld{ public static void main(String[] args) throws IOException{ ServerSocket listener = new ServerSocket(8080); while(true){ Socket sock = listener.accept(); new PrintWriter(sock.getOutputStream(), true). println("Goodbye, World!"); sock.close(); } } }
Class HTTPSock Inherits TCPSocket Event Sub DataAvailable() Dim headers As New InternetHeaders headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!"))) headers.AppendHeader("Content-Type", "text/plain") headers.AppendHeader("Content-Encoding", "identity") headers.AppendHeader("Connection", "close") Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!" Me.Write(data) Me.Close End Sub End Class Class HTTPServ Inherits ServerSocket Event Sub AddSocket() As TCPSocket Return New HTTPSock End Sub End Class Class App Inherits Application Event Sub Run(Args() As String) Dim sock As New HTTPServ sock.Port = 8080 sock.Listen() While True App.DoEvents Wend End Sub End Class
Rewrite the snippet below in VB so it works the same as the original Java code.
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
System.Console.Clear()
Change the following Java code into VB without altering its purpose.
public class PancakeSort { int[] heap; public String toString() { String info = ""; for (int x: heap) info += x + " "; return info; } public void flip(int n) { for (int i = 0; i < (n+1) / 2; ++i) { int tmp = heap[i]; heap[i] = heap[n-i]; heap[n-i] = tmp; } System.out.println("flip(0.." + n + "): " + toString()); } public int[] minmax(int n) { int xm, xM; xm = xM = heap[0]; int posm = 0, posM = 0; for (int i = 1; i < n; ++i) { if (heap[i] < xm) { xm = heap[i]; posm = i; } else if (heap[i] > xM) { xM = heap[i]; posM = i; } } return new int[] {posm, posM}; } public void sort(int n, int dir) { if (n == 0) return; int[] mM = minmax(n); int bestXPos = mM[dir]; int altXPos = mM[1-dir]; boolean flipped = false; if (bestXPos == n-1) { --n; } else if (bestXPos == 0) { flip(n-1); --n; } else if (altXPos == n-1) { dir = 1-dir; --n; flipped = true; } else { flip(bestXPos); } sort(n, dir); if (flipped) { flip(n); } } PancakeSort(int[] numbers) { heap = numbers; sort(numbers.length, 1); } public static void main(String[] args) { int[] numbers = new int[args.length]; for (int i = 0; i < args.length; ++i) numbers[i] = Integer.valueOf(args[i]); PancakeSort pancakes = new PancakeSort(numbers); System.out.println(pancakes); } }
Public Sub printarray(A) For i = LBound(A) To UBound(A) Debug.Print A(i), Next Debug.Print End Sub Public Sub Flip(ByRef A, p1, p2, trace) If trace Then Debug.Print "we Cut = Int((p2 - p1 + 1) / 2) For i = 0 To Cut - 1 temp = A(i) A(i) = A(p2 - i) A(p2 - i) = temp Next End Sub Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False) lb = LBound(A) ub = UBound(A) Length = ub - lb + 1 If Length <= 1 Then Exit Sub End If For i = ub To lb + 1 Step -1 P = lb Maximum = A(P) For j = lb + 1 To i If A(j) > Maximum Then P = j Maximum = A(j) End If Next j If P < i Then If P > 1 Then Flip A, lb, P, trace If trace Then printarray A End If Flip A, lb, i, trace If trace Then printarray A End If Next i End Sub Public Sub TestPancake(Optional trace As Boolean = False) Dim A() A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0) Debug.Print "Initial array:" printarray A pancakesort A, trace Debug.Print "Final array:" printarray A End Sub
Generate a VB translation of this Java snippet without changing its computational steps.
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; public class ChemicalCalculator { private static final Map<String, Double> atomicMass = new HashMap<>(); static { atomicMass.put("H", 1.008); atomicMass.put("He", 4.002602); atomicMass.put("Li", 6.94); atomicMass.put("Be", 9.0121831); atomicMass.put("B", 10.81); atomicMass.put("C", 12.011); atomicMass.put("N", 14.007); atomicMass.put("O", 15.999); atomicMass.put("F", 18.998403163); atomicMass.put("Ne", 20.1797); atomicMass.put("Na", 22.98976928); atomicMass.put("Mg", 24.305); atomicMass.put("Al", 26.9815385); atomicMass.put("Si", 28.085); atomicMass.put("P", 30.973761998); atomicMass.put("S", 32.06); atomicMass.put("Cl", 35.45); atomicMass.put("Ar", 39.948); atomicMass.put("K", 39.0983); atomicMass.put("Ca", 40.078); atomicMass.put("Sc", 44.955908); atomicMass.put("Ti", 47.867); atomicMass.put("V", 50.9415); atomicMass.put("Cr", 51.9961); atomicMass.put("Mn", 54.938044); atomicMass.put("Fe", 55.845); atomicMass.put("Co", 58.933194); atomicMass.put("Ni", 58.6934); atomicMass.put("Cu", 63.546); atomicMass.put("Zn", 65.38); atomicMass.put("Ga", 69.723); atomicMass.put("Ge", 72.630); atomicMass.put("As", 74.921595); atomicMass.put("Se", 78.971); atomicMass.put("Br", 79.904); atomicMass.put("Kr", 83.798); atomicMass.put("Rb", 85.4678); atomicMass.put("Sr", 87.62); atomicMass.put("Y", 88.90584); atomicMass.put("Zr", 91.224); atomicMass.put("Nb", 92.90637); atomicMass.put("Mo", 95.95); atomicMass.put("Ru", 101.07); atomicMass.put("Rh", 102.90550); atomicMass.put("Pd", 106.42); atomicMass.put("Ag", 107.8682); atomicMass.put("Cd", 112.414); atomicMass.put("In", 114.818); atomicMass.put("Sn", 118.710); atomicMass.put("Sb", 121.760); atomicMass.put("Te", 127.60); atomicMass.put("I", 126.90447); atomicMass.put("Xe", 131.293); atomicMass.put("Cs", 132.90545196); atomicMass.put("Ba", 137.327); atomicMass.put("La", 138.90547); atomicMass.put("Ce", 140.116); atomicMass.put("Pr", 140.90766); atomicMass.put("Nd", 144.242); atomicMass.put("Pm", 145.0); atomicMass.put("Sm", 150.36); atomicMass.put("Eu", 151.964); atomicMass.put("Gd", 157.25); atomicMass.put("Tb", 158.92535); atomicMass.put("Dy", 162.500); atomicMass.put("Ho", 164.93033); atomicMass.put("Er", 167.259); atomicMass.put("Tm", 168.93422); atomicMass.put("Yb", 173.054); atomicMass.put("Lu", 174.9668); atomicMass.put("Hf", 178.49); atomicMass.put("Ta", 180.94788); atomicMass.put("W", 183.84); atomicMass.put("Re", 186.207); atomicMass.put("Os", 190.23); atomicMass.put("Ir", 192.217); atomicMass.put("Pt", 195.084); atomicMass.put("Au", 196.966569); atomicMass.put("Hg", 200.592); atomicMass.put("Tl", 204.38); atomicMass.put("Pb", 207.2); atomicMass.put("Bi", 208.98040); atomicMass.put("Po", 209.0); atomicMass.put("At", 210.0); atomicMass.put("Rn", 222.0); atomicMass.put("Fr", 223.0); atomicMass.put("Ra", 226.0); atomicMass.put("Ac", 227.0); atomicMass.put("Th", 232.0377); atomicMass.put("Pa", 231.03588); atomicMass.put("U", 238.02891); atomicMass.put("Np", 237.0); atomicMass.put("Pu", 244.0); atomicMass.put("Am", 243.0); atomicMass.put("Cm", 247.0); atomicMass.put("Bk", 247.0); atomicMass.put("Cf", 251.0); atomicMass.put("Es", 252.0); atomicMass.put("Fm", 257.0); atomicMass.put("Uue", 315.0); atomicMass.put("Ubn", 299.0); } private static double evaluate(String s) { String sym = s + "["; double sum = 0.0; StringBuilder symbol = new StringBuilder(); String number = ""; for (int i = 0; i < sym.length(); ++i) { char c = sym.charAt(i); if ('@' <= c && c <= '[') { int n = 1; if (!number.isEmpty()) { n = Integer.parseInt(number); } if (symbol.length() > 0) { sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n; } if (c == '[') { break; } symbol = new StringBuilder(String.valueOf(c)); number = ""; } else if ('a' <= c && c <= 'z') { symbol.append(c); } else if ('0' <= c && c <= '9') { number += c; } else { throw new RuntimeException("Unexpected symbol " + c + " in molecule"); } } return sum; } private static String replaceParens(String s) { char letter = 'a'; String si = s; while (true) { int start = si.indexOf('('); if (start == -1) { break; } for (int i = start + 1; i < si.length(); ++i) { if (si.charAt(i) == ')') { String expr = si.substring(start + 1, i); String symbol = "@" + letter; String pattern = Pattern.quote(si.substring(start, i + 1)); si = si.replaceFirst(pattern, symbol); atomicMass.put(symbol, evaluate(expr)); letter++; break; } if (si.charAt(i) == '(') { start = i; } } } return si; } public static void main(String[] args) { List<String> molecules = List.of( "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" ); for (String molecule : molecules) { double mass = evaluate(replaceParens(molecule)); System.out.printf("%17s -> %7.3f\n", molecule, mass); } } }
Module Module1 Dim atomicMass As New Dictionary(Of String, Double) From { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.63}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.9055}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.71}, {"Sb", 121.76}, {"Te", 127.6}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.5}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.9804}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299} } Function Evaluate(s As String) As Double s += "[" Dim sum = 0.0 Dim symbol = "" Dim number = "" For i = 1 To s.Length Dim c = s(i - 1) If "@" <= c AndAlso c <= "[" Then Dim n = 1 If number <> "" Then n = Integer.Parse(number) End If If symbol <> "" Then sum += atomicMass(symbol) * n End If If c = "[" Then Exit For End If symbol = c.ToString number = "" ElseIf "a" <= c AndAlso c <= "z" Then symbol += c ElseIf "0" <= c AndAlso c <= "9" Then number += c Else Throw New Exception(String.Format("Unexpected symbol {0} in molecule", c)) End If Next Return sum End Function Function ReplaceFirst(text As String, search As String, replace As String) As String Dim pos = text.IndexOf(search) If pos < 0 Then Return text Else Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length) End If End Function Function ReplaceParens(s As String) As String Dim letter = "s"c While True Dim start = s.IndexOf("(") If start = -1 Then Exit While End If For i = start + 1 To s.Length - 1 If s(i) = ")" Then Dim expr = s.Substring(start + 1, i - start - 1) Dim symbol = String.Format("@{0}", letter) s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol) atomicMass(symbol) = Evaluate(expr) letter = Chr(Asc(letter) + 1) Exit For End If If s(i) = "(" Then start = i Continue For End If Next End While Return s End Function Sub Main() Dim molecules() As String = { "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" } For Each molecule In molecules Dim mass = Evaluate(ReplaceParens(molecule)) Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass) Next End Sub End Module
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); } private static List<Long> getPythagoreanQuadruples(long max) { List<Long> list = new ArrayList<>(); long n = -1; long m = -1; while ( true ) { long nTest = (long) Math.pow(2, n+1); long mTest = (long) (5L * Math.pow(2, m+1)); long test = 0; if ( nTest > mTest ) { test = mTest; m++; } else { test = nTest; n++; } if ( test < max ) { list.add(test); } else { break; } } return list; } }
Const n = 2200 Public Sub pq() Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3 Dim l(n) As Boolean, l_add(9680000) As Boolean For x = 1 To n x2 = x * x For y = x To n l_add(x2 + y * y) = True Next y Next x For x = 1 To n s1 = s s = s + 2 s2 = s For y = x + 1 To n If l_add(s1) Then l(y) = True s1 = s1 + s2 s2 = s2 + 2 Next Next For x = 1 To n If Not l(x) Then Debug.Print x; Next Debug.Print End Sub
Translate the given Java code snippet into VB without altering its behavior.
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); disableOption("needspeeling"); setOption("numberofbananas", "1024"); addOption("numberofstrawberries", "62000"); store(); } } private enum EntryType { EMPTY, ENABLED, DISABLED, COMMENT } private static class Entry { EntryType type; String name, value; Entry(EntryType t, String n, String v) { type = t; name = n; value = v; } } private static Map<String, Entry> entries = new LinkedHashMap<>(); private static String path; private static boolean readConfig(String p) { path = p; File f = new File(path); if (!f.exists() || f.isDirectory()) return false; String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)"; Pattern regex = Pattern.compile(regexString); try (Scanner sc = new Scanner(new FileReader(f))){ int emptyLines = 0; String line; while (sc.hasNext()) { line = sc.nextLine().trim(); if (line.isEmpty()) { addOption("" + emptyLines++, null, EntryType.EMPTY); } else if (line.charAt(0) == '#') { entries.put(line, new Entry(EntryType.COMMENT, line, null)); } else { line = line.replaceAll("[^a-zA-Z0-9\\x20;]", ""); Matcher m = regex.matcher(line); if (m.find() && !m.group(2).isEmpty()) { EntryType t = EntryType.ENABLED; if (!m.group(1).isEmpty()) t = EntryType.DISABLED; addOption(m.group(2), m.group(3), t); } } } } catch (IOException e) { System.out.println(e); } return true; } private static void addOption(String name, String value) { addOption(name, value, EntryType.ENABLED); } private static void addOption(String name, String value, EntryType t) { name = name.toUpperCase(); entries.put(name, new Entry(t, name, value)); } private static void enableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.ENABLED; } private static void disableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.DISABLED; } private static void setOption(String name, String value) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.value = value; } private static void store() { try (PrintWriter pw = new PrintWriter(path)) { for (Entry e : entries.values()) { switch (e.type) { case EMPTY: pw.println(); break; case ENABLED: pw.format("%s %s%n", e.name, e.value); break; case DISABLED: pw.format("; %s %s%n", e.name, e.value); break; case COMMENT: pw.println(e.name); break; default: break; } } if (pw.checkError()) { throw new IOException("writing to file failed"); } } catch (IOException e) { System.out.println(e); } } }
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With Set objFSO = Nothing Set objParamLookup = Nothing
Port the provided Java code into VB while preserving the original functionality.
import java.util.*; public class PracticalNumbers { public static void main(String[] args) { final int from = 1; final int to = 333; List<Integer> practical = new ArrayList<>(); for (int i = from; i <= to; ++i) { if (isPractical(i)) practical.add(i); } System.out.printf("Found %d practical numbers between %d and %d:\n%s\n", practical.size(), from, to, shorten(practical, 10)); printPractical(666); printPractical(6666); printPractical(66666); printPractical(672); printPractical(720); printPractical(222222); } private static void printPractical(int n) { if (isPractical(n)) System.out.printf("%d is a practical number.\n", n); else System.out.printf("%d is not a practical number.\n", n); } private static boolean isPractical(int n) { int[] divisors = properDivisors(n); for (int i = 1; i < n; ++i) { if (!sumOfAnySubset(i, divisors, divisors.length)) return false; } return true; } private static boolean sumOfAnySubset(int n, int[] f, int len) { if (len == 0) return false; int total = 0; for (int i = 0; i < len; ++i) { if (n == f[i]) return true; total += f[i]; } if (n == total) return true; if (n > total) return false; --len; int d = n - f[len]; return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len); } private static int[] properDivisors(int n) { List<Integer> divisors = new ArrayList<>(); divisors.add(1); for (int i = 2;; ++i) { int i2 = i * i; if (i2 > n) break; if (n % i == 0) { divisors.add(i); if (i2 != n) divisors.add(n / i); } } int[] result = new int[divisors.size()]; for (int i = 0; i < result.length; ++i) result[i] = divisors.get(i); Arrays.sort(result); return result; } private static String shorten(List<Integer> list, int n) { StringBuilder str = new StringBuilder(); int len = list.size(), i = 0; if (n > 0 && len > 0) str.append(list.get(i++)); for (; i < n && i < len; ++i) { str.append(", "); str.append(list.get(i)); } if (len > i + n) { if (n > 0) str.append(", ..."); i = len - n; } for (; i < len; ++i) { str.append(", "); str.append(list.get(i)); } return str.toString(); } }
Imports System.Collections.Generic, System.Linq, System.Console Module Module1 Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean If n <= 0 Then Return False Else If f.Contains(n) Then Return True Select Case n.CompareTo(f.Sum()) Case 1 : Return False : Case 0 : Return True Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf) End Select : Return true End Function Function ip(ByVal n As Integer) As Boolean Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList() Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f)) End Function Sub Main() Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m If ip(i) OrElse i = 1 Then c += 1 : Write("{0,3} {1}", i, If(c Mod 10 = 0, vbLf, "")) i += If(i = 1, 1, 2) : End While Write(vbLf & "Found {0} practical numbers between 1 and {1} inclusive." & vbLf, c, m) Do : m = If(m < 500, m << 1, m * 10 + 6) Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4 End Sub End Module
Preserve the algorithm and functionality while converting the code from Java to VB.
1. 1.0 2432311.7567374 1.234E-10 1.234e-10 758832d 728832f 1.0f 758832D 728832F 1.0F 1 / 2. 1 / 2
Sub Main() Dim d As Double Dim s As Single d = -12.3456 d = 1000# d = 0.00001 d = 67# d = 8.9 d = 0.33 d = 0# d = 2# * 10 ^ 3 d = 2E+50 d = 2E-50 s = -12.3456! s = 1000! s = 0.00001! s = 67! s = 8.9! s = 0.33! s = 0! s = 2! * 10 ^ 3 End Sub
Ensure the translated VB code behaves exactly like the original Java snippet.
import java.io.*; import static java.lang.String.format; import java.util.*; public class WordSearch { static class Grid { int numAttempts; char[][] cells = new char[nRows][nCols]; List<String> solutions = new ArrayList<>(); } final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; final static int nRows = 10; final static int nCols = 10; final static int gridSize = nRows * nCols; final static int minWords = 25; final static Random rand = new Random(); public static void main(String[] args) { printResult(createWordSearch(readWords("unixdict.txt"))); } static List<String> readWords(String filename) { int maxLen = Math.max(nRows, nCols); List<String> words = new ArrayList<>(); try (Scanner sc = new Scanner(new FileReader(filename))) { while (sc.hasNext()) { String s = sc.next().trim().toLowerCase(); if (s.matches("^[a-z]{3," + maxLen + "}$")) words.add(s); } } catch (FileNotFoundException e) { System.out.println(e); } return words; } static Grid createWordSearch(List<String> words) { Grid grid = null; int numAttempts = 0; outer: while (++numAttempts < 100) { Collections.shuffle(words); grid = new Grid(); int messageLen = placeMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; for (String word : words) { cellsFilled += tryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.solutions.size() >= minWords) { grid.numAttempts = numAttempts; break outer; } else break; } } } return grid; } static int placeMessage(Grid grid, String msg) { msg = msg.toUpperCase().replaceAll("[^A-Z]", ""); int messageLen = msg.length(); if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen; for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.nextInt(gapSize); grid.cells[pos / nCols][pos % nCols] = msg.charAt(i); } return messageLen; } return 0; } static int tryPlaceWord(Grid grid, String word) { int randDir = rand.nextInt(dirs.length); int randPos = rand.nextInt(gridSize); for (int dir = 0; dir < dirs.length; dir++) { dir = (dir + randDir) % dirs.length; for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize; int lettersPlaced = tryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; } static int tryLocation(Grid grid, String word, int dir, int pos) { int r = pos / nCols; int c = pos % nCols; int len = word.length(); if ((dirs[dir][0] == 1 && (len + c) > nCols) || (dirs[dir][0] == -1 && (len - 1) > c) || (dirs[dir][1] == 1 && (len + r) > nRows) || (dirs[dir][1] == -1 && (len - 1) > r)) return 0; int rr, cc, i, overlaps = 0; for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i)) return 0; cc += dirs[dir][0]; rr += dirs[dir][1]; } for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.cells[rr][cc] == word.charAt(i)) overlaps++; else grid.cells[rr][cc] = word.charAt(i); if (i < len - 1) { cc += dirs[dir][0]; rr += dirs[dir][1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.solutions.add(format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)); } return lettersPlaced; } static void printResult(Grid grid) { if (grid == null || grid.numAttempts == 0) { System.out.println("No grid to display"); return; } int size = grid.solutions.size(); System.out.println("Attempts: " + grid.numAttempts); System.out.println("Number of words: " + size); System.out.println("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { System.out.printf("%n%d ", r); for (int c = 0; c < nCols; c++) System.out.printf(" %c ", grid.cells[r][c]); } System.out.println("\n"); for (int i = 0; i < size - 1; i += 2) { System.out.printf("%s %s%n", grid.solutions.get(i), grid.solutions.get(i + 1)); } if (size % 2 == 1) System.out.println(grid.solutions.get(size - 1)); } }
Module Module1 ReadOnly Dirs As Integer(,) = { {1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1} } Const RowCount = 10 Const ColCount = 10 Const GridSize = RowCount * ColCount Const MinWords = 25 Class Grid Public cells(RowCount - 1, ColCount - 1) As Char Public solutions As New List(Of String) Public numAttempts As Integer Sub New() For i = 0 To RowCount - 1 For j = 0 To ColCount - 1 cells(i, j) = ControlChars.NullChar Next Next End Sub End Class Dim Rand As New Random() Sub Main() PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))) End Sub Function ReadWords(filename As String) As List(Of String) Dim maxlen = Math.Max(RowCount, ColCount) Dim words As New List(Of String) Dim objReader As New IO.StreamReader(filename) Dim line As String Do While objReader.Peek() <> -1 line = objReader.ReadLine() If line.Length > 3 And line.Length < maxlen Then If line.All(Function(c) Char.IsLetter(c)) Then words.Add(line) End If End If Loop Return words End Function Function CreateWordSearch(words As List(Of String)) As Grid For numAttempts = 1 To 1000 Shuffle(words) Dim grid As New Grid() Dim messageLen = PlaceMessage(grid, "Rosetta Code") Dim target = GridSize - messageLen Dim cellsFilled = 0 For Each word In words cellsFilled = cellsFilled + TryPlaceWord(grid, word) If cellsFilled = target Then If grid.solutions.Count >= MinWords Then grid.numAttempts = numAttempts Return grid Else Exit For End If End If Next Next Return Nothing End Function Function PlaceMessage(grid As Grid, msg As String) As Integer msg = msg.ToUpper() msg = msg.Replace(" ", "") If msg.Length > 0 And msg.Length < GridSize Then Dim gapSize As Integer = GridSize / msg.Length Dim pos = 0 Dim lastPos = -1 For i = 0 To msg.Length - 1 If i = 0 Then pos = pos + Rand.Next(gapSize - 1) Else pos = pos + Rand.Next(2, gapSize - 1) End If Dim r As Integer = Math.Floor(pos / ColCount) Dim c = pos Mod ColCount grid.cells(r, c) = msg(i) lastPos = pos Next Return msg.Length End If Return 0 End Function Function TryPlaceWord(grid As Grid, word As String) As Integer Dim randDir = Rand.Next(Dirs.GetLength(0)) Dim randPos = Rand.Next(GridSize) For d = 0 To Dirs.GetLength(0) - 1 Dim dd = (d + randDir) Mod Dirs.GetLength(0) For p = 0 To GridSize - 1 Dim pp = (p + randPos) Mod GridSize Dim lettersPLaced = TryLocation(grid, word, dd, pp) If lettersPLaced > 0 Then Return lettersPLaced End If Next Next Return 0 End Function Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer Dim r As Integer = pos / ColCount Dim c = pos Mod ColCount Dim len = word.Length If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then Return 0 End If If r = RowCount OrElse c = ColCount Then Return 0 End If Dim rr = r Dim cc = c For i = 0 To len - 1 If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then Return 0 End If cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) Next Dim overlaps = 0 rr = r cc = c For i = 0 To len - 1 If grid.cells(rr, cc) = word(i) Then overlaps = overlaps + 1 Else grid.cells(rr, cc) = word(i) End If If i < len - 1 Then cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) End If Next Dim lettersPlaced = len - overlaps If lettersPlaced > 0 Then grid.solutions.Add(String.Format("{0,-10} ({1},{2})({3},{4})", word, c, r, cc, rr)) End If Return lettersPlaced End Function Sub PrintResult(grid As Grid) If IsNothing(grid) OrElse grid.numAttempts = 0 Then Console.WriteLine("No grid to display") Return End If Console.WriteLine("Attempts: {0}", grid.numAttempts) Console.WriteLine("Number of words: {0}", GridSize) Console.WriteLine() Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9") For r = 0 To RowCount - 1 Console.WriteLine() Console.Write("{0} ", r) For c = 0 To ColCount - 1 Console.Write(" {0} ", grid.cells(r, c)) Next Next Console.WriteLine() Console.WriteLine() For i = 0 To grid.solutions.Count - 1 If i Mod 2 = 0 Then Console.Write("{0}", grid.solutions(i)) Else Console.WriteLine(" {0}", grid.solutions(i)) End If Next Console.WriteLine() End Sub Sub Shuffle(Of T)(list As IList(Of T)) Dim r As Random = New Random() For i = 0 To list.Count - 1 Dim index As Integer = r.Next(i, list.Count) If i <> index Then Dim temp As T = list(i) list(i) = list(index) list(index) = temp End If Next End Sub End Module
Change the programming language of this snippet from Java to VB without modifying what it does.
module BreakOO { class Exposed { public String pub = "public"; protected String pro = "protected"; private String pri = "private"; @Override String toString() { return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}"; } } void run() { @Inject Console console; Exposed expo = new Exposed(); console.print($"before: {expo}"); expo.pub = $"this was {expo.pub}"; assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed)); expoPro.pro = $"this was {expoPro.pro}"; assert (private Exposed) expoPri := &expo.revealAs((private Exposed)); expoPri.pri = $"this was {expoPri.pri}"; assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed)); expoStr.pub = $"{expoStr.pub}!!!"; expoStr.pro = $"{expoStr.pro}!!!"; expoStr.pri = $"{expoStr.pri}!!!"; console.print($"after: {expo}"); } }
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
Preserve the algorithm and functionality while converting the code from Java to VB.
module BreakOO { class Exposed { public String pub = "public"; protected String pro = "protected"; private String pri = "private"; @Override String toString() { return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}"; } } void run() { @Inject Console console; Exposed expo = new Exposed(); console.print($"before: {expo}"); expo.pub = $"this was {expo.pub}"; assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed)); expoPro.pro = $"this was {expoPro.pro}"; assert (private Exposed) expoPri := &expo.revealAs((private Exposed)); expoPri.pri = $"this was {expoPri.pri}"; assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed)); expoStr.pub = $"{expoStr.pub}!!!"; expoStr.pro = $"{expoStr.pro}!!!"; expoStr.pri = $"{expoStr.pri}!!!"; console.print($"after: {expo}"); } }
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
Ensure the translated VB code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Eertree { public static void main(String[] args) { List<Node> tree = eertree("eertree"); List<String> result = subPalindromes(tree); System.out.println(result); } private static class Node { int length; Map<Character, Integer> edges = new HashMap<>(); int suffix; public Node(int length) { this.length = length; } public Node(int length, Map<Character, Integer> edges, int suffix) { this.length = length; this.edges = edges != null ? edges : new HashMap<>(); this.suffix = suffix; } } private static final int EVEN_ROOT = 0; private static final int ODD_ROOT = 1; private static List<Node> eertree(String s) { List<Node> tree = new ArrayList<>(); tree.add(new Node(0, null, ODD_ROOT)); tree.add(new Node(-1, null, ODD_ROOT)); int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); for (n = suffix; ; n = tree.get(n).suffix) { k = tree.get(n).length; int b = i - k - 1; if (b >= 0 && s.charAt(b) == c) { break; } } if (tree.get(n).edges.containsKey(c)) { suffix = tree.get(n).edges.get(c); continue; } suffix = tree.size(); tree.add(new Node(k + 2)); tree.get(n).edges.put(c, suffix); if (tree.get(suffix).length == 1) { tree.get(suffix).suffix = 0; continue; } while (true) { n = tree.get(n).suffix; int b = i - tree.get(n).length - 1; if (b >= 0 && s.charAt(b) == c) { break; } } tree.get(suffix).suffix = tree.get(n).edges.get(c); } return tree; } private static List<String> subPalindromes(List<Node> tree) { List<String> s = new ArrayList<>(); subPalindromes_children(0, "", tree, s); for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) { String ct = String.valueOf(cm.getKey()); s.add(ct); subPalindromes_children(cm.getValue(), ct, tree, s); } return s; } private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) { for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) { Character c = cm.getKey(); Integer m = cm.getValue(); String pl = c + p + c; s.add(pl); subPalindromes_children(m, pl, tree, s); } } }
Module Module1 Class Node Public Sub New(Len As Integer) Length = Len Edges = New Dictionary(Of Char, Integer) End Sub Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer) Length = len Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg) Suffix = suf End Sub Property Edges As Dictionary(Of Char, Integer) Property Length As Integer Property Suffix As Integer End Class ReadOnly EVEN_ROOT As Integer = 0 ReadOnly ODD_ROOT As Integer = 1 Function Eertree(s As String) As List(Of Node) Dim tree As New List(Of Node) From { New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT), New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT) } Dim suffix = ODD_ROOT Dim n As Integer Dim k As Integer For i = 1 To s.Length Dim c = s(i - 1) n = suffix While True k = tree(n).Length Dim b = i - k - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If n = tree(n).Suffix End While If tree(n).Edges.ContainsKey(c) Then suffix = tree(n).Edges(c) Continue For End If suffix = tree.Count tree.Add(New Node(k + 2)) tree(n).Edges(c) = suffix If tree(suffix).Length = 1 Then tree(suffix).Suffix = 0 Continue For End If While True n = tree(n).Suffix Dim b = i - tree(n).Length - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If End While Dim a = tree(n) Dim d = a.Edges(c) Dim e = tree(suffix) e.Suffix = d Next Return tree End Function Function SubPalindromes(tree As List(Of Node)) As List(Of String) Dim s As New List(Of String) Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String) For Each c In tree(n).Edges.Keys Dim m = tree(n).Edges(c) Dim p1 = c + p + c s.Add(p1) children(m, p1) Next End Sub children(0, "") For Each c In tree(1).Edges.Keys Dim m = tree(1).Edges(c) Dim ct = c.ToString() s.Add(ct) children(m, ct) Next Return s End Function Sub Main() Dim tree = Eertree("eertree") Dim result = SubPalindromes(tree) Dim listStr = String.Join(", ", result) Console.WriteLine("[{0}]", listStr) End Sub End Module
Generate a VB translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Eertree { public static void main(String[] args) { List<Node> tree = eertree("eertree"); List<String> result = subPalindromes(tree); System.out.println(result); } private static class Node { int length; Map<Character, Integer> edges = new HashMap<>(); int suffix; public Node(int length) { this.length = length; } public Node(int length, Map<Character, Integer> edges, int suffix) { this.length = length; this.edges = edges != null ? edges : new HashMap<>(); this.suffix = suffix; } } private static final int EVEN_ROOT = 0; private static final int ODD_ROOT = 1; private static List<Node> eertree(String s) { List<Node> tree = new ArrayList<>(); tree.add(new Node(0, null, ODD_ROOT)); tree.add(new Node(-1, null, ODD_ROOT)); int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); for (n = suffix; ; n = tree.get(n).suffix) { k = tree.get(n).length; int b = i - k - 1; if (b >= 0 && s.charAt(b) == c) { break; } } if (tree.get(n).edges.containsKey(c)) { suffix = tree.get(n).edges.get(c); continue; } suffix = tree.size(); tree.add(new Node(k + 2)); tree.get(n).edges.put(c, suffix); if (tree.get(suffix).length == 1) { tree.get(suffix).suffix = 0; continue; } while (true) { n = tree.get(n).suffix; int b = i - tree.get(n).length - 1; if (b >= 0 && s.charAt(b) == c) { break; } } tree.get(suffix).suffix = tree.get(n).edges.get(c); } return tree; } private static List<String> subPalindromes(List<Node> tree) { List<String> s = new ArrayList<>(); subPalindromes_children(0, "", tree, s); for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) { String ct = String.valueOf(cm.getKey()); s.add(ct); subPalindromes_children(cm.getValue(), ct, tree, s); } return s; } private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) { for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) { Character c = cm.getKey(); Integer m = cm.getValue(); String pl = c + p + c; s.add(pl); subPalindromes_children(m, pl, tree, s); } } }
Module Module1 Class Node Public Sub New(Len As Integer) Length = Len Edges = New Dictionary(Of Char, Integer) End Sub Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer) Length = len Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg) Suffix = suf End Sub Property Edges As Dictionary(Of Char, Integer) Property Length As Integer Property Suffix As Integer End Class ReadOnly EVEN_ROOT As Integer = 0 ReadOnly ODD_ROOT As Integer = 1 Function Eertree(s As String) As List(Of Node) Dim tree As New List(Of Node) From { New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT), New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT) } Dim suffix = ODD_ROOT Dim n As Integer Dim k As Integer For i = 1 To s.Length Dim c = s(i - 1) n = suffix While True k = tree(n).Length Dim b = i - k - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If n = tree(n).Suffix End While If tree(n).Edges.ContainsKey(c) Then suffix = tree(n).Edges(c) Continue For End If suffix = tree.Count tree.Add(New Node(k + 2)) tree(n).Edges(c) = suffix If tree(suffix).Length = 1 Then tree(suffix).Suffix = 0 Continue For End If While True n = tree(n).Suffix Dim b = i - tree(n).Length - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If End While Dim a = tree(n) Dim d = a.Edges(c) Dim e = tree(suffix) e.Suffix = d Next Return tree End Function Function SubPalindromes(tree As List(Of Node)) As List(Of String) Dim s As New List(Of String) Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String) For Each c In tree(n).Edges.Keys Dim m = tree(n).Edges(c) Dim p1 = c + p + c s.Add(p1) children(m, p1) Next End Sub children(0, "") For Each c In tree(1).Edges.Keys Dim m = tree(1).Edges(c) Dim ct = c.ToString() s.Add(ct) children(m, ct) Next Return s End Function Sub Main() Dim tree = Eertree("eertree") Dim result = SubPalindromes(tree) Dim listStr = String.Join(", ", result) Console.WriteLine("[{0}]", listStr) End Sub End Module
Keep all operations the same but rewrite the snippet in VB.
import java.time.LocalDate; import java.time.temporal.WeekFields; public class LongYear { public static void main(String[] args) { System.out.printf("Long years this century:%n"); for (int year = 2000 ; year < 2100 ; year++ ) { if ( longYear(year) ) { System.out.print(year + " "); } } } private static boolean longYear(int year) { return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53; } }
DEFINT A-Z DECLARE FUNCTION p% (Yr AS INTEGER) DECLARE FUNCTION LongYear% (Yr AS INTEGER) DIM iYi, iYf, i CLS PRINT "This program calculates which are 53-week years in a range." PRINT INPUT "Initial year"; iYi INPUT "Final year (could be the same)"; iYf IF iYf >= iYi THEN FOR i = iYi TO iYf IF LongYear(i) THEN PRINT i; " "; END IF NEXT i END IF PRINT PRINT PRINT "End of program." END FUNCTION LongYear% (Yr AS INTEGER) LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3) END FUNCTION FUNCTION p% (Yr AS INTEGER) p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7 END FUNCTION
Transform the following Java implementation into VB, maintaining the same output and logic.
import java.time.LocalDate; import java.time.temporal.WeekFields; public class LongYear { public static void main(String[] args) { System.out.printf("Long years this century:%n"); for (int year = 2000 ; year < 2100 ; year++ ) { if ( longYear(year) ) { System.out.print(year + " "); } } } private static boolean longYear(int year) { return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53; } }
DEFINT A-Z DECLARE FUNCTION p% (Yr AS INTEGER) DECLARE FUNCTION LongYear% (Yr AS INTEGER) DIM iYi, iYf, i CLS PRINT "This program calculates which are 53-week years in a range." PRINT INPUT "Initial year"; iYi INPUT "Final year (could be the same)"; iYf IF iYf >= iYi THEN FOR i = iYi TO iYf IF LongYear(i) THEN PRINT i; " "; END IF NEXT i END IF PRINT PRINT PRINT "End of program." END FUNCTION LongYear% (Yr AS INTEGER) LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3) END FUNCTION FUNCTION p% (Yr AS INTEGER) p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7 END FUNCTION
Rewrite the snippet below in VB so it works the same as the original Java code.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ZumkellerNumbers { public static void main(String[] args) { int n = 1; System.out.printf("First 220 Zumkeller numbers:%n"); for ( int count = 1 ; count <= 220 ; n += 1 ) { if ( isZumkeller(n) ) { System.out.printf("%3d ", n); if ( count % 20 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( isZumkeller(n) ) { System.out.printf("%6d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } n = 1; System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n"); for ( int count = 1 ; count <= 40 ; n += 2 ) { if ( n % 5 != 0 && isZumkeller(n) ) { System.out.printf("%8d", n); if ( count % 10 == 0 ) { System.out.printf("%n"); } count++; } } } private static boolean isZumkeller(int n) { if ( n % 18 == 6 || n % 18 == 12 ) { return true; } List<Integer> divisors = getDivisors(n); int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum(); if ( divisorSum % 2 == 1 ) { return false; } int abundance = divisorSum - 2 * n; if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) { return true; } Collections.sort(divisors); int j = divisors.size() - 1; int sum = divisorSum/2; if ( divisors.get(j) > sum ) { return false; } return canPartition(j, divisors, sum, new int[2]); } private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) { if ( j < 0 ) { return true; } for ( int i = 0 ; i < 2 ; i++ ) { if ( buckets[i] + divisors.get(j) <= sum ) { buckets[i] += divisors.get(j); if ( canPartition(j-1, divisors, sum, buckets) ) { return true; } buckets[i] -= divisors.get(j); } if( buckets[i] == 0 ) { break; } } return false; } private static final List<Integer> getDivisors(int number) { List<Integer> divisors = new ArrayList<Integer>(); long sqrt = (long) Math.sqrt(number); for ( int i = 1 ; i <= sqrt ; i++ ) { if ( number % i == 0 ) { divisors.add(i); int div = number / i; if ( div != i ) { divisors.add(div); } } } return divisors; } }
Module Module1 Function GetDivisors(n As Integer) As List(Of Integer) Dim divs As New List(Of Integer) From { 1, n } Dim i = 2 While i * i <= n If n Mod i = 0 Then Dim j = n \ i divs.Add(i) If i <> j Then divs.Add(j) End If End If i += 1 End While Return divs End Function Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean If sum = 0 Then Return True End If Dim le = divs.Count If le = 0 Then Return False End If Dim last = divs(le - 1) Dim newDivs As New List(Of Integer) For i = 1 To le - 1 newDivs.Add(divs(i - 1)) Next If last > sum Then Return IsPartSum(newDivs, sum) End If Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last) End Function Function IsZumkeller(n As Integer) As Boolean Dim divs = GetDivisors(n) Dim sum = divs.Sum() REM if sum is odd can If sum Mod 2 = 1 Then Return False End If REM if n is odd use If n Mod 2 = 1 Then Dim abundance = sum - 2 * n Return abundance > 0 AndAlso abundance Mod 2 = 0 End If REM if n and sum are both even check if there Return IsPartSum(divs, sum \ 2) End Function Sub Main() Console.WriteLine("The first 220 Zumkeller numbers are:") Dim i = 2 Dim count = 0 While count < 220 If IsZumkeller(i) Then Console.Write("{0,3} ", i) count += 1 If count Mod 20 = 0 Then Console.WriteLine() End If End If i += 1 End While Console.WriteLine() Console.WriteLine("The first 40 odd Zumkeller numbers are:") i = 3 count = 0 While count < 40 If IsZumkeller(i) Then Console.Write("{0,5} ", i) count += 1 If count Mod 10 = 0 Then Console.WriteLine() End If End If i += 2 End While Console.WriteLine() Console.WriteLine("The first 40 odd Zumkeller numbers which don i = 3 count = 0 While count < 40 If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then Console.Write("{0,7} ", i) count += 1 If count Mod 8 = 0 Then Console.WriteLine() End If End If i += 2 End While End Sub End Module
Convert this Java snippet to VB and keep its semantics consistent.
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
Rewrite the snippet below in VB so it works the same as the original Java code.
import java.util.*; class MergeMaps { public static void main(String[] args) { Map<String, Object> base = new HashMap<>(); base.put("name", "Rocket Skates"); base.put("price", 12.75); base.put("color", "yellow"); Map<String, Object> update = new HashMap<>(); update.put("price", 15.25); update.put("color", "red"); update.put("year", 1974); Map<String, Object> result = new HashMap<>(base); result.putAll(update); System.out.println(result); } }
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"}; public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); } private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; } private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; } }
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"}; public static void main(String[] args) { int elements = 15; for ( int b = 0 ; b < 10 ; b++ ) { System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b); System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements)); int decimalPlaces = 32; BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); System.out.printf("%n"); } int b = 1; int decimalPlaces = 256; System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b); BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1); System.out.printf("Value to %d decimal places after %s iterations : %s%n", decimalPlaces, ratio[1], ratio[0]); } private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) { BigDecimal x0Bi = BigDecimal.valueOf(x0); BigDecimal x1Bi = BigDecimal.valueOf(x1); BigDecimal bBi = BigDecimal.valueOf(b); MathContext mc = new MathContext(digits); BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc); int iterations = 0; while ( true ) { iterations++; BigDecimal x = bBi.multiply(x1Bi).add(x0Bi); BigDecimal fractionCurrent = x.divide(x1Bi, mc); if ( fractionCurrent.compareTo(fractionPrior) == 0 ) { break; } x0Bi = x1Bi; x1Bi = x; fractionPrior = fractionCurrent; } return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)}; } private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) { List<BigInteger> list = new ArrayList<>(); BigInteger x0Bi = BigInteger.valueOf(x0); BigInteger x1Bi = BigInteger.valueOf(x1); BigInteger bBi = BigInteger.valueOf(b); if ( n > 0 ) { list.add(x0Bi); } if ( n > 1 ) { list.add(x1Bi); } while ( n > 2 ) { BigInteger x = bBi.multiply(x1Bi).add(x0Bi); list.add(x); n--; x0Bi = x1Bi; x1Bi = x; } return list; } }
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
Generate a VB translation of this Java snippet without changing its computational steps.
import java.io.*; import java.util.*; public class Dijkstra { private static final Graph.Edge[] GRAPH = { new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d", 11), new Graph.Edge("c", "f", 2), new Graph.Edge("d", "e", 6), new Graph.Edge("e", "f", 9), }; private static final String START = "a"; private static final String END = "e"; public static void main(String[] args) { Graph g = new Graph(GRAPH); g.dijkstra(START); g.printPath(END); } } class Graph { private final Map<String, Vertex> graph; public static class Edge { public final String v1, v2; public final int dist; public Edge(String v1, String v2, int dist) { this.v1 = v1; this.v2 = v2; this.dist = dist; } } public static class Vertex implements Comparable<Vertex>{ public final String name; public int dist = Integer.MAX_VALUE; public Vertex previous = null; public final Map<Vertex, Integer> neighbours = new HashMap<>(); public Vertex(String name) { this.name = name; } private void printPath() { if (this == this.previous) { System.out.printf("%s", this.name); } else if (this.previous == null) { System.out.printf("%s(unreached)", this.name); } else { this.previous.printPath(); System.out.printf(" -> %s(%d)", this.name, this.dist); } } public int compareTo(Vertex other) { if (dist == other.dist) return name.compareTo(other.name); return Integer.compare(dist, other.dist); } @Override public String toString() { return "(" + name + ", " + dist + ")"; } } public Graph(Edge[] edges) { graph = new HashMap<>(edges.length); for (Edge e : edges) { if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); } for (Edge e : edges) { graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); } } public void dijkstra(String startName) { if (!graph.containsKey(startName)) { System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName); return; } final Vertex source = graph.get(startName); NavigableSet<Vertex> q = new TreeSet<>(); for (Vertex v : graph.values()) { v.previous = v == source ? source : null; v.dist = v == source ? 0 : Integer.MAX_VALUE; q.add(v); } dijkstra(q); } private void dijkstra(final NavigableSet<Vertex> q) { Vertex u, v; while (!q.isEmpty()) { u = q.pollFirst(); if (u.dist == Integer.MAX_VALUE) break; for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { v = a.getKey(); final int alternateDist = u.dist + a.getValue(); if (alternateDist < v.dist) { q.remove(v); v.dist = alternateDist; v.previous = u; q.add(v); } } } } public void printPath(String endName) { if (!graph.containsKey(endName)) { System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName); return; } graph.get(endName).printPath(); System.out.println(); } public void printAllPaths() { for (Vertex v : graph.values()) { v.printPath(); System.out.println(); } } }
Class Branch Public from As Node Public towards As Node Public length As Integer Public distance As Integer Public key As String Class Node Public key As String Public correspondingBranch As Branch Const INFINITY = 32767 Private Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node) Dim a As New Collection Dim b As New Collection Dim c As New Collection Dim I As New Collection Dim II As New Collection Dim III As New Collection Dim u As Node, R_ As Node, dist As Integer For Each n In Nodes c.Add n, n.key Next n For Each e In Branches III.Add e, e.key Next e a.Add P, P.key c.Remove P.key Set u = P Do For Each r In III If r.from Is u Then Set R_ = r.towards If Belongs(R_, c) Then c.Remove R_.key b.Add R_, R_.key Set R_.correspondingBranch = r If u.correspondingBranch Is Nothing Then R_.correspondingBranch.distance = r.length Else R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If III.Remove r.key II.Add r, r.key Else If Belongs(R_, b) Then If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then II.Remove R_.correspondingBranch.key II.Add r, r.key Set R_.correspondingBranch = r R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If End If End If End If Next r dist = INFINITY Set u = Nothing For Each n In b If dist > n.correspondingBranch.distance Then dist = n.correspondingBranch.distance Set u = n End If Next n b.Remove u.key a.Add u, u.key II.Remove u.correspondingBranch.key I.Add u.correspondingBranch, u.correspondingBranch.key Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q) If Not Q Is Nothing Then GetPath Q End Sub Private Function Belongs(n As Node, col As Collection) As Boolean Dim obj As Node On Error GoTo err Belongs = True Set obj = col(n.key) Exit Function err: Belongs = False End Function Private Sub GetPath(Target As Node) Dim path As String If Target.correspondingBranch Is Nothing Then path = "no path" Else path = Target.key Set u = Target Do While Not u.correspondingBranch Is Nothing path = u.correspondingBranch.from.key & " " & path Set u = u.correspondingBranch.from Loop Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path End If End Sub Public Sub test() Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = "ab": ab.distance = INFINITY Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = "ac": ac.distance = INFINITY Set af.from = a: Set af.towards = f: af.length = 14: af.key = "af": af.distance = INFINITY Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = "bc": bc.distance = INFINITY Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = "bd": bd.distance = INFINITY Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = "cd": cd.distance = INFINITY Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = "cf": cf.distance = INFINITY Set de.from = d: Set de.towards = e: de.length = 6: de.key = "de": de.distance = INFINITY Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = "ef": ef.distance = INFINITY a.key = "a" b.key = "b" c.key = "c" d.key = "d" e.key = "e" f.key = "f" Dim testNodes As New Collection Dim testBranches As New Collection testNodes.Add a, "a" testNodes.Add b, "b" testNodes.Add c, "c" testNodes.Add d, "d" testNodes.Add e, "e" testNodes.Add f, "f" testBranches.Add ab, "ab" testBranches.Add ac, "ac" testBranches.Add af, "af" testBranches.Add bc, "bc" testBranches.Add bd, "bd" testBranches.Add cd, "cd" testBranches.Add cf, "cf" testBranches.Add de, "de" testBranches.Add ef, "ef" Debug.Print "From", "To", "Distance", "Path" Dijkstra testNodes, testBranches, a, e Dijkstra testNodes, testBranches, a GetPath f End Sub
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
import java.util.Arrays; import java.util.Random; public class GeometricAlgebra { private static int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } private static double reorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += bitCount(k & j); k = k >> 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } static class Vector { private double[] dims; public Vector(double[] dims) { this.dims = dims; } public Vector dot(Vector rhs) { return times(rhs).plus(rhs.times(this)).times(0.5); } public Vector unaryMinus() { return times(-1.0); } public Vector plus(Vector rhs) { double[] result = Arrays.copyOf(dims, 32); for (int i = 0; i < rhs.dims.length; ++i) { result[i] += rhs.get(i); } return new Vector(result); } public Vector times(Vector rhs) { double[] result = new double[32]; for (int i = 0; i < dims.length; ++i) { if (dims[i] != 0.0) { for (int j = 0; j < rhs.dims.length; ++j) { if (rhs.get(j) != 0.0) { double s = reorderingSign(i, j) * dims[i] * rhs.dims[j]; int k = i ^ j; result[k] += s; } } } } return new Vector(result); } public Vector times(double scale) { double[] result = dims.clone(); for (int i = 0; i < 5; ++i) { dims[i] *= scale; } return new Vector(result); } double get(int index) { return dims[index]; } void set(int index, double value) { dims[index] = value; } @Override public String toString() { StringBuilder sb = new StringBuilder("("); boolean first = true; for (double value : dims) { if (first) { first = false; } else { sb.append(", "); } sb.append(value); } return sb.append(")").toString(); } } private static Vector e(int n) { if (n > 4) { throw new IllegalArgumentException("n must be less than 5"); } Vector result = new Vector(new double[32]); result.set(1 << n, 1.0); return result; } private static final Random rand = new Random(); private static Vector randomVector() { Vector result = new Vector(new double[32]); for (int i = 0; i < 5; ++i) { Vector temp = new Vector(new double[]{rand.nextDouble()}); result = result.plus(temp.times(e(i))); } return result; } private static Vector randomMultiVector() { Vector result = new Vector(new double[32]); for (int i = 0; i < 32; ++i) { result.set(i, rand.nextDouble()); } return result; } public static void main(String[] args) { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { if (i < j) { if (e(i).dot(e(j)).get(0) != 0.0) { System.out.println("Unexpected non-null scalar product."); return; } } } } Vector a = randomMultiVector(); Vector b = randomMultiVector(); Vector c = randomMultiVector(); Vector x = randomVector(); System.out.println(a.times(b).times(c)); System.out.println(a.times(b.times(c))); System.out.println(); System.out.println(a.times(b.plus(c))); System.out.println(a.times(b).plus(a.times(c))); System.out.println(); System.out.println(a.plus(b).times(c)); System.out.println(a.times(c).plus(b.times(c))); System.out.println(); System.out.println(x.times(x)); } }
Option Strict On Imports System.Text Module Module1 Structure Vector Private ReadOnly dims() As Double Public Sub New(da() As Double) dims = da End Sub Public Shared Operator -(v As Vector) As Vector Return v * -1.0 End Operator Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double Array.Copy(lhs.dims, 0, result, 0, lhs.Length) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = lhs(i2) + rhs(i2) Next Return New Vector(result) End Operator Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double For i = 1 To lhs.Length Dim i2 = i - 1 If lhs(i2) <> 0.0 Then For j = 1 To lhs.Length Dim j2 = j - 1 If rhs(j2) <> 0.0 Then Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2) Dim k = i2 Xor j2 result(k) += s End If Next End If Next Return New Vector(result) End Operator Public Shared Operator *(v As Vector, scale As Double) As Vector Dim result = CType(v.dims.Clone, Double()) For i = 1 To result.Length Dim i2 = i - 1 result(i2) *= scale Next Return New Vector(result) End Operator Default Public Property Index(key As Integer) As Double Get Return dims(key) End Get Set(value As Double) dims(key) = value End Set End Property Public ReadOnly Property Length As Integer Get Return dims.Length End Get End Property Public Function Dot(rhs As Vector) As Vector Return (Me * rhs + rhs * Me) * 0.5 End Function Private Shared Function BitCount(i As Integer) As Integer i -= ((i >> 1) And &H55555555) i = (i And &H33333333) + ((i >> 2) And &H33333333) i = (i + (i >> 4)) And &HF0F0F0F i += (i >> 8) i += (i >> 16) Return i And &H3F End Function Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double Dim k = i >> 1 Dim sum = 0 While k <> 0 sum += BitCount(k And j) k >>= 1 End While Return If((sum And 1) = 0, 1.0, -1.0) End Function Public Overrides Function ToString() As String Dim it = dims.GetEnumerator Dim sb As New StringBuilder("[") If it.MoveNext() Then sb.Append(it.Current) End If While it.MoveNext sb.Append(", ") sb.Append(it.Current) End While sb.Append("]") Return sb.ToString End Function End Structure Function DoubleArray(size As Integer) As Double() Dim result(size - 1) As Double For i = 1 To size Dim i2 = i - 1 result(i2) = 0.0 Next Return result End Function Function E(n As Integer) As Vector If n > 4 Then Throw New ArgumentException("n must be less than 5") End If Dim result As New Vector(DoubleArray(32)) result(1 << n) = 1.0 Return result End Function ReadOnly r As New Random() Function RandomVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To 5 Dim i2 = i - 1 Dim singleton() As Double = {r.NextDouble()} result += New Vector(singleton) * E(i2) Next Return result End Function Function RandomMultiVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = r.NextDouble() Next Return result End Function Sub Main() For i = 1 To 5 Dim i2 = i - 1 For j = 1 To 5 Dim j2 = j - 1 If i2 < j2 Then If E(i2).Dot(E(j2))(0) <> 0.0 Then Console.Error.WriteLine("Unexpected non-null scalar product") Return End If ElseIf i2 = j2 Then If E(i2).Dot(E(j2))(0) = 0.0 Then Console.Error.WriteLine("Unexpected null scalar product") Return End If End If Next Next Dim a = RandomMultiVector() Dim b = RandomMultiVector() Dim c = RandomMultiVector() Dim x = RandomVector() Console.WriteLine((a * b) * c) Console.WriteLine(a * (b * c)) Console.WriteLine() Console.WriteLine(a * (b + c)) Console.WriteLine(a * b + a * c) Console.WriteLine() Console.WriteLine((a + b) * c) Console.WriteLine(a * c + b * c) Console.WriteLine() Console.WriteLine(x * x) End Sub End Module
Port the following code from Java to VB with equivalent syntax and logic.
Map<String, Integer> map = new HashMap<String, Integer>(); map.put("hello", 1); map.put("world", 2); map.put("!", 3); for (Map.Entry<String, Integer> e : map.entrySet()) { String key = e.getKey(); Integer value = e.getValue(); System.out.println("key = " + key + ", value = " + value); } for (String key : map.keySet()) { System.out.println("key = " + key); } for (Integer value : map.values()) { System.out.println("value = " + value); }
Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 For Each s In h.Keys Debug.Print s Next For Each s In h.Items Debug.Print s Next u = h.Keys v = h.Items For i = 0 To h.Count - 1 Debug.Print u(i), v(i) Next End Sub
Produce a functionally identical VB code for the snippet given in Java.
class BoundedIntOutOfBoundsException extends Exception { public BoundedIntOutOfBoundsException(int v, int l, int u) { super("value " + v + " is out of bounds [" + l + "," + u + "]"); } } class BoundedInt { private int value; private int lower; private int upper; public BoundedInt(int l, int u) { lower = Math.min(l, u); upper = Math.max(l, u); } private boolean checkBounds(int v) { return (v >= this.lower) && (v <= this.upper); } public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{ assign(i.value()); } public void assign(int v) throws BoundedIntOutOfBoundsException { if ( checkBounds(v) ) { this.value = v; } else { throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper); } } public int add(BoundedInt i) throws BoundedIntOutOfBoundsException { return add(i.value()); } public int add(int i) throws BoundedIntOutOfBoundsException { if ( checkBounds(this.value + i) ) { this.value += i; } else { throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper); } return this.value; } public int value() { return this.value; } } public class Bounded { public static void main(String[] args) throws BoundedIntOutOfBoundsException { BoundedInt a = new BoundedInt(1, 10); BoundedInt b = new BoundedInt(1, 10); a.assign(6); try { b.assign(12); } catch (Exception e) { System.out.println(e.getMessage()); } b.assign(9); try { a.add(b.value()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
Private mvarValue As Integer Public Property Let Value(ByVal vData As Integer) If (vData > 10) Or (vData < 1) Then Error 380 Else mvarValue = vData End If End Property Public Property Get Value() As Integer Value = mvarValue End Property Private Sub Class_Initialize() mvarValue = 1 End Sub
Translate this program into VB but keep the logic exactly as in Java.
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, {"Bob", "foo"}}; hashJoin(table1, 1, table2, 0).stream() .forEach(r -> System.out.println(Arrays.deepToString(r))); } static List<String[][]> hashJoin(String[][] records1, int idx1, String[][] records2, int idx2) { List<String[][]> result = new ArrayList<>(); Map<String, List<String[]>> map = new HashMap<>(); for (String[] record : records1) { List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>()); v.add(record); map.put(record[idx1], v); } for (String[] record : records2) { List<String[]> lst = map.get(record[idx2]); if (lst != null) { lst.stream().forEach(r -> { result.add(new String[][]{r, record}); }); } } return result; } }
Dim t_age(4,1) t_age(0,0) = 27 : t_age(0,1) = "Jonah" t_age(1,0) = 18 : t_age(1,1) = "Alan" t_age(2,0) = 28 : t_age(2,1) = "Glory" t_age(3,0) = 18 : t_age(3,1) = "Popeye" t_age(4,0) = 28 : t_age(4,1) = "Alan" Dim t_nemesis(4,1) t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders" t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts" t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies" t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy" Call hash_join(t_age,1,t_nemesis,0) Sub hash_join(table_1,index_1,table_2,index_2) Set hash = CreateObject("Scripting.Dictionary") For i = 0 To UBound(table_1) hash.Add i,Array(table_1(i,0),table_1(i,1)) Next For j = 0 To UBound(table_2) For Each key In hash.Keys If hash(key)(index_1) = table_2(j,index_2) Then WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_ " = " & table_2(j,0) & "," & table_2(j,1) End If Next Next End Sub
Preserve the algorithm and functionality while converting the code from Java to VB.
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; s.currentAngle = 0; s.currentX = (size - length)/2; s.currentY = length; s.lineLength = length; s.begin(size); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiSquareCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = AXIOM; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'X') sb.append(PRODUCTION); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final String AXIOM = "F+XF+F+XF"; private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X"; private static final int ANGLE = 90; }
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: end sub public sub lt(i): ori=(ori + i*iang) end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class const raiz2=1.4142135623730950488016887242097 sub media_sierp (niv,sz) if niv=0 then x.fw sz: exit sub media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz end sub sub sierp(niv,sz) media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 end sub dim x set x=new turtle x.iangle=45 x.orient=0 x.incr=1 x.x=100:x.y=270 sierp 5,4 set x=nothing
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; s.currentAngle = 0; s.currentX = (size - length)/2; s.currentY = length; s.lineLength = length; s.begin(size); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiSquareCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = AXIOM; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'X') sb.append(PRODUCTION); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final String AXIOM = "F+XF+F+XF"; private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X"; private static final int ANGLE = 90; }
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: end sub public sub lt(i): ori=(ori + i*iang) end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class const raiz2=1.4142135623730950488016887242097 sub media_sierp (niv,sz) if niv=0 then x.fw sz: exit sub media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz end sub sub sierp(niv,sz) media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 end sub dim x set x=new turtle x.iangle=45 x.orient=0 x.incr=1 x.x=100:x.y=270 sierp 5,4 set x=nothing
Write the same code in VB as shown below in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList("aab", "aa b") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d"); for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) { List<List<String>> matches = wordBreak(testString, dict); System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size()); for ( List<String> match : matches ) { System.out.printf(" Word Break = %s%n", match); } System.out.printf("%n"); } } private static List<List<String>> wordBreak(String s, List<String> dictionary) { List<List<String>> matches = new ArrayList<>(); Queue<Node> queue = new LinkedList<>(); queue.add(new Node(s)); while ( ! queue.isEmpty() ) { Node node = queue.remove(); if ( node.val.length() == 0 ) { matches.add(node.parsed); } else { for ( String word : dictionary ) { if ( node.val.startsWith(word) ) { String valNew = node.val.substring(word.length(), node.val.length()); List<String> parsedNew = new ArrayList<>(); parsedNew.addAll(node.parsed); parsedNew.add(word); queue.add(new Node(valNew, parsedNew)); } } } } return matches; } private static class Node { private String val; private List<String> parsed; public Node(String initial) { val = initial; parsed = new ArrayList<>(); } public Node(String s, List<String> p) { val = s; parsed = p; } } }
Module Module1 Structure Node Private ReadOnly m_val As String Private ReadOnly m_parsed As List(Of String) Sub New(initial As String) m_val = initial m_parsed = New List(Of String) End Sub Sub New(s As String, p As List(Of String)) m_val = s m_parsed = p End Sub Public Function Value() As String Return m_val End Function Public Function Parsed() As List(Of String) Return m_parsed End Function End Structure Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String)) Dim matches As New List(Of List(Of String)) Dim q As New Queue(Of Node) q.Enqueue(New Node(s)) While q.Count > 0 Dim node = q.Dequeue() REM check if fully parsed If node.Value.Length = 0 Then matches.Add(node.Parsed) Else For Each word In dictionary REM check for match If node.Value.StartsWith(word) Then Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length) Dim parsedNew As New List(Of String) parsedNew.AddRange(node.Parsed) parsedNew.Add(word) q.Enqueue(New Node(valNew, parsedNew)) End If Next End If End While Return matches End Function Sub Main() Dim dict As New List(Of String) From {"a", "aa", "b", "ab", "aab"} For Each testString In {"aab", "aa b"} Dim matches = WordBreak(testString, dict) Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count) For Each match In matches Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match)) Next Console.WriteLine() Next dict = New List(Of String) From {"abc", "a", "ac", "b", "c", "cb", "d"} For Each testString In {"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} Dim matches = WordBreak(testString, dict) Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count) For Each match In matches Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match)) Next Console.WriteLine() Next End Sub End Module
Write a version of this Java function in VB with identical behavior.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LatinSquaresInReducedForm { public static void main(String[] args) { System.out.printf("Reduced latin squares of order 4:%n"); for ( LatinSquare square : getReducedLatinSquares(4) ) { System.out.printf("%s%n", square); } System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n"); for ( int n = 1 ; n <= 6 ; n++ ) { List<LatinSquare> list = getReducedLatinSquares(n); System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1)); } } private static long fact(int n) { if ( n == 0 ) { return 1; } int prod = 1; for ( int i = 1 ; i <= n ; i++ ) { prod *= i; } return prod; } private static List<LatinSquare> getReducedLatinSquares(int n) { List<LatinSquare> squares = new ArrayList<>(); squares.add(new LatinSquare(n)); PermutationGenerator permGen = new PermutationGenerator(n); for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) { List<LatinSquare> squaresNext = new ArrayList<>(); for ( LatinSquare square : squares ) { while ( permGen.hasMore() ) { int[] perm = permGen.getNext(); if ( (perm[0]+1) != (fillRow+1) ) { continue; } boolean permOk = true; done: for ( int row = 0 ; row < fillRow ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { if ( square.get(row, col) == (perm[col]+1) ) { permOk = false; break done; } } } if ( permOk ) { LatinSquare newSquare = new LatinSquare(square); for ( int col = 0 ; col < n ; col++ ) { newSquare.set(fillRow, col, perm[col]+1); } squaresNext.add(newSquare); } } permGen.reset(); } squares = squaresNext; } return squares; } @SuppressWarnings("unused") private static int[] display(int[] in) { int [] out = new int[in.length]; for ( int i = 0 ; i < in.length ; i++ ) { out[i] = in[i] + 1; } return out; } private static class LatinSquare { int[][] square; int size; public LatinSquare(int n) { square = new int[n][n]; size = n; for ( int col = 0 ; col < n ; col++ ) { set(0, col, col + 1); } } public LatinSquare(LatinSquare ls) { int n = ls.size; square = new int[n][n]; size = n; for ( int row = 0 ; row < n ; row++ ) { for ( int col = 0 ; col < n ; col++ ) { set(row, col, ls.get(row, col)); } } } public void set(int row, int col, int value) { square[row][col] = value; } public int get(int row, int col) { return square[row][col]; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for ( int row = 0 ; row < size ; row++ ) { sb.append(Arrays.toString(square[row])); sb.append("\n"); } return sb.toString(); } } private static class PermutationGenerator { private int[] a; private BigInteger numLeft; private BigInteger total; public PermutationGenerator (int n) { if (n < 1) { throw new IllegalArgumentException ("Min 1"); } a = new int[n]; total = getFactorial(n); reset(); } private void reset () { for ( int i = 0 ; i < a.length ; i++ ) { a[i] = i; } numLeft = new BigInteger(total.toString()); } public boolean hasMore() { return numLeft.compareTo(BigInteger.ZERO) == 1; } private static BigInteger getFactorial (int n) { BigInteger fact = BigInteger.ONE; for ( int i = n ; i > 1 ; i-- ) { fact = fact.multiply(new BigInteger(Integer.toString(i))); } return fact; } public int[] getNext() { if ( numLeft.equals(total) ) { numLeft = numLeft.subtract (BigInteger.ONE); return a; } int j = a.length - 2; while ( a[j] > a[j+1] ) { j--; } int k = a.length - 1; while ( a[j] > a[k] ) { k--; } int temp = a[k]; a[k] = a[j]; a[j] = temp; int r = a.length - 1; int s = j + 1; while (r > s) { int temp2 = a[s]; a[s] = a[r]; a[r] = temp2; r--; s++; } numLeft = numLeft.subtract(BigInteger.ONE); return a; } } }
Option Strict On Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer)) Module Module1 Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim u = a a = b b = u End Sub Sub PrintSquare(latin As Matrix) For Each row In latin Dim it = row.GetEnumerator Console.Write("[") If it.MoveNext Then Console.Write(it.Current) End If While it.MoveNext Console.Write(", ") Console.Write(it.Current) End While Console.WriteLine("]") Next Console.WriteLine() End Sub Function DList(n As Integer, start As Integer) As Matrix start -= 1 REM use 0 based indexes Dim a = Enumerable.Range(0, n).ToArray a(start) = a(0) a(0) = start Array.Sort(a, 1, a.Length - 1) Dim first = a(1) REM recursive closure permutes a[1:] Dim r As New Matrix Dim Recurse As Action(Of Integer) = Sub(last As Integer) If last = first Then REM bottom of recursion. you get here once for each permutation REM test if permutation is deranged. For j = 1 To a.Length - 1 Dim v = a(j) If j = v Then Return REM no, ignore it End If Next REM yes, save a copy with 1 based indexing Dim b = a.Select(Function(v) v + 1).ToArray r.Add(b.ToList) Return End If For i = last To 1 Step -1 Swap(a(i), a(last)) Recurse(last - 1) Swap(a(i), a(last)) Next End Sub Recurse(n - 1) Return r End Function Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong If n <= 0 Then If echo Then Console.WriteLine("[]") Console.WriteLine() End If Return 0 End If If n = 1 Then If echo Then Console.WriteLine("[1]") Console.WriteLine() End If Return 1 End If Dim rlatin As New Matrix For i = 0 To n - 1 rlatin.Add(New List(Of Integer)) For j = 0 To n - 1 rlatin(i).Add(0) Next Next REM first row For j = 0 To n - 1 rlatin(0)(j) = j + 1 Next Dim count As ULong = 0 Dim Recurse As Action(Of Integer) = Sub(i As Integer) Dim rows = DList(n, i) For r = 0 To rows.Count - 1 rlatin(i - 1) = rows(r) For k = 0 To i - 2 For j = 1 To n - 1 If rlatin(k)(j) = rlatin(i - 1)(j) Then If r < rows.Count - 1 Then GoTo outer End If If i > 2 Then Return End If End If Next Next If i < n Then Recurse(i + 1) Else count += 1UL If echo Then PrintSquare(rlatin) End If End If outer: While False REM empty End While Next End Sub REM remiain rows Recurse(2) Return count End Function Function Factorial(n As ULong) As ULong If n <= 0 Then Return 1 End If Dim prod = 1UL For i = 2UL To n prod *= i Next Return prod End Function Sub Main() Console.WriteLine("The four reduced latin squares of order 4 are:") Console.WriteLine() ReducedLatinSquares(4, True) Console.WriteLine("The size of the set of reduced latin squares for the following orders") Console.WriteLine("and hence the total number of latin squares of these orders are:") Console.WriteLine() For n = 1 To 6 Dim nu As ULong = CULng(n) Dim size = ReducedLatinSquares(n, False) Dim f = Factorial(nu - 1UL) f *= f * nu * size Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f) Next End Sub End Module
Generate an equivalent VB version of this Java code.
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class UPC { private static final int SEVEN = 7; private static final Map<String, Integer> LEFT_DIGITS = Map.of( " ## #", 0, " ## #", 1, " # ##", 2, " #### #", 3, " # ##", 4, " ## #", 5, " # ####", 6, " ### ##", 7, " ## ###", 8, " # ##", 9 ); private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey() .replace(' ', 's') .replace('#', ' ') .replace('s', '#'), Map.Entry::getValue )); private static final String END_SENTINEL = "# #"; private static final String MID_SENTINEL = " # # "; private static void decodeUPC(String input) { Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> { int pos = 0; var part = candidate.substring(pos, pos + END_SENTINEL.length()); List<Integer> output = new ArrayList<>(); if (END_SENTINEL.equals(part)) { pos += END_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (LEFT_DIGITS.containsKey(part)) { output.add(LEFT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + MID_SENTINEL.length()); if (MID_SENTINEL.equals(part)) { pos += MID_SENTINEL.length(); } else { return Map.entry(false, output); } for (int i = 1; i < SEVEN; i++) { part = candidate.substring(pos, pos + SEVEN); pos += SEVEN; if (RIGHT_DIGITS.containsKey(part)) { output.add(RIGHT_DIGITS.get(part)); } else { return Map.entry(false, output); } } part = candidate.substring(pos, pos + END_SENTINEL.length()); if (!END_SENTINEL.equals(part)) { return Map.entry(false, output); } int sum = 0; for (int i = 0; i < output.size(); i++) { if (i % 2 == 0) { sum += 3 * output.get(i); } else { sum += output.get(i); } } return Map.entry(sum % 10 == 0, output); }; Consumer<List<Integer>> printList = list -> { var it = list.iterator(); System.out.print('['); if (it.hasNext()) { System.out.print(it.next()); } while (it.hasNext()) { System.out.print(", "); System.out.print(it.next()); } System.out.print(']'); }; var candidate = input.trim(); var out = decode.apply(candidate); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(); } else { StringBuilder builder = new StringBuilder(candidate); builder.reverse(); out = decode.apply(builder.toString()); if (out.getKey()) { printList.accept(out.getValue()); System.out.println(" Upside down"); } else if (out.getValue().size() == 12) { System.out.println("Invalid checksum"); } else { System.out.println("Invalid digit(s)"); } } } public static void main(String[] args) { var barcodes = List.of( " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ); barcodes.forEach(UPC::decodeUPC); } }
Option Explicit Const m_limit ="# #" Const m_middle=" # # " Dim a,bnum,i,check,odic a=array(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",_ " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",_ " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",_ " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",_ " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",_ " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",_ " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",_ " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",_ " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",_ " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ") bnum=Array("0001101","0011001","0010011","0111101","0100011"," 0110001","0101111","0111011","0110111","0001011") Set oDic = WScript.CreateObject("scripting.dictionary") For i=0 To 9: odic.Add bin2dec(bnum(i),Asc("1")),i+1 odic.Add bin2dec(bnum(i),Asc("0")),-i-1 Next For i=0 To UBound(a) : print pad(i+1,-2) & ": "& upc(a(i)) :Next WScript.Quit(1) Function bin2dec(ByVal B,a) Dim n While len(b) n =n *2 - (asc(b)=a) b=mid(b,2) Wend bin2dec= n And 127 End Function Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else pad= left(s& space(n),n) end if :end function Function iif(t,a,b) If t Then iif=a Else iif=b End If :End Function Function getnum(s,r) Dim n,s1,r1 s1=Left(s,7) s=Mid(s,8) r1=r Do If r Then s1=StrReverse(s1) n=bin2dec(s1,asc("#")) If odic.exists(n) Then getnum=odic(n) Exit Function Else If r1<>r Then getnum=0:Exit Function r=Not r End If Loop End Function Function getmarker(s,m) getmarker= (InStr(s,m)= 1) s=Mid(s,Len(m)+1) End Function Function checksum(ByVal s) Dim n,i : n=0 do n=n+(Asc(s)-48)*3 s=Mid(s,2) n=n+(Asc(s)-48)*1 s=Mid(s,2) Loop until Len(s)=0 checksum= ((n mod 10)=0) End function Function upc(ByVal s1) Dim i,n,s,out,rev,j s=Trim(s1) If getmarker(s,m_limit)=False Then upc= "bad start marker ":Exit function rev=False out="" For j= 0 To 1 For i=0 To 5 n=getnum(s,rev) If n=0 Then upc= pad(out,16) & pad ("bad code",-10) & pad("pos "& i+j*6+1,-11): Exit Function out=out & Abs(n)-1 Next If j=0 Then If getmarker(s,m_middle)=False Then upc= "bad middle marker " & out :Exit Function Next If getmarker(s,m_limit)=False Then upc= "bad end marker " :Exit function If rev Then out=strreverse(out) upc= pad(out,16) & pad(iif (checksum(out),"valid","not valid"),-10)& pad(iif(rev,"reversed",""),-11) End Function
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message: %n%s%n", enc); System.out.printf("%nDecoded message: %n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
Option Explicit Private Type Adress Row As Integer Column As Integer End Type Private myTable() As String Sub Main() Dim keyw As String, boolQ As Boolean, text As String, test As Long Dim res As String keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example") If keyw = "" Then GoTo ErrorHand Debug.Print "Enter your keyword : " & keyw boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N") Debug.Print "" Debug.Print "Table : " myTable = CreateTable(keyw, boolQ) On Error GoTo ErrorHand test = UBound(myTable) On Error GoTo 0 text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res Exit Sub ErrorHand: Debug.Print "error" End Sub Private Function CreateTable(strKeyword As String, Q As Boolean) As String() Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer Dim strT As String, coll As New Collection Dim s As String strKeyword = UCase(Replace(strKeyword, " ", "")) If Q Then If InStr(strKeyword, "J") > 0 Then Debug.Print "Your keyword isn Exit Function End If Else If InStr(strKeyword, "Q") > 0 Then Debug.Print "Your keyword isn Exit Function End If End If strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ") t = Split(StrConv(strKeyword, vbUnicode), Chr(0)) For c = LBound(t) To UBound(t) - 1 strT = Replace(strT, t(c), "") On Error Resume Next coll.Add t(c), t(c) On Error GoTo 0 Next strKeyword = vbNullString For c = 1 To coll.Count strKeyword = strKeyword & coll(c) Next t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0)) c = 1: r = 1 For cpt = LBound(t) To UBound(t) - 1 temp(r, c) = t(cpt) s = s & " " & t(cpt) c = c + 1 If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = "" Next CreateTable = temp End Function Private Function Encode(s As String) As String Dim i&, t() As String, cpt& s = UCase(Replace(s, " ", "")) For i = 1 To Len(s) - 1 If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i) Next For i = 1 To Len(s) Step 2 ReDim Preserve t(cpt) t(cpt) = Mid(s, i, 2) cpt = cpt + 1 Next i If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X" Debug.Print "[the pairs : " & Join(t, " ") & "]" For i = LBound(t) To UBound(t) t(i) = SwapPairsEncoding(t(i)) Next Encode = Join(t, " ") End Function Private Function SwapPairsEncoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1) resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1) SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1) resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1) SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function Private Function Decode(s As String) As String Dim t, i&, j&, e& t = Split(s, " ") e = UBound(t) - 1 For i = LBound(t) To UBound(t) t(i) = SwapPairsDecoding(CStr(t(i))) Next For i = LBound(t) To e If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then t(i) = Left(t(i), 1) & Left(t(i + 1), 1) For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If End If Next Decode = Join(t, " ") End Function Private Function SwapPairsDecoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1) resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1) SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1) resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1) SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function
Transform the following Java implementation into VB, maintaining the same output and logic.
import java.awt.Point; import java.util.Scanner; public class PlayfairCipher { private static char[][] charTable; private static Point[] positions; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String key = prompt("Enter an encryption key (min length 6): ", sc, 6); String txt = prompt("Enter the message: ", sc, 1); String jti = prompt("Replace J with I? y/n: ", sc, 1); boolean changeJtoI = jti.equalsIgnoreCase("y"); createTable(key, changeJtoI); String enc = encode(prepareText(txt, changeJtoI)); System.out.printf("%nEncoded message: %n%s%n", enc); System.out.printf("%nDecoded message: %n%s%n", decode(enc)); } private static String prompt(String promptText, Scanner sc, int minLen) { String s; do { System.out.print(promptText); s = sc.nextLine().trim(); } while (s.length() < minLen); return s; } private static String prepareText(String s, boolean changeJtoI) { s = s.toUpperCase().replaceAll("[^A-Z]", ""); return changeJtoI ? s.replace("J", "I") : s.replace("Q", ""); } private static void createTable(String key, boolean changeJtoI) { charTable = new char[5][5]; positions = new Point[26]; String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI); int len = s.length(); for (int i = 0, k = 0; i < len; i++) { char c = s.charAt(i); if (positions[c - 'A'] == null) { charTable[k / 5][k % 5] = c; positions[c - 'A'] = new Point(k % 5, k / 5); k++; } } } private static String encode(String s) { StringBuilder sb = new StringBuilder(s); for (int i = 0; i < sb.length(); i += 2) { if (i == sb.length() - 1) sb.append(sb.length() % 2 == 1 ? 'X' : ""); else if (sb.charAt(i) == sb.charAt(i + 1)) sb.insert(i + 1, 'X'); } return codec(sb, 1); } private static String decode(String s) { return codec(new StringBuilder(s), 4); } private static String codec(StringBuilder text, int direction) { int len = text.length(); for (int i = 0; i < len; i += 2) { char a = text.charAt(i); char b = text.charAt(i + 1); int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y; int col1 = positions[a - 'A'].x; int col2 = positions[b - 'A'].x; if (row1 == row2) { col1 = (col1 + direction) % 5; col2 = (col2 + direction) % 5; } else if (col1 == col2) { row1 = (row1 + direction) % 5; row2 = (row2 + direction) % 5; } else { int tmp = col1; col1 = col2; col2 = tmp; } text.setCharAt(i, charTable[row1][col1]); text.setCharAt(i + 1, charTable[row2][col2]); } return text.toString(); } }
Option Explicit Private Type Adress Row As Integer Column As Integer End Type Private myTable() As String Sub Main() Dim keyw As String, boolQ As Boolean, text As String, test As Long Dim res As String keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example") If keyw = "" Then GoTo ErrorHand Debug.Print "Enter your keyword : " & keyw boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N") Debug.Print "" Debug.Print "Table : " myTable = CreateTable(keyw, boolQ) On Error GoTo ErrorHand test = UBound(myTable) On Error GoTo 0 text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res Exit Sub ErrorHand: Debug.Print "error" End Sub Private Function CreateTable(strKeyword As String, Q As Boolean) As String() Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer Dim strT As String, coll As New Collection Dim s As String strKeyword = UCase(Replace(strKeyword, " ", "")) If Q Then If InStr(strKeyword, "J") > 0 Then Debug.Print "Your keyword isn Exit Function End If Else If InStr(strKeyword, "Q") > 0 Then Debug.Print "Your keyword isn Exit Function End If End If strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ") t = Split(StrConv(strKeyword, vbUnicode), Chr(0)) For c = LBound(t) To UBound(t) - 1 strT = Replace(strT, t(c), "") On Error Resume Next coll.Add t(c), t(c) On Error GoTo 0 Next strKeyword = vbNullString For c = 1 To coll.Count strKeyword = strKeyword & coll(c) Next t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0)) c = 1: r = 1 For cpt = LBound(t) To UBound(t) - 1 temp(r, c) = t(cpt) s = s & " " & t(cpt) c = c + 1 If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = "" Next CreateTable = temp End Function Private Function Encode(s As String) As String Dim i&, t() As String, cpt& s = UCase(Replace(s, " ", "")) For i = 1 To Len(s) - 1 If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i) Next For i = 1 To Len(s) Step 2 ReDim Preserve t(cpt) t(cpt) = Mid(s, i, 2) cpt = cpt + 1 Next i If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X" Debug.Print "[the pairs : " & Join(t, " ") & "]" For i = LBound(t) To UBound(t) t(i) = SwapPairsEncoding(t(i)) Next Encode = Join(t, " ") End Function Private Function SwapPairsEncoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1) resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1) SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1) resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1) SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function Private Function Decode(s As String) As String Dim t, i&, j&, e& t = Split(s, " ") e = UBound(t) - 1 For i = LBound(t) To UBound(t) t(i) = SwapPairsDecoding(CStr(t(i))) Next For i = LBound(t) To e If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then t(i) = Left(t(i), 1) & Left(t(i + 1), 1) For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If End If Next Decode = Join(t, " ") End Function Private Function SwapPairsDecoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1) resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1) SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1) resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1) SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function
Generate an equivalent VB version of this Java code.
import java.util.*; public class ClosestPair { public static class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return "(" + x + ", " + y + ")"; } } public static class Pair { public Point point1 = null; public Point point2 = null; public double distance = 0.0; public Pair() { } public Pair(Point point1, Point point2) { this.point1 = point1; this.point2 = point2; calcDistance(); } public void update(Point point1, Point point2, double distance) { this.point1 = point1; this.point2 = point2; this.distance = distance; } public void calcDistance() { this.distance = distance(point1, point2); } public String toString() { return point1 + "-" + point2 + " : " + distance; } } public static double distance(Point p1, Point p2) { double xdist = p2.x - p1.x; double ydist = p2.y - p1.y; return Math.hypot(xdist, ydist); } public static Pair bruteForce(List<? extends Point> points) { int numPoints = points.size(); if (numPoints < 2) return null; Pair pair = new Pair(points.get(0), points.get(1)); if (numPoints > 2) { for (int i = 0; i < numPoints - 1; i++) { Point point1 = points.get(i); for (int j = i + 1; j < numPoints; j++) { Point point2 = points.get(j); double distance = distance(point1, point2); if (distance < pair.distance) pair.update(point1, point2, distance); } } } return pair; } public static void sortByX(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.x < point2.x) return -1; if (point1.x > point2.x) return 1; return 0; } } ); } public static void sortByY(List<? extends Point> points) { Collections.sort(points, new Comparator<Point>() { public int compare(Point point1, Point point2) { if (point1.y < point2.y) return -1; if (point1.y > point2.y) return 1; return 0; } } ); } public static Pair divideAndConquer(List<? extends Point> points) { List<Point> pointsSortedByX = new ArrayList<Point>(points); sortByX(pointsSortedByX); List<Point> pointsSortedByY = new ArrayList<Point>(points); sortByY(pointsSortedByY); return divideAndConquer(pointsSortedByX, pointsSortedByY); } private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY) { int numPoints = pointsSortedByX.size(); if (numPoints <= 3) return bruteForce(pointsSortedByX); int dividingIndex = numPoints >>> 1; List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex); List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints); List<Point> tempList = new ArrayList<Point>(leftOfCenter); sortByY(tempList); Pair closestPair = divideAndConquer(leftOfCenter, tempList); tempList.clear(); tempList.addAll(rightOfCenter); sortByY(tempList); Pair closestPairRight = divideAndConquer(rightOfCenter, tempList); if (closestPairRight.distance < closestPair.distance) closestPair = closestPairRight; tempList.clear(); double shortestDistance =closestPair.distance; double centerX = rightOfCenter.get(0).x; for (Point point : pointsSortedByY) if (Math.abs(centerX - point.x) < shortestDistance) tempList.add(point); for (int i = 0; i < tempList.size() - 1; i++) { Point point1 = tempList.get(i); for (int j = i + 1; j < tempList.size(); j++) { Point point2 = tempList.get(j); if ((point2.y - point1.y) >= shortestDistance) break; double distance = distance(point1, point2); if (distance < closestPair.distance) { closestPair.update(point1, point2, distance); shortestDistance = distance; } } } return closestPair; } public static void main(String[] args) { int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]); List<Point> points = new ArrayList<Point>(); Random r = new Random(); for (int i = 0; i < numPoints; i++) points.add(new Point(r.nextDouble(), r.nextDouble())); System.out.println("Generated " + numPoints + " random points"); long startTime = System.currentTimeMillis(); Pair bruteForceClosestPair = bruteForce(points); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair); startTime = System.currentTimeMillis(); Pair dqClosestPair = divideAndConquer(points); elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair); if (bruteForceClosestPair.distance != dqClosestPair.distance) System.out.println("MISMATCH"); } }
Option Explicit Private Type MyPoint X As Single Y As Single End Type Private Type MyPair p1 As MyPoint p2 As MyPoint End Type Sub Main() Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long Dim T# Randomize Timer Nb = 10 Do ReDim points(1 To Nb) For i = 1 To Nb points(i).X = Rnd * Nb points(i).Y = Rnd * Nb Next d = 1000000000000# T = Timer BF = BruteForce(points, d) Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec." Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y Debug.Print "dist : " & d Debug.Print "--------------------------------------------------" Nb = Nb * 10 Loop While Nb <= 10000 End Sub Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair Dim i As Long, j As Long, d As Single, ClosestPair As MyPair For i = 1 To UBound(p) - 1 For j = i + 1 To UBound(p) d = Dist(p(i), p(j)) If d < mindist Then mindist = d ClosestPair.p1 = p(i) ClosestPair.p2 = p(j) End If Next Next BruteForce = ClosestPair End Function Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2) End Function
Port the following code from Java to VB with equivalent syntax and logic.
public class Animal{ }
Class Animal End Class Class Dog Inherits Animal End Class Class Lab Inherits Dog End Class Class Collie Inherits Dog End Class Class Cat Inherits Animal End Class
Port the provided Java code into VB while preserving the original functionality.
Map<String, Int> map = new HashMap(); map["foo"] = 5; map["bar"] = 10; map["baz"] = 15; map["foo"] = 6;
Option Explicit Sub Test() Dim h As Object Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 Debug.Print h.Item("A") h.Item("C") = 4 h.Key("C") = "D" Debug.Print h.exists("C") h.Remove "B" Debug.Print h.Count h.RemoveAll Debug.Print h.Count End Sub
Preserve the algorithm and functionality while converting the code from Java to VB.
import java.awt.*; import javax.swing.*; public class ColorWheel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ColorWheelFrame frame = new ColorWheelFrame(); frame.setVisible(true); } }); } private static class ColorWheelFrame extends JFrame { private ColorWheelFrame() { super("Color Wheel"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().add(new ColorWheelPanel()); pack(); } } private static class ColorWheelPanel extends JComponent { private ColorWheelPanel() { setPreferredSize(new Dimension(400, 400)); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; int w = getWidth(); int h = getHeight(); int margin = 10; int radius = (Math.min(w, h) - 2 * margin)/2; int cx = w/2; int cy = h/2; float[] dist = {0.F, 1.0F}; g2.setColor(Color.BLACK); g2.fillRect(0, 0, w, h); for (int angle = 0; angle < 360; ++angle) { Color color = hsvToRgb(angle, 1.0, 1.0); Color[] colors = {Color.WHITE, color}; RadialGradientPaint paint = new RadialGradientPaint(cx, cy, radius, dist, colors); g2.setPaint(paint); g2.fillArc(cx - radius, cy - radius, radius*2, radius*2, angle, 1); } } } private static Color hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - Math.abs(hp % 2.0 - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255)); } }
Option explicit Class ImgClass Private ImgL,ImgH,ImgDepth,bkclr,loc,tt private xmini,xmaxi,ymini,ymaxi,dirx,diry public ImgArray() private filename private Palette,szpal public property get xmin():xmin=xmini:end property public property get ymin():ymin=ymini:end property public property get xmax():xmax=xmaxi:end property public property get ymax():ymax=ymaxi:end property public property let depth(x) if x<>8 and x<>32 then err.raise 9 Imgdepth=x end property public sub set0 (x0,y0) if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 xmini=-x0 ymini=-y0 xmaxi=xmini+imgl-1 ymaxi=ymini+imgh-1 end sub Public Default Function Init(name,w,h,orient,dep,bkg,mipal) dim i,j ImgL=w ImgH=h tt=timer loc=getlocale set0 0,0 redim imgArray(ImgL-1,ImgH-1) bkclr=bkg if bkg<>0 then for i=0 to ImgL-1 for j=0 to ImgH-1 imgarray(i,j)=bkg next next end if Select Case orient Case 1: dirx=1 : diry=1 Case 2: dirx=-1 : diry=1 Case 3: dirx=-1 : diry=-1 Case 4: dirx=1 : diry=-1 End select filename=name ImgDepth =dep if imgdepth=8 then loadpal(mipal) end if set init=me end function private sub loadpal(mipale) if isarray(mipale) Then palette=mipale szpal=UBound(mipale)+1 Else szpal=256 , not relevant End if End Sub Private Sub Class_Terminate if err<>0 then wscript.echo "Error " & err.number wscript.echo "copying image to bmp file" savebmp wscript.echo "opening " & filename & " with your default bmp viewer" CreateObject("Shell.Application").ShellExecute filename wscript.echo timer-tt & " iseconds" End Sub function long2wstr( x) dim k1,k2,x1 k1= (x and &hffff&) k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0)) long2wstr=chrw(k1) & chrw(k2) end function function int2wstr(x) int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0))) End Function Public Sub SaveBMP Dim s,ostream, x,y,loc const hdrs=54 dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4) dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0 with CreateObject("ADODB.Stream") .Charset = "UTF-16LE" .Type = 2 .open .writetext ChrW(&h4d42) .writetext long2wstr(hdrs+palsize+bms) .writetext long2wstr(0) .writetext long2wstr (hdrs+palsize) .writetext long2wstr(40) .writetext long2wstr(Imgl) .writetext long2wstr(imgh) .writetext int2wstr(1) .writetext int2wstr(imgdepth) .writetext long2wstr(&H0) .writetext long2wstr(bms) .writetext long2wstr(&Hc4e) .writetext long2wstr(&hc43) .writetext long2wstr(szpal) .writetext long2wstr(&H0) Dim x1,x2,y1,y2 If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1 If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 Select Case imgdepth Case 32 For y=y1 To y2 step diry For x=x1 To x2 Step dirx .writetext long2wstr(Imgarray(x,y)) Next Next Case 8 For x=0 to szpal-1 .writetext long2wstr(palette(x)) Next dim pad:pad=ImgL mod 4 For y=y1 to y2 step diry For x=x1 To x2 step dirx*2 .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255)) Next if pad and 1 then .writetext chrw(ImgArray(x2,y)) if pad >1 then .writetext chrw(0) Next Case Else WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits" End Select Dim outf:Set outf= CreateObject("ADODB.Stream") outf.Type = 1 outf.Open .position=2 .CopyTo outf .close outf.savetofile filename,2 outf.close end with End Sub end class function hsv2rgb( Hue, Sat, Value) dim Angle, Radius,Ur,Vr,Wr,Rdim dim r,g,b, rgb Angle = (Hue-150) *0.01745329251994329576923690768489 Ur = Value * 2.55 Radius = Ur * tan(Sat *0.01183199) Vr = Radius * cos(Angle) *0.70710678 Wr = Radius * sin(Angle) *0.40824829 r = (Ur - Vr - Wr) g = (Ur + Vr - Wr) b = (Ur + Wr + Wr) if r >255 then Rdim = (Ur - 255) / (Vr + Wr) r = 255 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim elseif r < 0 then Rdim = Ur / (Vr + Wr) r = 0 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim end if if g >255 then Rdim = (255 - Ur) / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 255 b = Ur + 2 * Wr * Rdim elseif g<0 then Rdim = -Ur / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 0 b = Ur + 2 * Wr * Rdim end if if b>255 then Rdim = (255 - Ur) / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 255 elseif b<0 then Rdim = -Ur / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 0 end If hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff) end function function ang(col,row) if col =0 then if row<0 then ang=90 else ang=270 end if else if col>0 then ang=atn(-row/col)*57.2957795130 else ang=(atn(row/-col)*57.2957795130)+180 end if end if ang=(ang+360) mod 360 end function Dim X,row,col,fn,tt,hr,sat,row2 const h=160 const w=160 const rad=159 const r2=25500 tt=timer fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp" Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0) x.set0 w,h for row=x.xmin+1 to x.xmax row2=row*row hr=int(Sqr(r2-row2)) For col=hr To 159 Dim a:a=((col\16 +row\16) And 1)* &hffffff x.imgArray(col+160,row+160)=a x.imgArray(-col+160,row+160)=a next for col=-hr to hr sat=100-sqr(row2+col*col)/rad *50 x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat) next next Set X = Nothing
Transform the following Java implementation into VB, maintaining the same output and logic.
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0))); var k = j; var d = j; int n = 500; int n0 = n; do { System.out.print(d); i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED); k = TWENTY.multiply(j); for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) { if (k.add(d).multiply(d).compareTo(i) > 0) { d = d.subtract(BigInteger.ONE); break; } } j = j.multiply(BigInteger.TEN).add(d); k = k.add(d); if (n0 > 0) { n--; } } while (n > 0); System.out.println(); } }
Imports System.Math, System.Console, BI = System.Numerics.BigInteger Module Module1 Sub Main(ByVal args As String()) Dim i, j, k, d As BI : i = 2 j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j Dim n As Integer = -1, n0 As Integer = -1, st As DateTime = DateTime.Now If args.Length > 0 Then Integer.TryParse(args(0), n) If n > 0 Then n0 = n Else n = 1 Do Write(d) : i = (i - k * d) * 100 : k = 20 * j For d = 1 To 10 If (k + d) * d > i Then d -= 1 : Exit For Next j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1 Loop While n > 0 If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st) End Sub End Module
Convert this Java block to VB, preserving its control flow and logic.
import java.math.BigInteger; public class SquareRoot { public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100); public static final BigInteger TWENTY = BigInteger.valueOf(20); public static void main(String[] args) { var i = BigInteger.TWO; var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0))); var k = j; var d = j; int n = 500; int n0 = n; do { System.out.print(d); i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED); k = TWENTY.multiply(j); for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) { if (k.add(d).multiply(d).compareTo(i) > 0) { d = d.subtract(BigInteger.ONE); break; } } j = j.multiply(BigInteger.TEN).add(d); k = k.add(d); if (n0 > 0) { n--; } } while (n > 0); System.out.println(); } }
Imports System.Math, System.Console, BI = System.Numerics.BigInteger Module Module1 Sub Main(ByVal args As String()) Dim i, j, k, d As BI : i = 2 j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j Dim n As Integer = -1, n0 As Integer = -1, st As DateTime = DateTime.Now If args.Length > 0 Then Integer.TryParse(args(0), n) If n > 0 Then n0 = n Else n = 1 Do Write(d) : i = (i - k * d) * 100 : k = 20 * j For d = 1 To 10 If (k + d) * d > i Then d -= 1 : Exit For Next j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1 Loop While n > 0 If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st) End Sub End Module
Write a version of this Java function in VB with identical behavior.
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); System.out.println("All public fields (including inherited):"); for (Field f : clazz.getFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } System.out.println(); System.out.println("All declared fields (excluding inherited):"); for (Field f : clazz.getDeclaredFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } } }
Imports System.Reflection Module Module1 Class TestClass Private privateField = 7 Public ReadOnly Property PublicNumber = 4 Private ReadOnly Property PrivateNumber = 2 End Class Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return From p In obj.GetType().GetProperties(flags) Where p.GetIndexParameters().Length = 0 Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)} End Function Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)}) End Function Sub Main() Dim t As New TestClass() Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance For Each prop In GetPropertyValues(t, flags) Console.WriteLine(prop) Next For Each field In GetFieldValues(t, flags) Console.WriteLine(field) Next End Sub End Module
Write a version of this Java function in VB with identical behavior.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class ColumnAligner { private List<String[]> words = new ArrayList<>(); private int columns = 0; private List<Integer> columnWidths = new ArrayList<>(); public ColumnAligner(String s) { String[] lines = s.split("\\n"); for (String line : lines) { processInputLine(line); } } public ColumnAligner(List<String> lines) { for (String line : lines) { processInputLine(line); } } private void processInputLine(String line) { String[] lineWords = line.split("\\$"); words.add(lineWords); columns = Math.max(columns, lineWords.length); for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i >= columnWidths.size()) { columnWidths.add(word.length()); } else { columnWidths.set(i, Math.max(columnWidths.get(i), word.length())); } } } interface AlignFunction { String align(String s, int length); } public String alignLeft() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.rightPad(s, length); } }); } public String alignRight() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.leftPad(s, length); } }); } public String alignCenter() { return align(new AlignFunction() { @Override public String align(String s, int length) { return StringUtils.center(s, length); } }); } private String align(AlignFunction a) { StringBuilder result = new StringBuilder(); for (String[] lineWords : words) { for (int i = 0; i < lineWords.length; i++) { String word = lineWords[i]; if (i == 0) { result.append("|"); } result.append(a.align(word, columnWidths.get(i)) + "|"); } result.append("\n"); } return result.toString(); } public static void main(String args[]) throws IOException { if (args.length < 1) { System.out.println("Usage: ColumnAligner file [left|right|center]"); return; } String filePath = args[0]; String alignment = "left"; if (args.length >= 2) { alignment = args[1]; } ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8)); switch (alignment) { case "left": System.out.print(ca.alignLeft()); break; case "right": System.out.print(ca.alignRight()); break; case "center": System.out.print(ca.alignCenter()); break; default: System.err.println(String.format("Error! Unknown alignment: '%s'", alignment)); break; } } }
Dim MText as QMemorystream MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" MText.WriteLine "are$delineated$by$a$single$ MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" MText.WriteLine "column$are$separated$by$at$least$one$space." MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$" MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column." DefStr TextLeft, TextRight, TextCenter DefStr MLine, LWord, Newline = chr$(13)+chr$(10) DefInt ColWidth(100), ColCount DefSng NrSpaces MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y)) next next MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) NrSpaces = ColWidth(y) - len(LWord) TextLeft = TextLeft + LWord + Space$(NrSpaces+1) TextRight = TextRight + Space$(NrSpaces+1) + LWord TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2)) next TextLeft = TextLeft + Newline TextRight = TextRight + Newline TextCenter = TextCenter + Newline next
Produce a functionally identical VB code for the snippet given in Java.
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Write the same algorithm in VB as shown in this Java implementation.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
Keep all operations the same but rewrite the snippet in VB.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58); private static String convertToBase58(String hash) { return convertToBase58(hash, 16); } private static String convertToBase58(String hash, int base) { BigInteger x; if (base == 16 && hash.substring(0, 2).equals("0x")) { x = new BigInteger(hash.substring(2), 16); } else { x = new BigInteger(hash, base); } StringBuilder sb = new StringBuilder(); while (x.compareTo(BIG0) > 0) { int r = x.mod(BIG58).intValue(); sb.append(ALPHABET.charAt(r)); x = x.divide(BIG58); } return sb.reverse().toString(); } public static void main(String[] args) { String s = "25420294593250030202636073700053352635053786165627414518"; String b = convertToBase58(s, 10); System.out.printf("%s -> %s\n", s, b); List<String> hashes = List.of( "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e" ); for (String hash : hashes) { String b58 = convertToBase58(hash); System.out.printf("%-56s -> %s\n", hash, b58); } } }
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
Transform the following Java implementation into VB, maintaining the same output and logic.
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class DataEncryptionStandard { private static byte[] toHexByteArray(String self) { byte[] bytes = new byte[self.length() / 2]; for (int i = 0; i < bytes.length; ++i) { bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16)); } return bytes; } private static void printHexBytes(byte[] self, String label) { System.out.printf("%s: ", label); for (byte b : self) { int bb = (b >= 0) ? ((int) b) : b + 256; String ts = Integer.toString(bb, 16); if (ts.length() < 2) { ts = "0" + ts; } System.out.print(ts); } System.out.println(); } public static void main(String[] args) throws Exception { String strKey = "0e329232ea6d0d73"; byte[] keyBytes = toHexByteArray(strKey); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); Cipher encCipher = Cipher.getInstance("DES"); encCipher.init(Cipher.ENCRYPT_MODE, key); String strPlain = "8787878787878787"; byte[] plainBytes = toHexByteArray(strPlain); byte[] encBytes = encCipher.doFinal(plainBytes); printHexBytes(encBytes, "Encoded"); Cipher decCipher = Cipher.getInstance("DES"); decCipher.init(Cipher.DECRYPT_MODE, key); byte[] decBytes = decCipher.doFinal(encBytes); printHexBytes(decBytes, "Decoded"); } }
Imports System.IO Imports System.Security.Cryptography Module Module1 Function ByteArrayToString(ba As Byte()) As String Return BitConverter.ToString(ba).Replace("-", "") End Function Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte() Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} Dim provider As New DESCryptoServiceProvider Dim transform = provider.CreateEncryptor(passwordBytes, iv) Dim mode = CryptoStreamMode.Write Dim memStream As New MemoryStream Dim cryptoStream As New CryptoStream(memStream, transform, mode) cryptoStream.Write(messageBytes, 0, messageBytes.Length) cryptoStream.FlushFinalBlock() Dim encryptedMessageBytes(memStream.Length - 1) As Byte memStream.Position = 0 memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length) Return encryptedMessageBytes End Function Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte() Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0} Dim provider As New DESCryptoServiceProvider Dim transform = provider.CreateDecryptor(passwordBytes, iv) Dim mode = CryptoStreamMode.Write Dim memStream As New MemoryStream Dim cryptoStream As New CryptoStream(memStream, transform, mode) cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length) cryptoStream.FlushFinalBlock() Dim decryptedMessageBytes(memStream.Length - 1) As Byte memStream.Position = 0 memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length) Return decryptedMessageBytes End Function Sub Main() Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73} Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87} Dim encStr = Encrypt(plainBytes, keyBytes) Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr)) Dim decStr = Decrypt(encStr, keyBytes) Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr)) End Sub End Module
Translate the given Java code snippet into VB without altering its behavior.
import java.io.File; import java.util.*; import java.util.regex.*; public class CommatizingNumbers { public static void main(String[] args) throws Exception { commatize("pi=3.14159265358979323846264338327950288419716939937510582" + "097494459231", 6, 5, " "); commatize("The author has two Z$100000000000000 Zimbabwe notes (100 " + "trillion).", 0, 3, "."); try (Scanner sc = new Scanner(new File("input.txt"))) { while(sc.hasNext()) commatize(sc.nextLine()); } } static void commatize(String s) { commatize(s, 0, 3, ","); } static void commatize(String s, int start, int step, String ins) { if (start < 0 || start > s.length() || step < 1 || step > s.length()) return; Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start)); StringBuffer result = new StringBuffer(s.substring(0, start)); if (m.find()) { StringBuilder sb = new StringBuilder(m.group(1)).reverse(); for (int i = step; i < sb.length(); i += step) sb.insert(i++, ins); m.appendReplacement(result, sb.reverse().toString()); } System.out.println(m.appendTail(result)); } }
Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3) Dim l As Integer: l = Len(s) For i = start To l If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then For j = i + 1 To l + 1 If j > l Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For Else If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For End If End If Next j Exit For End If Next i Debug.Print s End Sub Public Sub main() commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5 commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "." commatize """-in Aus$+1411.8millions""" commatize "===US$0017440 millions=== (in 2000 dollars)" commatize "123.e8000 is pretty big." commatize "The land area of the earth is 57268900(29% of the surface) square miles." commatize "Ain commatize "James was never known as 0000000007" commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." commatize " $-140000±100 millions." commatize "6/9/1946 was a good year for some." End Sub
Convert the following code from Java to VB, ensuring the logic remains intact.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ArithmeticCoding { private static class Triple<A, B, C> { A a; B b; C c; Triple(A a, B b, C c) { this.a = a; this.b = b; this.c = c; } } private static class Freq extends HashMap<Character, Long> { } private static Freq cumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; ++i) { char c = (char) i; Long v = freq.get(c); if (v != null) { cf.put(c, total); total += v; } } return cf; } private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) { char[] chars = str.toCharArray(); Freq freq = new Freq(); for (char c : chars) { if (!freq.containsKey(c)) freq.put(c, 1L); else freq.put(c, freq.get(c) + 1); } Freq cf = cumulativeFreq(freq); BigInteger base = BigInteger.valueOf(chars.length); BigInteger lower = BigInteger.ZERO; BigInteger pf = BigInteger.ONE; for (char c : chars) { BigInteger x = BigInteger.valueOf(cf.get(c)); lower = lower.multiply(base).add(x.multiply(pf)); pf = pf.multiply(BigInteger.valueOf(freq.get(c))); } BigInteger upper = lower.add(pf); int powr = 0; BigInteger bigRadix = BigInteger.valueOf(radix); while (true) { pf = pf.divide(bigRadix); if (pf.equals(BigInteger.ZERO)) break; powr++; } BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr)); return new Triple<>(diff, powr, freq); } private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = BigInteger.valueOf(radix); BigInteger enc = num.multiply(powr.pow(pwr)); long base = 0; for (Long v : freq.values()) base += v; Freq cf = cumulativeFreq(freq); Map<Long, Character> dict = new HashMap<>(); for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey()); long lchar = -1; for (long i = 0; i < base; ++i) { Character v = dict.get(i); if (v != null) { lchar = v; } else if (lchar != -1) { dict.put(i, (char) lchar); } } StringBuilder decoded = new StringBuilder((int) base); BigInteger bigBase = BigInteger.valueOf(base); for (long i = base - 1; i >= 0; --i) { BigInteger pow = bigBase.pow((int) i); BigInteger div = enc.divide(pow); Character c = dict.get(div.longValue()); BigInteger fv = BigInteger.valueOf(freq.get(c)); BigInteger cv = BigInteger.valueOf(cf.get(c)); BigInteger diff = enc.subtract(pow.multiply(cv)); enc = diff.divide(fv); decoded.append(c); } return decoded.toString(); } public static void main(String[] args) { long radix = 10; String[] strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"}; String fmt = "%-25s=> %19s * %d^%s\n"; for (String str : strings) { Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix); String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c); System.out.printf(fmt, str, encoded.a, radix, encoded.b); if (!Objects.equals(str, dec)) throw new RuntimeException("\tHowever that is incorrect!"); } } }
Imports System.Numerics Imports System.Text Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long) Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long)) Module Module1 Function CumulativeFreq(freq As Freq) As Freq Dim total As Long = 0 Dim cf As New Freq For i = 0 To 255 Dim c = Chr(i) If freq.ContainsKey(c) Then Dim v = freq(c) cf(c) = total total += v End If Next Return cf End Function Function ArithmeticCoding(str As String, radix As Long) As Triple Dim freq As New Freq For Each c In str If freq.ContainsKey(c) Then freq(c) += 1 Else freq(c) = 1 End If Next Dim cf = CumulativeFreq(freq) Dim base As BigInteger = str.Length Dim lower As BigInteger = 0 Dim pf As BigInteger = 1 For Each c In str Dim x = cf(c) lower = lower * base + x * pf pf = pf * freq(c) Next Dim upper = lower + pf Dim powr = 0 Dim bigRadix As BigInteger = radix While True pf = pf / bigRadix If pf = 0 Then Exit While End If powr = powr + 1 End While Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)) Return New Triple(diff, powr, freq) End Function Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String Dim powr As BigInteger = radix Dim enc = num * BigInteger.Pow(powr, pwr) Dim base = freq.Values.Sum() Dim cf = CumulativeFreq(freq) Dim dict As New Dictionary(Of Long, Char) For Each key In cf.Keys Dim value = cf(key) dict(value) = key Next Dim lchar As Long = -1 For i As Long = 0 To base - 1 If dict.ContainsKey(i) Then lchar = AscW(dict(i)) Else dict(i) = ChrW(lchar) End If Next Dim decoded As New StringBuilder Dim bigBase As BigInteger = base For i As Long = base - 1 To 0 Step -1 Dim pow = BigInteger.Pow(bigBase, i) Dim div = enc / pow Dim c = dict(div) Dim fv = freq(c) Dim cv = cf(c) Dim diff = enc - pow * cv enc = diff / fv decoded.Append(c) Next Return decoded.ToString() End Function Sub Main() Dim radix As Long = 10 Dim strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"} For Each St In strings Dim encoded = ArithmeticCoding(St, radix) Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3) Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", St, encoded.Item1, radix, encoded.Item2) If St <> dec Then Throw New Exception(vbTab + "However that is incorrect!") End If Next End Sub End Module
Please provide an equivalent version of this Java code in VB.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; public class Kosaraju { static class Recursive<I> { I func; } private static List<Integer> kosaraju(List<List<Integer>> g) { int size = g.size(); boolean[] vis = new boolean[size]; int[] l = new int[size]; AtomicInteger x = new AtomicInteger(size); List<List<Integer>> t = new ArrayList<>(); for (int i = 0; i < size; ++i) { t.add(new ArrayList<>()); } Recursive<IntConsumer> visit = new Recursive<>(); visit.func = (int u) -> { if (!vis[u]) { vis[u] = true; for (Integer v : g.get(u)) { visit.func.accept(v); t.get(v).add(u); } int xval = x.decrementAndGet(); l[xval] = u; } }; for (int i = 0; i < size; ++i) { visit.func.accept(i); } int[] c = new int[size]; Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>(); assign.func = (Integer u, Integer root) -> { if (vis[u]) { vis[u] = false; c[u] = root; for (Integer v : t.get(u)) { assign.func.accept(v, root); } } }; for (int u : l) { assign.func.accept(u, u); } return Arrays.stream(c).boxed().collect(Collectors.toList()); } public static void main(String[] args) { List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < 8; ++i) { g.add(new ArrayList<>()); } g.get(0).add(1); g.get(1).add(2); g.get(2).add(0); g.get(3).add(1); g.get(3).add(2); g.get(3).add(4); g.get(4).add(3); g.get(4).add(5); g.get(5).add(2); g.get(5).add(6); g.get(6).add(5); g.get(7).add(4); g.get(7).add(6); g.get(7).add(7); List<Integer> output = kosaraju(g); System.out.println(output); } }
Module Module1 Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer) Dim size = g.Count Dim vis(size - 1) As Boolean Dim l(size - 1) As Integer Dim x = size Dim t As New List(Of List(Of Integer)) For i = 1 To size t.Add(New List(Of Integer)) Next Dim visit As Action(Of Integer) = Sub(u As Integer) If Not vis(u) Then vis(u) = True For Each v In g(u) visit(v) t(v).Add(u) Next x -= 1 l(x) = u End If End Sub For i = 1 To size visit(i - 1) Next Dim c(size - 1) As Integer Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer) If vis(u) Then vis(u) = False c(u) = root For Each v In t(u) assign(v, root) Next End If End Sub For Each u In l assign(u, u) Next Return c.ToList End Function Sub Main() Dim g = New List(Of List(Of Integer)) From { New List(Of Integer) From {1}, New List(Of Integer) From {2}, New List(Of Integer) From {0}, New List(Of Integer) From {1, 2, 4}, New List(Of Integer) From {3, 5}, New List(Of Integer) From {2, 6}, New List(Of Integer) From {5}, New List(Of Integer) From {4, 6, 7} } Dim output = Kosaraju(g) Console.WriteLine("[{0}]", String.Join(", ", output)) End Sub End Module
Translate this program into VB but keep the logic exactly as in Java.
package pentominotiling; import java.util.*; public class PentominoTiling { static final char[] symbols = "FILNPTUVWXYZ-".toCharArray(); static final Random rand = new Random(); static final int nRows = 8; static final int nCols = 8; static final int blank = 12; static int[][] grid = new int[nRows][nCols]; static boolean[] placed = new boolean[symbols.length - 1]; public static void main(String[] args) { shuffleShapes(); for (int r = 0; r < nRows; r++) Arrays.fill(grid[r], -1); for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.nextInt(nRows); randCol = rand.nextInt(nCols); } while (grid[randRow][randCol] == blank); grid[randRow][randCol] = blank; } if (solve(0, 0)) { printResult(); } else { System.out.println("no solution"); } } static void shuffleShapes() { int n = shapes.length; while (n > 1) { int r = rand.nextInt(n--); int[][] tmp = shapes[r]; shapes[r] = shapes[n]; shapes[n] = tmp; char tmpSymbol = symbols[r]; symbols[r] = symbols[n]; symbols[n] = tmpSymbol; } } static void printResult() { for (int[] r : grid) { for (int i : r) System.out.printf("%c ", symbols[i]); System.out.println(); } } static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) { for (int i = 0; i < o.length; i += 2) { int x = c + o[i + 1]; int y = r + o[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; } grid[r][c] = shapeIndex; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex; return true; } static void removeOrientation(int[] o, int r, int c) { grid[r][c] = -1; for (int i = 0; i < o.length; i += 2) grid[r + o[i]][c + o[i + 1]] = -1; } static boolean solve(int pos, int numPlaced) { if (numPlaced == shapes.length) return true; int row = pos / nCols; int col = pos % nCols; if (grid[row][col] != -1) return solve(pos + 1, numPlaced); for (int i = 0; i < shapes.length; i++) { if (!placed[i]) { for (int[] orientation : shapes[i]) { if (!tryPlaceOrientation(orientation, row, col, i)) continue; placed[i] = true; if (solve(pos + 1, numPlaced + 1)) return true; removeOrientation(orientation, row, col); placed[i] = false; } } } return false; } static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}}; static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}; static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}}; static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}}; static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}}; static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}}; static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}}; static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}}; static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}}; static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}}; static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}}; static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}}; static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z}; }
Module Module1 Dim symbols As Char() = "XYPFTVNLUZWI█".ToCharArray(), nRows As Integer = 8, nCols As Integer = 8, target As Integer = 12, blank As Integer = 12, grid As Integer()() = New Integer(nRows - 1)() {}, placed As Boolean() = New Boolean(target - 1) {}, pens As List(Of List(Of Integer())), rand As Random, seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586} Sub Main() Unpack(seeds) : rand = New Random() : ShuffleShapes(2) For r As Integer = 0 To nRows - 1 grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next For i As Integer = 0 To 3 Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols) Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank Next If Solve(0, 0) Then PrintResult() Else Console.WriteLine("no solution for this configuration:") : PrintResult() End If If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey() End Sub Sub ShuffleShapes(count As Integer) For i As Integer = 0 To count : For j = 0 To pens.Count - 1 Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch Next : Next End Sub Sub PrintResult() For Each r As Integer() In grid : For Each i As Integer In r Console.Write("{0} ", If(i < 0, ".", symbols(i))) Next : Console.WriteLine() : Next End Sub Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean If numPlaced = target Then Return True Dim row As Integer = pos \ nCols, col As Integer = pos Mod nCols If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced) For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then For Each orientation As Integer() In pens(i) If Not TPO(orientation, row, col, i) Then Continue For placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True RmvO(orientation, row, col) : placed(i) = False Next : End If : Next : Return False End Function Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer) grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2 grid(row + ori(i))(col + ori(i + 1)) = -1 : Next End Sub Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer, ByVal sIdx As Integer) As Boolean For i As Integer = 0 To ori.Length - 1 Step 2 Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i) If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse grid(y)(x) <> -1 Then Return False Next : grid(row)(col) = sIdx For i As Integer = 0 To ori.Length - 1 Step 2 grid(row + ori(i))(col + ori(i + 1)) = sIdx Next : Return True End Function Sub Unpack(sv As Integer()) pens = New List(Of List(Of Integer())) : For Each item In sv Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item), fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7 If i = 4 Then Mir(exi) Else Rot(exi) fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi)) Next : pens.Add(Gen) : Next End Sub Function Expand(i As Integer) As List(Of Integer) Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next End Function Function ToP(p As List(Of Integer)) As Integer() Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1) tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next Dim res As New List(Of Integer) : For Each item In tmp.Skip(1) Dim adj = If((item And 7) > 4, 8, 0) res.Add((adj + item) \ 8) : res.Add((item And 7) - adj) Next : Return res.ToArray() End Function Function TheSame(a As Integer(), b As Integer()) As Boolean For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False Next : Return True End Function Sub Rot(ByRef p As List(Of Integer)) For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next End Sub Sub Mir(ByRef p As List(Of Integer)) For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next End Sub End Module
Write the same algorithm in VB as shown in this Java implementation.
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup"); if(!backFile.exists()) { backFile.createNewFile(); } Path back = Paths.get(filename + ".backup").toRealPath(); Files.move(file, back, StandardCopyOption.REPLACE_EXISTING); try(PrintWriter out = new PrintWriter(file.toFile())){ for(int i = 0; i < data.length; i++) { out.print(data[i]); if(i < data.length - 1) { out.println(); } } } } public static void main(String[] args) { try { saveWithBackup("original.txt", "fourth", "fifth", "sixth"); } catch (IOException e) { System.err.println(e); } } }
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") link = .TargetPath .Close End With Name link As link & ".bak" End If End If End Sub Public Sub main() backup "D:\test.txt" End Sub
Convert this Java snippet to VB and keep its semantics consistent.
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.*; public class Backup { public static void saveWithBackup(String filename, String... data) throws IOException { Path file = Paths.get(filename).toRealPath(); File backFile = new File(filename + ".backup"); if(!backFile.exists()) { backFile.createNewFile(); } Path back = Paths.get(filename + ".backup").toRealPath(); Files.move(file, back, StandardCopyOption.REPLACE_EXISTING); try(PrintWriter out = new PrintWriter(file.toFile())){ for(int i = 0; i < data.length; i++) { out.print(data[i]); if(i < data.length - 1) { out.println(); } } } } public static void main(String[] args) { try { saveWithBackup("original.txt", "fourth", "fifth", "sixth"); } catch (IOException e) { System.err.println(e); } } }
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") link = .TargetPath .Close End With Name link As link & ".bak" End If End If End Sub Public Sub main() backup "D:\test.txt" End Sub
Write the same code in VB as shown below in Java.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FILE_NAME = "MachinFormula.txt"; public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } } private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } } private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); } private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); } private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); } private static Fraction evaluateArctan(int coefficient, Fraction fraction) { if ( coefficient == 1 ) { return fraction; } else if ( coefficient < 0 ) { return evaluateArctan(-coefficient, fraction).negate(); } if ( coefficient % 2 == 0 ) { Fraction f = evaluateArctan(coefficient/2, fraction); return arctanFormula(f, f); } Fraction a = evaluateArctan(coefficient/2, fraction); Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); return arctanFormula(a, b); } private static Fraction arctanFormula(Fraction f1, Fraction f2) { return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); } private static class Fraction { public static final Fraction ONE = new Fraction("1", "1"); private BigInteger numerator; private BigInteger denominator; public Fraction(String num, String den) { numerator = new BigInteger(num); denominator = new BigInteger(den); } public Fraction(BigInteger num, BigInteger den) { numerator = num; denominator = den; } public Fraction negate() { return new Fraction(numerator.negate(), denominator); } public Fraction add(Fraction f) { BigInteger gcd = denominator.gcd(f.denominator); BigInteger first = numerator.multiply(f.denominator.divide(gcd)); BigInteger second = f.numerator.multiply(denominator.divide(gcd)); return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); } public Fraction subtract(Fraction f) { return add(f.negate()); } public Fraction multiply(Fraction f) { BigInteger num = numerator.multiply(f.numerator); BigInteger den = denominator.multiply(f.denominator); BigInteger gcd = num.gcd(den); return new Fraction(num.divide(gcd), den.divide(gcd)); } public Fraction divide(Fraction f) { return multiply(new Fraction(f.denominator, f.numerator)); } @Override public String toString() { if ( denominator.compareTo(BigInteger.ONE) == 0 ) { return numerator.toString(); } return numerator + " / " + denominator; } } private static class Term { private int coefficient; private Fraction fraction; public Term(int c, Fraction f) { coefficient = c; fraction = f; } } }
Imports System.Numerics Public Class BigRat Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) nu = bRat.nu : de = bRat.de End Sub Sub New(n As BigInteger, d As BigInteger) If d = BigInteger.Zero Then _ Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d))) Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d) If bi > BigInteger.One Then n /= bi : d /= bi If d < BigInteger.Zero Then n = -n : d = -d nu = n : de = d End Sub Shared Operator -(x As BigRat) As BigRat Return New BigRat(-x.nu, x.de) End Operator Shared Operator +(x As BigRat, y As BigRat) Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de) End Operator Shared Operator -(x As BigRat, y As BigRat) As BigRat Return x + (-y) End Operator Shared Operator *(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.nu, x.de * y.de) End Operator Shared Operator /(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.de, x.de * y.nu) End Operator Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Dim dif As BigRat = New BigRat(nu, de) - obj If dif.nu < BigInteger.Zero Then Return -1 If dif.nu > BigInteger.Zero Then Return 1 Return 0 End Function Shared Operator =(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) = 0 End Operator Shared Operator <>(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) <> 0 End Operator Overrides Function ToString() As String If de = BigInteger.One Then Return nu.ToString Return String.Format("({0}/{1})", nu, de) End Function Shared Function Combine(a As BigRat, b As BigRat) As BigRat Return (a + b) / (BigRat.One - (a * b)) End Function End Class Public Structure Term Dim c As Integer, br As BigRat Sub New(cc As Integer, bigr As BigRat) c = cc : br = bigr End Sub End Structure Module Module1 Function Eval(c As Integer, x As BigRat) As BigRat If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x) Dim hc As Integer = c \ 2 Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x)) End Function Function Sum(terms As List(Of Term)) As BigRat If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br) Dim htc As Integer = terms.Count / 2 Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList)) End Function Function ParseLine(ByVal s As String) As List(Of Term) ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero) While t.Contains(" ") : t = t.Replace(" ", "") : End While p = t.IndexOf("pi/4=") : If p < 0 Then _ Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function t = t.Substring(p + 5) For Each item As String In t.Split(")") If item.Length > 5 Then If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item) ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function End If x.c = 1 : x.br = New BigRat(BigRat.One) p = item.IndexOf("/") : If p > 0 Then x.br.de = UInt64.Parse(item.Substring(p + 1)) item = item.Substring(0, p) p = item.IndexOf("(") : If p > 0 Then x.br.nu = UInt64.Parse(item.Substring(p + 1)) p = item.IndexOf("a") : If p > 0 Then Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c) If x.c = 0 Then x.c = 1 If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c End If ParseLine.Add(x) End If End If End If Next End Function Sub Main(ByVal args As String()) Dim nl As String = vbLf For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl & "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl & "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl & "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl & "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl & "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl & "PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl & "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl & "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl & "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl & "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl & "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl & "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl & "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl & "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl) Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item) Next End Sub End Module
Port the provided Java code into VB while preserving the original functionality.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CheckMachinFormula { private static String FILE_NAME = "MachinFormula.txt"; public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } } private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } } private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); } private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); } private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); } private static Fraction evaluateArctan(int coefficient, Fraction fraction) { if ( coefficient == 1 ) { return fraction; } else if ( coefficient < 0 ) { return evaluateArctan(-coefficient, fraction).negate(); } if ( coefficient % 2 == 0 ) { Fraction f = evaluateArctan(coefficient/2, fraction); return arctanFormula(f, f); } Fraction a = evaluateArctan(coefficient/2, fraction); Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); return arctanFormula(a, b); } private static Fraction arctanFormula(Fraction f1, Fraction f2) { return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); } private static class Fraction { public static final Fraction ONE = new Fraction("1", "1"); private BigInteger numerator; private BigInteger denominator; public Fraction(String num, String den) { numerator = new BigInteger(num); denominator = new BigInteger(den); } public Fraction(BigInteger num, BigInteger den) { numerator = num; denominator = den; } public Fraction negate() { return new Fraction(numerator.negate(), denominator); } public Fraction add(Fraction f) { BigInteger gcd = denominator.gcd(f.denominator); BigInteger first = numerator.multiply(f.denominator.divide(gcd)); BigInteger second = f.numerator.multiply(denominator.divide(gcd)); return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); } public Fraction subtract(Fraction f) { return add(f.negate()); } public Fraction multiply(Fraction f) { BigInteger num = numerator.multiply(f.numerator); BigInteger den = denominator.multiply(f.denominator); BigInteger gcd = num.gcd(den); return new Fraction(num.divide(gcd), den.divide(gcd)); } public Fraction divide(Fraction f) { return multiply(new Fraction(f.denominator, f.numerator)); } @Override public String toString() { if ( denominator.compareTo(BigInteger.ONE) == 0 ) { return numerator.toString(); } return numerator + " / " + denominator; } } private static class Term { private int coefficient; private Fraction fraction; public Term(int c, Fraction f) { coefficient = c; fraction = f; } } }
Imports System.Numerics Public Class BigRat Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) nu = bRat.nu : de = bRat.de End Sub Sub New(n As BigInteger, d As BigInteger) If d = BigInteger.Zero Then _ Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d))) Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d) If bi > BigInteger.One Then n /= bi : d /= bi If d < BigInteger.Zero Then n = -n : d = -d nu = n : de = d End Sub Shared Operator -(x As BigRat) As BigRat Return New BigRat(-x.nu, x.de) End Operator Shared Operator +(x As BigRat, y As BigRat) Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de) End Operator Shared Operator -(x As BigRat, y As BigRat) As BigRat Return x + (-y) End Operator Shared Operator *(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.nu, x.de * y.de) End Operator Shared Operator /(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.de, x.de * y.nu) End Operator Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Dim dif As BigRat = New BigRat(nu, de) - obj If dif.nu < BigInteger.Zero Then Return -1 If dif.nu > BigInteger.Zero Then Return 1 Return 0 End Function Shared Operator =(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) = 0 End Operator Shared Operator <>(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) <> 0 End Operator Overrides Function ToString() As String If de = BigInteger.One Then Return nu.ToString Return String.Format("({0}/{1})", nu, de) End Function Shared Function Combine(a As BigRat, b As BigRat) As BigRat Return (a + b) / (BigRat.One - (a * b)) End Function End Class Public Structure Term Dim c As Integer, br As BigRat Sub New(cc As Integer, bigr As BigRat) c = cc : br = bigr End Sub End Structure Module Module1 Function Eval(c As Integer, x As BigRat) As BigRat If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x) Dim hc As Integer = c \ 2 Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x)) End Function Function Sum(terms As List(Of Term)) As BigRat If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br) Dim htc As Integer = terms.Count / 2 Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList)) End Function Function ParseLine(ByVal s As String) As List(Of Term) ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero) While t.Contains(" ") : t = t.Replace(" ", "") : End While p = t.IndexOf("pi/4=") : If p < 0 Then _ Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function t = t.Substring(p + 5) For Each item As String In t.Split(")") If item.Length > 5 Then If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item) ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function End If x.c = 1 : x.br = New BigRat(BigRat.One) p = item.IndexOf("/") : If p > 0 Then x.br.de = UInt64.Parse(item.Substring(p + 1)) item = item.Substring(0, p) p = item.IndexOf("(") : If p > 0 Then x.br.nu = UInt64.Parse(item.Substring(p + 1)) p = item.IndexOf("a") : If p > 0 Then Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c) If x.c = 0 Then x.c = 1 If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c End If ParseLine.Add(x) End If End If End If Next End Function Sub Main(ByVal args As String()) Dim nl As String = vbLf For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl & "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl & "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl & "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl & "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl & "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl & "PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl & "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl & "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl & "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl & "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl & "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl & "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl & "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl & "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl) Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item) Next End Sub End Module
Produce a functionally identical VB code for the snippet given in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; public class IQPuzzle { public static void main(String[] args) { System.out.printf(" "); for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) { System.out.printf("  %,6d", start); } System.out.printf("%n"); for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) { System.out.printf("%2d", start); Map<Integer,Integer> solutions = solve(start); for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) { System.out.printf("  %,6d", solutions.containsKey(end) ? solutions.get(end) : 0); } System.out.printf("%n"); } int moveNum = 0; System.out.printf("%nOne Solution:%n"); for ( Move m : oneSolution ) { moveNum++; System.out.printf("Move %d = %s%n", moveNum, m); } } private static List<Move> oneSolution = null; private static Map<Integer, Integer> solve(int emptyPeg) { Puzzle puzzle = new Puzzle(emptyPeg); Map<Integer,Integer> solutions = new HashMap<>(); Stack<Puzzle> stack = new Stack<Puzzle>(); stack.push(puzzle); while ( ! stack.isEmpty() ) { Puzzle p = stack.pop(); if ( p.solved() ) { solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2); if ( oneSolution == null ) { oneSolution = p.moves; } continue; } for ( Move move : p.getValidMoves() ) { Puzzle pMove = p.move(move); stack.add(pMove); } } return solutions; } private static class Puzzle { public static int MAX_PEGS = 16; private boolean[] pegs = new boolean[MAX_PEGS]; private List<Move> moves; public Puzzle(int emptyPeg) { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { pegs[i] = true; } pegs[emptyPeg] = false; moves = new ArrayList<>(); } public Puzzle() { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { pegs[i] = true; } moves = new ArrayList<>(); } private static Map<Integer,List<Move>> validMoves = new HashMap<>(); static { validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6))); validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9))); validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10))); validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11))); validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14))); validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15))); validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9))); validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10))); validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7))); validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8))); validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13))); validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14))); validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15))); validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5))); validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6))); } public List<Move> getValidMoves() { List<Move> moves = new ArrayList<Move>(); for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { for ( Move testMove : validMoves.get(i) ) { if ( pegs[testMove.jump] && ! pegs[testMove.end] ) { moves.add(testMove); } } } } return moves; } public boolean solved() { boolean foundFirstPeg = false; for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { if ( foundFirstPeg ) { return false; } foundFirstPeg = true; } } return true; } public Puzzle move(Move move) { Puzzle p = new Puzzle(); if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) { throw new RuntimeException("Invalid move."); } for ( int i = 1 ; i < MAX_PEGS ; i++ ) { p.pegs[i] = pegs[i]; } p.pegs[move.start] = false; p.pegs[move.jump] = false; p.pegs[move.end] = true; for ( Move m : moves ) { p.moves.add(new Move(m.start, m.jump, m.end)); } p.moves.add(new Move(move.start, move.jump, move.end)); return p; } public int getLastPeg() { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { return i; } } throw new RuntimeException("ERROR: Illegal position."); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for ( int i = 1 ; i < MAX_PEGS ; i++ ) { sb.append(pegs[i] ? 1 : 0); sb.append(","); } sb.setLength(sb.length()-1); sb.append("]"); return sb.toString(); } } private static class Move { int start; int jump; int end; public Move(int s, int j, int e) { start = s; jump = j; end = e; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("s=" + start); sb.append(", j=" + jump); sb.append(", e=" + end); sb.append("}"); return sb.toString(); } } }
Imports System, Microsoft.VisualBasic.DateAndTime Public Module Module1 Const n As Integer = 5 Dim Board As String Dim Starting As Integer = 1 Dim Target As Integer = 13 Dim Moves As Integer() Dim bi() As Integer Dim ib() As Integer Dim nl As Char = Convert.ToChar(10) Public Function Dou(s As String) As String Dou = "" : Dim b As Boolean = True For Each ch As Char In s If b Then b = ch <> " " If b Then Dou &= ch & " " Else Dou = " " & Dou Next : Dou = Dou.TrimEnd() End Function Public Function Fmt(s As String) As String If s.Length < Board.Length Then Return s Fmt = "" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) & If(i = n, s.Substring(Board.Length), "") & nl Next End Function Public Function Triangle(n As Integer) As Integer Return (n * (n + 1)) / 2 End Function Public Function Init(s As String, pos As Integer) As String Init = s : Mid(Init, pos, 1) = "0" End Function Public Sub InitIndex() ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0 For i As Integer = 0 To ib.Length - 1 If i = 0 Then ib(i) = 0 : bi(j) = 0 : j += 1 Else If Board(i - 1) = "1" Then ib(i) = j : bi(j) = i : j += 1 End If Next End Sub Public Function solve(brd As String, pegsLeft As Integer) As String If pegsLeft = 1 Then If Target = 0 Then Return "Completed" If brd(bi(Target) - 1) = "1" Then Return "Completed" Else Return "fail" End If For i = 1 To Board.Length If brd(i - 1) = "1" Then For Each mj In Moves Dim over As Integer = i + mj Dim land As Integer = i + 2 * mj If land >= 1 AndAlso land <= brd.Length _ AndAlso brd(land - 1) = "0" _ AndAlso brd(over - 1) = "1" Then setPegs(brd, "001", i, over, land) Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1) If Res.Length <> 4 Then _ Return brd & info(i, over, land) & nl & Res setPegs(brd, "110", i, over, land) End If Next End If Next Return "fail" End Function Function info(frm As Integer, over As Integer, dest As Integer) As String Return " Peg from " & ib(frm).ToString() & " goes to " & ib(dest).ToString() & ", removing peg at " & ib(over).ToString() End Function Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer) Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2) End Sub Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer) x = Math.Max(Math.Min(x, hi), lo) End Sub Public Sub Main() Dim t As Integer = Triangle(n) LimitIt(Starting, 1, t) LimitIt(Target, 0, t) Dim stime As Date = Now() Moves = {-n - 1, -n, -1, 1, n, n + 1} Board = New String("1", n * n) For i As Integer = 0 To n - 2 Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(" ", n - 1 - i) Next InitIndex() Dim B As String = Init(Board, bi(Starting)) Console.WriteLine(Fmt(B & " Starting with peg removed from " & Starting.ToString())) Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl) Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & " ms." If res(0).Length = 4 Then If Target = 0 Then Console.WriteLine("Unable to find a solution with last peg left anywhere.") Else Console.WriteLine("Unable to find a solution with last peg left at " & Target.ToString() & ".") End If Console.WriteLine("Computation time: " & ts) Else For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next Console.WriteLine("Computation time to first found solution: " & ts) End If If Diagnostics.Debugger.IsAttached Then Console.ReadLine() End Sub End Module
Preserve the algorithm and functionality while converting the code from Java to VB.
public class LogicPuzzle { boolean S[] = new boolean[13]; int Count = 0; public boolean check2 () { int count = 0; for (int k = 7; k <= 12; k++) if (S[k]) count++; return S[2] == (count == 3); } public boolean check3 () { int count = 0; for (int k = 2; k <= 12; k += 2) if (S[k]) count++; return S[3] == (count == 2); } public boolean check4 () { return S[4] == ( !S[5] || S[6] && S[7]); } public boolean check5 () { return S[5] == ( !S[2] && !S[3] && !S[4]); } public boolean check6 () { int count = 0; for (int k = 1; k <= 11; k += 2) if (S[k]) count++; return S[6] == (count == 4); } public boolean check7 () { return S[7] == ((S[2] || S[3]) && !(S[2] && S[3])); } public boolean check8 () { return S[8] == ( !S[7] || S[5] && S[6]); } public boolean check9 () { int count = 0; for (int k = 1; k <= 6; k++) if (S[k]) count++; return S[9] == (count == 3); } public boolean check10 () { return S[10] == (S[11] && S[12]); } public boolean check11 () { int count = 0; for (int k = 7; k <= 9; k++) if (S[k]) count++; return S[11] == (count == 1); } public boolean check12 () { int count = 0; for (int k = 1; k <= 11; k++) if (S[k]) count++; return S[12] == (count == 4); } public void check () { if (check2() && check3() && check4() && check5() && check6() && check7() && check8() && check9() && check10() && check11() && check12()) { for (int k = 1; k <= 12; k++) if (S[k]) System.out.print(k + " "); System.out.println(); Count++; } } public void recurseAll (int k) { if (k == 13) check(); else { S[k] = false; recurseAll(k + 1); S[k] = true; recurseAll(k + 1); } } public static void main (String args[]) { LogicPuzzle P = new LogicPuzzle(); P.S[1] = true; P.recurseAll(2); System.out.println(); System.out.println(P.Count + " Solutions found."); } }
Public s As String Public t As Integer Function s1() s1 = Len(s) = 12 End Function Function s2() t = 0 For i = 7 To 12 t = t - (Mid(s, i, 1) = "1") Next i s2 = t = 3 End Function Function s3() t = 0 For i = 2 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s3 = t = 2 End Function Function s4() s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1")) End Function Function s5() s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0" End Function Function s6() t = 0 For i = 1 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s6 = t = 4 End Function Function s7() s7 = Mid(s, 2, 1) <> Mid(s, 3, 1) End Function Function s8() s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1") End Function Function s9() t = 0 For i = 1 To 6 t = t - (Mid(s, i, 1) = "1") Next i s9 = t = 3 End Function Function s10() s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1" End Function Function s11() t = 0 For i = 7 To 9 t = t - (Mid(s, i, 1) = "1") Next i s11 = t = 1 End Function Function s12() t = 0 For i = 1 To 11 t = t - (Mid(s, i, 1) = "1") Next i s12 = t = 4 End Function Public Sub twelve_statements() For i = 0 To 2 ^ 12 - 1 s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _ & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7) For b = 1 To 12 Select Case b Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For End Select If b = 12 Then Debug.Print s Next Next End Sub
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> #include <stdlib.h> struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf("%s", info[it].text); found_word = 1; } } if (0 == found_word) printf("%d", i); printf("\n"); } } int main(void) { struct replace_info info[3] = { {5, "Buzz"}, {7, "Baxx"}, {3, "Fizz"} }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
package main import ( "fmt" ) const numbers = 3 func main() { max := 20 words := map[int]string{ 3: "Fizz", 5: "Buzz", 7: "Baxx", } keys := []int{3, 5, 7} divisible := false for i := 1; i <= max; i++ { for _, n := range keys { if i % n == 0 { fmt.Print(words[n]) divisible = true } } if !divisible { fmt.Print(i) } fmt.Println() divisible = false } }
Write the same algorithm in Go as shown in this C implementation.
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
Translate this program into Go but keep the logic exactly as in C.
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
Port the following code from C to Go with equivalent syntax and logic.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> int main() { int jobs = 41, tid; omp_set_num_threads(5); #pragma omp parallel shared(jobs) private(tid) { tid = omp_get_thread_num(); while (jobs > 0) { #pragma omp barrier if (!jobs) break; printf("%d: taking job %d\n", tid, jobs--); usleep(100000 + rand() / (double) RAND_MAX * 3000000); printf("%d: done job\n", tid); } printf("[%d] leaving\n", tid); #pragma omp barrier } return 0; }
package main import ( "log" "math/rand" "sync" "time" ) func worker(part string) { log.Println(part, "worker begins part") time.Sleep(time.Duration(rand.Int63n(1e6))) log.Println(part, "worker completes part") wg.Done() } var ( partList = []string{"A", "B", "C", "D"} nAssemblies = 3 wg sync.WaitGroup ) func main() { rand.Seed(time.Now().UnixNano()) for c := 1; c <= nAssemblies; c++ { log.Println("begin assembly cycle", c) wg.Add(len(partList)) for _, part := range partList { go worker(part) } wg.Wait() log.Println("assemble. cycle", c, "complete") } }
Write a version of this C function in Go with identical behavior.
#include <stdio.h> #include <stdint.h> void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; } uint64_t from_seq(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++ & 128); return r; } int main() { uint8_t s[10]; uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; int i, j; for (j = 0; j < sizeof(x)/8; j++) { to_seq(x[j], s); printf("seq from %llx: [ ", x[j]); i = 0; do { printf("%02x ", s[i]); } while ((s[i++] & 128)); printf("] back: %llx\n", from_seq(s)); } return 0; }
package main import ( "fmt" "encoding/binary" ) func main() { buf := make([]byte, binary.MaxVarintLen64) for _, x := range []int64{0x200000, 0x1fffff} { v := buf[:binary.PutVarint(buf, x)] fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v) x, _ = binary.Varint(v) fmt.Println(x, "decoded") } }
Write a version of this C function in Go with identical behavior.
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> void * record(size_t bytes) { int fd; if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0; void *a = malloc(bytes); read(fd, a, bytes); close(fd); return a; } int play(void *buf, size_t len) { int fd; if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0; write(fd, buf, len); close(fd); return 1; } int main() { void *p = record(65536); play(p, 65536); return 0; }
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) name := "" for name == "" { fmt.Print("Enter output file name (without extension) : ") scanner.Scan() name = scanner.Text() check(scanner.Err()) } name += ".wav" rate := 0 for rate < 2000 || rate > 192000 { fmt.Print("Enter sampling rate in Hz (2000 to 192000) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) rate, _ = strconv.Atoi(input) } rateS := strconv.Itoa(rate) dur := 0.0 for dur < 5 || dur > 30 { fmt.Print("Enter duration in seconds (5 to 30)  : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) dur, _ = strconv.ParseFloat(input, 64) } durS := strconv.FormatFloat(dur, 'f', -1, 64) fmt.Println("OK, start speaking now...") args := []string{"-r", rateS, "-f", "S16_LE", "-d", durS, name} cmd := exec.Command("arecord", args...) err := cmd.Run() check(err) fmt.Printf("'%s' created on disk and will now be played back...\n", name) cmd = exec.Command("aplay", name) err = cmd.Run() check(err) fmt.Println("Play-back completed.") }
Convert this C block to Go, preserving its control flow and logic.
#include <glib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> guchar* sha256_merkle_tree(FILE* in, size_t block_size) { gchar* buffer = g_malloc(block_size); GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free); gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256); GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256); size_t bytes; while ((bytes = fread(buffer, 1, block_size, in)) > 0) { g_checksum_reset(checksum); g_checksum_update(checksum, (guchar*)buffer, bytes); gsize len = digest_length; guchar* digest = g_malloc(len); g_checksum_get_digest(checksum, digest, &len); g_ptr_array_add(hashes, digest); } g_free(buffer); guint hashes_length = hashes->len; if (hashes_length == 0) { g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return NULL; } while (hashes_length > 1) { guint j = 0; for (guint i = 0; i < hashes_length; i += 2, ++j) { guchar* digest1 = g_ptr_array_index(hashes, i); guchar* digest_out = g_ptr_array_index(hashes, j); if (i + 1 < hashes_length) { guchar* digest2 = g_ptr_array_index(hashes, i + 1); g_checksum_reset(checksum); g_checksum_update(checksum, digest1, digest_length); g_checksum_update(checksum, digest2, digest_length); gsize len = digest_length; g_checksum_get_digest(checksum, digest_out, &len); } else { memcpy(digest_out, digest1, digest_length); } } hashes_length = j; } guchar* result = g_ptr_array_steal_index(hashes, 0); g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return result; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s filename\n", argv[0]); return EXIT_FAILURE; } FILE* in = fopen(argv[1], "rb"); if (in) { guchar* digest = sha256_merkle_tree(in, 1024); fclose(in); if (digest) { gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256); for (gssize i = 0; i < length; ++i) printf("%02x", digest[i]); printf("\n"); g_free(digest); } } else { perror(argv[1]); return EXIT_FAILURE; } return EXIT_SUCCESS; }
package main import ( "crypto/sha256" "fmt" "io" "log" "os" ) func main() { const blockSize = 1024 f, err := os.Open("title.png") if err != nil { log.Fatal(err) } defer f.Close() var hashes [][]byte buffer := make([]byte, blockSize) h := sha256.New() for { bytesRead, err := f.Read(buffer) if err != nil { if err != io.EOF { log.Fatal(err) } break } h.Reset() h.Write(buffer[:bytesRead]) hashes = append(hashes, h.Sum(nil)) } buffer = make([]byte, 64) for len(hashes) > 1 { var hashes2 [][]byte for i := 0; i < len(hashes); i += 2 { if i < len(hashes)-1 { copy(buffer, hashes[i]) copy(buffer[32:], hashes[i+1]) h.Reset() h.Write(buffer) hashes2 = append(hashes2, h.Sum(nil)) } else { hashes2 = append(hashes2, hashes[i]) } } hashes = hashes2 } fmt.Printf("%x", hashes[0]) fmt.Println() }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <ctype.h> #include <stdio.h> void str_toupper(char *s) { while(*s) { *s=toupper(*s); s++; } } void str_tolower(char *s) { while(*s) { *s=tolower(*s); s++; } } int main(int argc, char *argv[]) { char t[255]="alphaBETA"; str_toupper(t); printf("uppercase: %s\n", t); str_tolower(t); printf("lowercase: %s\n", t); return 0; }
package main import ( "fmt" "strings" "unicode" "unicode/utf8" ) func main() { show("alphaBETA") show("alpha BETA") show("DŽLjnj") show("o'hare O'HARE o’hare don't") } func show(s string) { fmt.Println("\nstring: ", s, " len:", utf8.RuneCountInString(s), "runes") fmt.Println("All upper case: ", strings.ToUpper(s)) fmt.Println("All lower case: ", strings.ToLower(s)) fmt.Println("All title case: ", strings.ToTitle(s)) fmt.Println("Title words: ", strings.Title(s)) fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) }
Write the same algorithm in Go as shown in this C implementation.
#include <gtk/gtk.h> void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg; gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]); msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "You wrote '%s' and selected the number %d%s", c, (gint)v, (v==75000) ? "" : " which is wrong (75000 expected)!"); gtk_widget_show_all(GTK_WIDGET(msg)); (void)gtk_dialog_run(GTK_DIALOG(msg)); gtk_widget_destroy(GTK_WIDGET(msg)); if ( v==75000 ) gtk_main_quit(); } int main(int argc, char **argv) { GtkWindow *win; GtkEntry *entry; GtkSpinButton *spin; GtkButton *okbutton; GtkLabel *entry_l, *spin_l; GtkHBox *hbox[2]; GtkVBox *vbox; GtkWidget *widgs[2]; gtk_init(&argc, &argv); win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, "Insert values"); entry_l = (GtkLabel *)gtk_label_new("Insert a string"); spin_l = (GtkLabel *)gtk_label_new("Insert 75000"); entry = (GtkEntry *)gtk_entry_new(); spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1); widgs[0] = GTK_WIDGET(entry); widgs[1] = GTK_WIDGET(spin); okbutton = (GtkButton *)gtk_button_new_with_label("Ok"); hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1); vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin)); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str1, str2 string) bool { n, err := strconv.ParseFloat(str2, 64) if len(str1) == 0 || err != nil || n != 75000 { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid input", ) dialog.Run() dialog.Destroy() return false } return true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1) check(err, "Unable to create vertical box:") vbox.SetBorderWidth(1) hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create first horizontal box:") hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create second horizontal box:") label, err := gtk.LabelNew("Enter a string and the number 75000 \n") check(err, "Unable to create label:") sel, err := gtk.LabelNew("String: ") check(err, "Unable to create string entry label:") nel, err := gtk.LabelNew("Number: ") check(err, "Unable to create number entry label:") se, err := gtk.EntryNew() check(err, "Unable to create string entry:") ne, err := gtk.EntryNew() check(err, "Unable to create number entry:") hbox1.PackStart(sel, false, false, 2) hbox1.PackStart(se, false, false, 2) hbox2.PackStart(nel, false, false, 2) hbox2.PackStart(ne, false, false, 2) ab, err := gtk.ButtonNewWithLabel("Accept") check(err, "Unable to create accept button:") ab.Connect("clicked", func() { str1, _ := se.GetText() str2, _ := ne.GetText() if validateInput(window, str1, str2) { window.Destroy() } }) vbox.Add(label) vbox.Add(hbox1) vbox.Add(hbox2) vbox.Add(ab) window.Add(vbox) window.ShowAll() gtk.Main() }
Write the same algorithm in Go as shown in this C implementation.
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct cursor_tag { double x; double y; int angle; } cursor_t; void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; } void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, "L%g,%g\n", cursor->x, cursor->y); } void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } } void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, "<svg xmlns='http: size, size); fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n"); fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='"); fprintf(out, "M%g,%g\n", cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, "'/>\n</svg>\n"); } int main(int argc, char** argv) { const char* filename = "sierpinski_arrowhead.svg"; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, "w"); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) iy = 1.0 theta = 0 ) var cx, cy, h float64 func arrowhead(order int, length float64) { if order&1 == 0 { curve(order, length, 60) } else { turn(60) curve(order, length, -60) } drawLine(length) } func drawLine(length float64) { dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h) rads := gg.Radians(float64(theta)) cx += length * math.Cos(rads) cy += length * math.Sin(rads) } func turn(angle int) { theta = (theta + angle) % 360 } func curve(order int, length float64, angle int) { if order == 0 { drawLine(length) } else { curve(order-1, length/2, -angle) turn(angle) curve(order-1, length/2, angle) turn(angle) curve(order-1, length/2, -angle) } } func main() { dc.SetRGB(0, 0, 0) dc.Clear() order := 6 if order&1 == 0 { iy = -1 } cx, cy = width/2, height h = cx / 2 arrowhead(order, cx) dc.SetRGB255(255, 0, 255) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_arrowhead_curve.png") }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <string.h> static int badHrs, maxBadHrs; static double hrsTot = 0.0; static int rdgsTot = 0; char bhEndDate[40]; int mungeLine( char *line, int lno, FILE *fout ) { char date[40], *tkn; int dHrs, flag, hrs2, hrs; double hrsSum; int hrsCnt = 0; double avg; tkn = strtok(line, "."); if (tkn) { int n = sscanf(tkn, "%s %d", &date, &hrs2); if (n<2) { printf("badly formated line - %d %s\n", lno, tkn); return 0; } hrsSum = 0.0; while( tkn= strtok(NULL, ".")) { n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs); if (n>=2) { if (flag > 0) { hrsSum += 1.0*hrs2 + .001*dHrs; hrsCnt += 1; if (maxBadHrs < badHrs) { maxBadHrs = badHrs; strcpy(bhEndDate, date); } badHrs = 0; } else { badHrs += 1; } hrs2 = hrs; } else { printf("bad file syntax line %d: %s\n",lno, tkn); } } avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0; fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n", date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt); hrsTot += hrsSum; rdgsTot += hrsCnt; } return 1; } int main() { FILE *infile, *outfile; int lineNo = 0; char line[512]; const char *ifilename = "readings.txt"; outfile = fopen("V0.txt", "w"); infile = fopen(ifilename, "rb"); if (!infile) { printf("Can't open %s\n", ifilename); exit(1); } while (NULL != fgets(line, 512, infile)) { lineNo += 1; if (0 == mungeLine(line, lineNo, outfile)) printf("Bad line at %d",lineNo); } fclose(infile); fprintf(outfile, "File: %s\n", ifilename); fprintf(outfile, "Total:  %.3f\n", hrsTot); fprintf(outfile, "Readings: %d\n", rdgsTot); fprintf(outfile, "Average:  %.3f\n", hrsTot/rdgsTot); fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs); fprintf(outfile, "Ends on date %s\n", bhEndDate); fclose(outfile); return 0; }
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) const ( filename = "readings.txt" readings = 24 fields = readings*2 + 1 ) func main() { file, err := os.Open(filename) if err != nil { log.Fatal(err) } defer file.Close() var ( badRun, maxRun int badDate, maxDate string fileSum float64 fileAccept int ) endBadRun := func() { if badRun > maxRun { maxRun = badRun maxDate = badDate } badRun = 0 } s := bufio.NewScanner(file) for s.Scan() { f := strings.Fields(s.Text()) if len(f) != fields { log.Fatal("unexpected format,", len(f), "fields.") } var accept int var sum float64 for i := 1; i < fields; i += 2 { flag, err := strconv.Atoi(f[i+1]) if err != nil { log.Fatal(err) } if flag <= 0 { if badRun++; badRun == 1 { badDate = f[0] } } else { endBadRun() value, err := strconv.ParseFloat(f[i], 64) if err != nil { log.Fatal(err) } sum += value accept++ } } fmt.Printf("Line: %s Reject %2d Accept: %2d Line_tot:%9.3f", f[0], readings-accept, accept, sum) if accept > 0 { fmt.Printf(" Line_avg:%8.3f\n", sum/float64(accept)) } else { fmt.Println() } fileSum += sum fileAccept += accept } if err := s.Err(); err != nil { log.Fatal(err) } endBadRun() fmt.Println("\nFile =", filename) fmt.Printf("Total = %.3f\n", fileSum) fmt.Println("Readings = ", fileAccept) if fileAccept > 0 { fmt.Printf("Average =  %.3f\n", fileSum/float64(fileAccept)) } if maxRun == 0 { fmt.Println("\nAll data valid.") } else { fmt.Printf("\nMax data gap = %d, beginning on line %s.\n", maxRun, maxDate) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> const char *string = "The quick brown fox jumped over the lazy dog's back"; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", result[i]); printf("\n"); return EXIT_SUCCESS; }
package main import ( "crypto/md5" "fmt" ) func main() { for _, p := range [][2]string{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, {"e38ca1d920c4b8b8d3946b2c72f01680", "The quick brown fox jumped over the lazy dog's back"}, } { validate(p[0], p[1]) } } var h = md5.New() func validate(check, s string) { h.Reset() h.Write([]byte(s)) sum := fmt.Sprintf("%x", h.Sum(nil)) if sum != check { fmt.Println("MD5 fail") fmt.Println(" for string,", s) fmt.Println(" expected: ", check) fmt.Println(" got: ", sum) } }
Convert this C block to Go, preserving its control flow and logic.
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Produce a language-to-language conversion: from C to Go, same semantics.
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Convert this C block to Go, preserving its control flow and logic.
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST"; strptime(d, "%B %d %Y %I:%M%p %Z", &ts); t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); return EXIT_SUCCESS; }
package main import ( "fmt" "time" ) const taskDate = "March 7 2009 7:30pm EST" const taskFormat = "January 2 2006 3:04pm MST" func main() { if etz, err := time.LoadLocation("US/Eastern"); err == nil { time.Local = etz } fmt.Println("Input: ", taskDate) t, err := time.Parse(taskFormat, taskDate) if err != nil { fmt.Println(err) return } t = t.Add(12 * time.Hour) fmt.Println("+12 hrs: ", t) if _, offset := t.Zone(); offset == 0 { fmt.Println("No time zone info.") return } atz, err := time.LoadLocation("US/Arizona") if err == nil { fmt.Println("+12 hrs in Arizona:", t.In(atz)) } }
Maintain the same structure and functionality when rewriting this code in Go.
>>>>>,----------[++++++++ ++[->+>+<<]>+>[-<<+>>]+++ +++++[-<------>]>>+>,---- ------<<+[->>>>>+<<<<<]>> ]>>>[<<<<[<<<[->>+<<[->+> [-]<<]]>[-<+>]>[-<<<.>>>> ->>>>>[>>>>>]<-<<<<[<<<<< ]+<]<<<<]>>>>>[>>>>>]<]
package main import ( "fmt" "log" "os" "strconv" "time" ) func main() { out := make(chan uint64) for _, a := range os.Args[1:] { i, err := strconv.ParseUint(a, 10, 64) if err != nil { log.Fatal(err) } go func(n uint64) { time.Sleep(time.Duration(n) * time.Millisecond) out <- n }(i) } for _ = range os.Args[1:] { fmt.Println(<-out) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int a[10][10], i, j; srand(time(NULL)); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) a[i][j] = rand() % 20 + 1; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf(" %d", a[i][j]); if (a[i][j] == 20) goto Done; } printf("\n"); } Done: printf("\n"); return 0; }
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) values := make([][]int, 10) for i := range values { values[i] = make([]int, 10) for j := range values[i] { values[i][j] = rand.Intn(20) + 1 } } outerLoop: for i, row := range values { fmt.Printf("%3d)", i) for _, value := range row { fmt.Printf(" %3d", value) if value == 20 { break outerLoop } } fmt.Printf("\n") } fmt.Printf("\n") }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
Please provide an equivalent version of this C code in Go.
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
package main import "fmt" func uniq(list []int) []int { unique_set := make(map[int]bool, len(list)) for _, x := range list { unique_set[x] = true } result := make([]int, 0, len(unique_set)) for x := range unique_set { result = append(result, x) } return result } func main() { fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) }