Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in VB as shown in this Java implementation.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
Change the following Java code into VB without altering its purpose.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
Translate the given Java code snippet into VB without altering its behavior.
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curByte = (int)(n & 0x7F); if (i != (numBytes - 1)) curByte |= 0x80; output[i] = (byte)curByte; n >>>= 7; } return output; } public static long decode(byte[] b) { long n = 0; for (int i = 0; i < b.length; i++) { int curByte = b[i] & 0xFF; n = (n << 7) | (curByte & 0x7F); if ((curByte & 0x80) == 0) break; } return n; } public static String byteArrayToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { if (i > 0) sb.append(", "); String s = Integer.toHexString(b[i] & 0xFF); if (s.length() < 2) s = "0" + s; sb.append(s); } return sb.toString(); } public static void main(String[] args) { long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; for (long n : testNumbers) { byte[] encoded = encode(n); long decoded = decode(encoded); System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); } } }
Module Module1 Function ToVlq(v As ULong) As ULong Dim array(8) As Byte Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray buffer.CopyTo(array, 0) Return BitConverter.ToUInt64(array, 0) End Function Function FromVlq(v As ULong) As ULong Dim collection = BitConverter.GetBytes(v).Reverse() Return FromVlqCollection(collection) End Function Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte) If v > Math.Pow(2, 56) Then Throw New OverflowException("Integer exceeds max value.") End If Dim index = 7 Dim significantBitReached = False Dim mask = &H7FUL << (index * 7) While index >= 0 Dim buffer = mask And v If buffer > 0 OrElse significantBitReached Then significantBitReached = True buffer >>= index * 7 If index > 0 Then buffer = buffer Or &H80 End If Yield buffer End If mask >>= 7 index -= 1 End While End Function Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong Dim v = 0UL Dim significantBitReached = False Using enumerator = vlq.GetEnumerator Dim index = 0 While enumerator.MoveNext Dim buffer = enumerator.Current If buffer > 0 OrElse significantBitReached Then significantBitReached = True v <<= 7 v = v Or (buffer And &H7FUL) End If index += 1 If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then Exit While End If End While End Using Return v End Function Sub Main() Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF} For Each original In values Console.WriteLine("Original: 0x{0:X}", original) REM collection Dim seq = ToVlqCollection(original) Console.WriteLine("Sequence: 0x{0}", seq.Select(Function(b) b.ToString("X2")).Aggregate(Function(a, b) String.Concat(a, b))) Dim decoded = FromVlqCollection(seq) Console.WriteLine("Decoded: 0x{0:X}", decoded) REM ints Dim encoded = ToVlq(original) Console.WriteLine("Encoded: 0x{0:X}", encoded) decoded = FromVlq(encoded) Console.WriteLine("Decoded: 0x{0:X}", decoded) Console.WriteLine() Next End Sub End Module
Convert the following code from Java to VB, ensuring the logic remains intact.
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("äàâáçñßæεбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
Sub Main() Const TESTSTRING As String = "alphaBETA" Debug.Print "initial = " _ & TESTSTRING Debug.Print "uppercase = " _ & UCase(TESTSTRING) Debug.Print "lowercase = " _ & LCase(TESTSTRING) Debug.Print "first letter capitalized = " _ & StrConv(TESTSTRING, vbProperCase) Debug.Print "length (in characters) = " _ & CStr(Len(TESTSTRING)) Debug.Print "length (in bytes) = " _ & CStr(LenB(TESTSTRING)) Debug.Print "reversed = " _ & StrReverse(TESTSTRING) Debug.Print "first position of letter A (case-sensitive) = " _ & InStr(1, TESTSTRING, "A", vbBinaryCompare) Debug.Print "first position of letter A (case-insensitive) = " _ & InStr(1, TESTSTRING, "A", vbTextCompare) Debug.Print "concatenated with & TESTSTRING & "123" End Sub
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.io.File; import java.util.*; import static java.lang.System.out; public class TextProcessing1 { public static void main(String[] args) throws Exception { Locale.setDefault(new Locale("en", "US")); Metrics metrics = new Metrics(); int dataGap = 0; String gapBeginDate = null; try (Scanner lines = new Scanner(new File("readings.txt"))) { while (lines.hasNextLine()) { double lineTotal = 0.0; int linePairs = 0; int lineInvalid = 0; String lineDate; try (Scanner line = new Scanner(lines.nextLine())) { lineDate = line.next(); while (line.hasNext()) { final double value = line.nextDouble(); if (line.nextInt() <= 0) { if (dataGap == 0) gapBeginDate = lineDate; dataGap++; lineInvalid++; continue; } lineTotal += value; linePairs++; metrics.addDataGap(dataGap, gapBeginDate, lineDate); dataGap = 0; } } metrics.addLine(lineTotal, linePairs); metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal); } metrics.report(); } } private static class Metrics { private List<String[]> gapDates; private int maxDataGap = -1; private double total; private int pairs; private int lineResultCount; void addLine(double tot, double prs) { total += tot; pairs += prs; } void addDataGap(int gap, String begin, String end) { if (gap > 0 && gap >= maxDataGap) { if (gap > maxDataGap) { maxDataGap = gap; gapDates = new ArrayList<>(); } gapDates.add(new String[]{begin, end}); } } void lineResult(String date, int invalid, int prs, double tot) { if (lineResultCount >= 3) return; out.printf("%10s out: %2d in: %2d tot: %10.3f avg: %10.3f%n", date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0); lineResultCount++; } void report() { out.printf("%ntotal = %10.3f%n", total); out.printf("readings = %6d%n", pairs); out.printf("average = %010.3f%n", total / pairs); out.printf("%nmaximum run(s) of %d invalid measurements: %n", maxDataGap); for (String[] dates : gapDates) out.printf("begins at %s and ends at %s%n", dates[0], dates[1]); } } }
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\data.txt",1) bad_readings_total = 0 good_readings_total = 0 data_gap = 0 start_date = "" end_date = "" tmp_datax_gap = 0 tmp_start_date = "" Do Until objFile.AtEndOfStream bad_readings = 0 good_readings = 0 line_total = 0 line = objFile.ReadLine token = Split(line,vbTab) n = 1 Do While n <= UBound(token) If n + 1 <= UBound(token) Then If CInt(token(n+1)) < 1 Then bad_readings = bad_readings + 1 bad_readings_total = bad_readings_total + 1 If tmp_start_date = "" Then tmp_start_date = token(0) End If tmp_data_gap = tmp_data_gap + 1 Else good_readings = good_readings + 1 line_total = line_total + CInt(token(n)) good_readings_total = good_readings_total + 1 If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then start_date = tmp_start_date end_date = token(0) data_gap = tmp_data_gap tmp_start_date = "" tmp_data_gap = 0 Else tmp_start_date = "" tmp_data_gap = 0 End If End If End If n = n + 2 Loop line_avg = line_total/good_readings WScript.StdOut.Write "Date: " & token(0) & vbTab &_ "Bad Reads: " & bad_readings & vbTab &_ "Good Reads: " & good_readings & vbTab &_ "Line Total: " & FormatNumber(line_total,3) & vbTab &_ "Line Avg: " & FormatNumber(line_avg,3) WScript.StdOut.WriteLine Loop WScript.StdOut.WriteLine WScript.StdOut.Write "Maximum run of " & data_gap &_ " consecutive bad readings from " & start_date & " to " &_ end_date & "." WScript.StdOut.WriteLine objFile.Close Set objFSO = Nothing
Port the provided Java code into VB while preserving the original functionality.
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digester { public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); } static String hexDigest(String str, String digestName) { try { MessageDigest md = MessageDigest.getInstance(digestName); byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8)); char[] hex = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4); hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f); } return new String(hex); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
Imports System.Security.Cryptography Imports System.Text Module MD5hash Sub Main(args As String()) Console.WriteLine(GetMD5("Visual Basic .Net")) End Sub Private Function GetMD5(plainText As String) As String Dim hash As String = "" Using hashObject As MD5 = MD5.Create() Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText)) Dim hashBuilder As New StringBuilder For i As Integer = 0 To ptBytes.Length - 1 hashBuilder.Append(ptBytes(i).ToString("X2")) Next hash = hashBuilder.ToString End Using Return hash End Function End Module
Translate this program into VB but keep the logic exactly as in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
Translate the given Java code snippet into VB without altering its behavior.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
Maintain the same structure and functionality when rewriting this code in VB.
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await(); Thread.sleep(num * 1000); System.out.println(num); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { int[] nums = new int[args.length]; for (int i = 0; i < args.length; i++) nums[i] = Integer.parseInt(args[i]); sleepSortAndPrint(nums); } }
Imports System.Threading Module Module1 Sub SleepSort(items As IEnumerable(Of Integer)) For Each item In items Task.Factory.StartNew(Sub() Thread.Sleep(1000 * item) Console.WriteLine(item) End Sub) Next End Sub Sub Main() SleepSort({1, 5, 2, 1, 8, 10, 3}) Console.ReadKey() End Sub End Module
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
Public Sub LoopsNested() Dim a(1 To 10, 1 To 10) As Integer Randomize For i = 1 To 10 For j = 1 To 10 a(i, j) = Int(20 * Rnd) + 1 Next j Next i For i = 1 To 10 For j = 1 To 10 If a(i, j) <> 20 Then Debug.Print a(i, j), Else i = 10 Exit For End If Next j Debug.Print Next i End Sub
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Dim total As Variant, prim As Variant, maxPeri As Variant Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant) Dim p As Variant p = CDec(s0) + CDec(s1) + CDec(s2) If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2 newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2 newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2 End If End Sub Public Sub Program_PythagoreanTriples() maxPeri = CDec(100) Do While maxPeri <= 10000000# prim = CDec(0) total = CDec(0) newTri 3, 4, 5 Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives." maxPeri = maxPeri * 10 Loop End Sub
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Dim total As Variant, prim As Variant, maxPeri As Variant Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant) Dim p As Variant p = CDec(s0) + CDec(s1) + CDec(s2) If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2 newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2 newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2 End If End Sub Public Sub Program_PythagoreanTriples() maxPeri = CDec(100) Do While maxPeri <= 10000000# prim = CDec(0) total = CDec(0) newTri 3, 4, 5 Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives." maxPeri = maxPeri * 10 Loop End Sub
Maintain the same structure and functionality when rewriting this code in VB.
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
Option Explicit Sub Main() Dim myArr() As Variant, i As Long myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235)) For i = LBound(myArr) To UBound(myArr) Debug.Print myArr(i) Next End Sub Private Function Remove_Duplicate(Arr As Variant) As Variant() Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long ReDim Temp(UBound(Arr)) For i = LBound(Arr) To UBound(Arr) On Error Resume Next myColl.Add CStr(Arr(i)), CStr(Arr(i)) If Err.Number > 0 Then On Error GoTo 0 Else Temp(cpt) = Arr(i) cpt = cpt + 1 End If Next i ReDim Preserve Temp(cpt - 1) Remove_Duplicate = Temp End Function
Preserve the algorithm and functionality while converting the code from Java to VB.
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
function looksay( n ) dim i dim accum dim res dim c res = vbnullstring do if n = vbnullstring then exit do accum = 0 c = left( n,1 ) do while left( n, 1 ) = c accum = accum + 1 n = mid(n,2) loop if accum > 0 then res = res & accum & c end if loop looksay = res end function
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
Private myStack() Private myStackHeight As Integer Public Function Push(aValue) myStackHeight = myStackHeight + 1 ReDim Preserve myStack(myStackHeight) myStack(myStackHeight) = aValue End Function Public Function Pop() If myStackHeight > 0 Then Pop = myStack(myStackHeight) myStackHeight = myStackHeight - 1 Else MsgBox "Pop: stack is empty!" End If End Function Public Function IsEmpty() As Boolean IsEmpty = (myStackHeight = 0) End Function Property Get Size() As Integer Size = myStackHeight End Property
Translate this program into VB but keep the logic exactly as in Java.
public class TotientFunction { public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max)); } } private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; } private static final int max = 10000000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
Private Function totient(ByVal n As Long) As Long Dim tot As Long: tot = n Dim i As Long: i = 2 Do While i * i <= n If n Mod i = 0 Then Do While True n = n \ i If n Mod i <> 0 Then Exit Do Loop tot = tot - tot \ i End If i = i + IIf(i = 2, 1, 2) Loop If n > 1 Then tot = tot - tot \ n End If totient = tot End Function Public Sub main() Debug.Print " n phi prime" Debug.Print " --------------" Dim count As Long Dim tot As Integer, n As Long For n = 1 To 25 tot = totient(n) prime = (n - 1 = tot) count = count - prime Debug.Print Format(n, "@@"); Format(tot, "@@@@@"); Format(prime, "@@@@@@@@") Next n Debug.Print Debug.Print "Number of primes up to 25 = "; Format(count, "@@@@") For n = 26 To 100000 count = count - (totient(n) = n - 1) Select Case n Case 100, 1000, 10000, 100000 Debug.Print "Number of primes up to"; n; String$(6 - Len(CStr(n)), " "); "="; Format(count, "@@@@@") Case Else End Select Next n End Sub
Generate an equivalent VB version of this Java code.
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
Sub C_S_If() Dim A$, B$ A = "Hello" B = "World" If A = B Then Debug.Print A & " = " & B If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B _ Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End Sub
Write a version of this Java function in VB with identical behavior.
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Fractran{ public static void main(String []args){ new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); } final int limit = 15; Vector<Integer> num = new Vector<>(); Vector<Integer> den = new Vector<>(); public Fractran(String prog, Integer val){ compile(prog); dump(); exec(2); } void compile(String prog){ Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); Matcher matcher = regexp.matcher(prog); while(matcher.find()){ num.add(Integer.parseInt(matcher.group(1))); den.add(Integer.parseInt(matcher.group(2))); matcher = regexp.matcher(matcher.group(3)); } } void exec(Integer val){ int n = 0; while(val != null && n<limit){ System.out.println(n+": "+val); val = step(val); n++; } } Integer step(int val){ int i=0; while(i<den.size() && val%den.get(i) != 0) i++; if(i<den.size()) return num.get(i)*val/den.get(i); return null; } void dump(){ for(int i=0; i<den.size(); i++) System.out.print(num.get(i)+"/"+den.get(i)+" "); System.out.println(); } }
Option Base 1 Public prime As Variant Public nf As New Collection Public df As New Collection Const halt = 20 Private Sub init() prime = [{2,3,5,7,11,13,17,19,23,29,31}] End Sub Private Function factor(f As Long) As Variant Dim result(10) As Integer Dim i As Integer: i = 1 Do While f > 1 Do While f Mod prime(i) = 0 f = f \ prime(i) result(i) = result(i) + 1 Loop i = i + 1 Loop factor = result End Function Private Function decrement(ByVal a As Variant, b As Variant) As Variant For i = LBound(a) To UBound(a) a(i) = a(i) - b(i) Next i decrement = a End Function Private Function increment(ByVal a As Variant, b As Variant) As Variant For i = LBound(a) To UBound(a) a(i) = a(i) + b(i) Next i increment = a End Function Private Function test(a As Variant, b As Variant) flag = True For i = LBound(a) To UBound(a) If a(i) < b(i) Then flag = False Exit For End If Next i test = flag End Function Private Function unfactor(x As Variant) As Long result = 1 For i = LBound(x) To UBound(x) result = result * prime(i) ^ x(i) Next i unfactor = result End Function Private Sub compile(program As String) program = Replace(program, " ", "") programlist = Split(program, ",") For Each instruction In programlist parts = Split(instruction, "/") nf.Add factor(Val(parts(0))) df.Add factor(Val(parts(1))) Next instruction End Sub Private Function run(x As Long) As Variant n = factor(x) counter = 0 Do While True For i = 1 To df.Count If test(n, df(i)) Then n = increment(decrement(n, df(i)), nf(i)) Exit For End If Next i Debug.Print unfactor(n); counter = counter + 1 If num = 31 Or counter >= halt Then Exit Do Loop Debug.Print run = n End Function Private Function steps(x As Variant) As Variant For i = 1 To df.Count If test(x, df(i)) Then x = increment(decrement(x, df(i)), nf(i)) Exit For End If Next i steps = x End Function Private Function is_power_of_2(x As Variant) As Boolean flag = True For i = LBound(x) + 1 To UBound(x) If x(i) > 0 Then flag = False Exit For End If Next i is_power_of_2 = flag End Function Private Function filter_primes(x As Long, max As Integer) As Long n = factor(x) i = 0: iterations = 0 Do While i < max If is_power_of_2(steps(n)) Then Debug.Print n(1); i = i + 1 End If iterations = iterations + 1 Loop Debug.Print filter_primes = iterations End Function Public Sub main() init compile ("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1") Debug.Print "First 20 results:" output = run(2) Debug.Print "First 30 primes:" Debug.Print "after"; filter_primes(2, 30); "iterations." End Sub
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{ put( "needspeeling", false ); put( "seedsremoved", false ); }}; public static void main( final String[] args ) { System.out.println( parseFile( args[ 0 ] ) ); } public static Map<String, Object> parseFile( final String fileName ) { final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS ); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( fileName ) ); for ( String line; null != ( line = reader.readLine() ); ) { parseLine( line, result ); } } catch ( final IOException x ) { throw new RuntimeException( "Oops: " + x, x ); } finally { if ( null != reader ) try { reader.close(); } catch ( final IOException x2 ) { System.err.println( "Could not close " + fileName + " - " + x2 ); } } return result; } private static void parseLine( final String line, final Map<String, Object> map ) { if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) return; final Matcher matcher = LINE_PATTERN.matcher( line ); if ( ! matcher.matches() ) { System.err.println( "Bad config line: " + line ); return; } final String key = matcher.group( 1 ).trim().toLowerCase(); final String value = matcher.group( 2 ).trim(); if ( "".equals( value ) ) { map.put( key, true ); } else if ( -1 == value.indexOf( ',' ) ) { map.put( key, value ); } else { final String[] values = value.split( "," ); for ( int i = 0; i < values.length; i++ ) { values[ i ] = values[ i ].trim(); } map.put( key, Arrays.asList( values ) ); } } }
type TSettings extends QObject FullName as string FavouriteFruit as string NeedSpelling as integer SeedsRemoved as integer OtherFamily as QStringlist Constructor FullName = "" FavouriteFruit = "" NeedSpelling = 0 SeedsRemoved = 0 OtherFamily.clear end constructor end type Dim Settings as TSettings dim ConfigList as QStringList dim x as integer dim StrLine as string dim StrPara as string dim StrData as string function Trim$(Expr as string) as string Result = Rtrim$(Ltrim$(Expr)) end function Sub ConfigOption(PData as string) dim x as integer for x = 1 to tally(PData, ",") +1 Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x)) next end sub Function ConfigBoolean(PData as string) as integer PData = Trim$(PData) Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0) end function sub ReadSettings ConfigList.LoadFromFile("Rosetta.cfg") ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ") for x = 0 to ConfigList.ItemCount -1 StrLine = Trim$(ConfigList.item(x)) StrPara = Trim$(field$(StrLine," ",1)) StrData = Trim$(lTrim$(StrLine - StrPara)) Select case UCase$(StrPara) case "FULLNAME" : Settings.FullName = StrData case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData) case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData) case "OTHERFAMILY" : Call ConfigOption(StrData) end select next end sub Call ReadSettings
Write a version of this Java function in VB with identical behavior.
import java.util.Comparator; import java.util.Arrays; public class Test { public static void main(String[] args) { String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; Arrays.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { int c = s2.length() - s1.length(); if (c == 0) c = s1.compareToIgnoreCase(s2); return c; } }); for (String s: strings) System.out.print(s + " "); } }
Imports System Module Sorting_Using_a_Custom_Comparator Function CustomComparator(ByVal x As String, ByVal y As String) As Integer Dim result As Integer result = y.Length - x.Length If result = 0 Then result = String.Compare(x, y, True) End If Return result End Function Sub Main() Dim strings As String() = {"test", "Zoom", "strings", "a"} Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator)) End Sub End Module
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; public class Rotate { private static class State { private final String text = "Hello World! "; private int startIndex = 0; private boolean rotateRight = true; } public static void main(String[] args) { State state = new State(); JLabel label = new JLabel(state.text); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { state.rotateRight = !state.rotateRight; } }); TimerTask task = new TimerTask() { public void run() { int delta = state.rotateRight ? 1 : -1; state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length(); label.setText(rotate(state.text, state.startIndex)); } }; Timer timer = new Timer(false); timer.schedule(task, 0, 500); JFrame rot = new JFrame(); rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); rot.add(label); rot.pack(); rot.setLocationRelativeTo(null); rot.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { timer.cancel(); } }); rot.setVisible(true); } private static String rotate(String text, int startIdx) { char[] rotated = new char[text.length()]; for (int i = 0; i < text.length(); i++) { rotated[i] = text.charAt((i + startIdx) % text.length()); } return String.valueOf(rotated); } }
VERSION 5.00 Begin VB.Form Form1 Begin VB.Timer Timer1 Interval = 250 End Begin VB.Label Label1 AutoSize = -1 Caption = "Hello World! " End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private goRight As Boolean Private Sub Label1_Click() goRight = Not goRight End Sub Private Sub Timer1_Timer() If goRight Then x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1) Else x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1) End If Label1.Caption = x End Sub
Port the provided Java code into VB while preserving the original functionality.
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; public class Rotate { private static class State { private final String text = "Hello World! "; private int startIndex = 0; private boolean rotateRight = true; } public static void main(String[] args) { State state = new State(); JLabel label = new JLabel(state.text); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { state.rotateRight = !state.rotateRight; } }); TimerTask task = new TimerTask() { public void run() { int delta = state.rotateRight ? 1 : -1; state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length(); label.setText(rotate(state.text, state.startIndex)); } }; Timer timer = new Timer(false); timer.schedule(task, 0, 500); JFrame rot = new JFrame(); rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); rot.add(label); rot.pack(); rot.setLocationRelativeTo(null); rot.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { timer.cancel(); } }); rot.setVisible(true); } private static String rotate(String text, int startIdx) { char[] rotated = new char[text.length()]; for (int i = 0; i < text.length(); i++) { rotated[i] = text.charAt((i + startIdx) % text.length()); } return String.valueOf(rotated); } }
VERSION 5.00 Begin VB.Form Form1 Begin VB.Timer Timer1 Interval = 250 End Begin VB.Label Label1 AutoSize = -1 Caption = "Hello World! " End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private goRight As Boolean Private Sub Label1_Click() goRight = Not goRight End Sub Private Sub Timer1_Timer() If goRight Then x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1) Else x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1) End If Label1.Caption = x End Sub
Please provide an equivalent version of this Java code in VB.
import java.util.Arrays; import java.util.List; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public interface PythagComp{ static void main(String... args){ System.out.println(run(20)); } static List<List<Integer>> run(int n){ return range(1, n).mapToObj( x -> range(x, n).mapToObj( y -> range(y, n).mapToObj( z -> new Integer[]{x, y, z} ) ) ) .flatMap(identity()) .flatMap(identity()) .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) .map(Arrays::asList) .collect(toList()) ; } }
Module ListComp Sub Main() Dim ts = From a In Enumerable.Range(1, 20) _ From b In Enumerable.Range(a, 21 - a) _ From c In Enumerable.Range(b, 21 - b) _ Where a * a + b * b = c * c _ Select New With { a, b, c } For Each t In ts System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c) Next End Sub End Module
Convert the following code from Java to VB, ensuring the logic remains intact.
public static void sort(int[] nums){ for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ int smallest = Integer.MAX_VALUE; int smallestAt = currentPlace+1; for(int check = currentPlace; check<nums.length;check++){ if(nums[check]<smallest){ smallestAt = check; smallest = nums[check]; } } int temp = nums[currentPlace]; nums[currentPlace] = nums[smallestAt]; nums[smallestAt] = temp; } }
Function Selection_Sort(s) arr = Split(s,",") For i = 0 To UBound(arr) For j = i To UBound(arr) temp = arr(i) If arr(j) < arr(i) Then arr(i) = arr(j) arr(j) = temp End If Next Next Selection_Sort = (Join(arr,",")) End Function WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" WScript.StdOut.WriteLine WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1") WScript.StdOut.WriteLine WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
Ensure the translated VB code behaves exactly like the original Java snippet.
public class ArrayCallback7 { interface IntConsumer { void run(int x); } interface IntToInt { int run(int x); } static void forEach(int[] arr, IntConsumer consumer) { for (int i : arr) { consumer.run(i); } } static void update(int[] arr, IntToInt mapper) { for (int i = 0; i < arr.length; i++) { arr[i] = mapper.run(arr[i]); } } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); update(numbers, new IntToInt() { @Override public int run(int x) { return x * x; } }); forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); } }
Option Explicit Sub Main() Dim arr, i arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next Debug.Print Join(arr, ", ") End Sub Private Function Fibonacci(N) As Variant If N <= 1 Then Fibonacci = N Else Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2) End If End Function
Produce a language-to-language conversion: from Java to VB, same semantics.
String dog = "Benjamin"; String Dog = "Samba"; String DOG = "Bernie"; @Inject Console console; console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
Public Sub case_sensitivity() Dim DOG As String DOG = "Benjamin" DOG = "Samba" DOG = "Bernie" Debug.Print "There is just one dog named " & DOG End Sub
Change the programming language of this snippet from Java to VB without modifying what it does.
for (int i = 10; i >= 0; i--) { System.out.println(i); }
For i = 10 To 0 Step -1 Debug.Print i Next i
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.io.*; public class Test { public static void main(String[] args) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) { bw.write("abc"); } } }
Option Explicit Const strName As String = "MyFileText.txt" Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _ "The reverse of Read entire file—for when you want to update or " & vbCrLf & _ "create a file which you would read in its entirety all at once." Sub Main() Dim Nb As Integer Nb = FreeFile Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb Print #1, Text Close #Nb End Sub
Preserve the algorithm and functionality while converting the code from Java to VB.
for (Integer i = 0; i < 5; i++) { String line = ''; for (Integer j = 0; j < i; j++) { line += '*'; } System.debug(line); } List<String> lines = new List<String> { '*', '**', '***', '****', '*****' }; for (String line : lines) { System.debug(line); }
Public OutConsole As Scripting.TextStream For i = 0 To 4 For j = 0 To i OutConsole.Write "*" Next j OutConsole.WriteLine Next i
Ensure the translated VB code behaves exactly like the original Java snippet.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
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 sub sier(lev,lgth) dim i if lev=1 then for i=1 to 3 x.fw lgth x.lt 2 next else sier lev-1,lgth\2 x.fw lgth\2 sier lev-1,lgth\2 x.bw lgth\2 x.lt 1 x.fw lgth\2 x.rt 1 sier lev-1,lgth\2 x.lt 1 x.bw lgth\2 x.rt 1 end if end sub dim x set x=new turtle x.iangle=60 x.orient=0 x.incr=10 x.x=100:x.y=100 sier 7,64 set x=nothing
Transform the following Java implementation into VB, maintaining the same output and logic.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
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 sub sier(lev,lgth) dim i if lev=1 then for i=1 to 3 x.fw lgth x.lt 2 next else sier lev-1,lgth\2 x.fw lgth\2 sier lev-1,lgth\2 x.bw lgth\2 x.lt 1 x.fw lgth\2 x.rt 1 sier lev-1,lgth\2 x.lt 1 x.bw lgth\2 x.rt 1 end if end sub dim x set x=new turtle x.iangle=60 x.orient=0 x.incr=10 x.x=100:x.y=100 sier 7,64 set x=nothing
Convert this Java block to VB, preserving its control flow and logic.
public class NonContinuousSubsequences { public static void main(String args[]) { seqR("1234", "", 0, 0); } private static void seqR(String s, String c, int i, int added) { if (i == s.length()) { if (c.trim().length() > added) System.out.println(c); } else { seqR(s, c + s.charAt(i), i + 1, added + 1); seqR(s, c + ' ', i + 1, added); } } }
Function noncontsubseq(l) Dim i, j, g, n, r, s, w, m Dim a, b, c n = Ubound(l) For s = 0 To n-2 For g = s+1 To n-1 a = "[" For i = s To g-1 a = a & l(i) & ", " Next For w = 1 To n-g r = n+1-g-w For i = 1 To 2^r-1 Step 2 b = a For j = 0 To r-1 If i And 2^j Then b=b & l(g+w+j) & ", " Next c = (Left(b, Len(b)-1)) WScript.Echo Left(c, Len(c)-1) & "]" m = m+1 Next Next Next Next noncontsubseq = m End Function list = Array("1", "2", "3", "4") WScript.Echo "List: [" & Join(list, ", ") & "]" nn = noncontsubseq(list) WScript.Echo nn & " non-continuous subsequences"
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
Function IsPrime(x As Long) As Boolean Dim i As Long If x Mod 2 = 0 Then Exit Function Else For i = 3 To Int(Sqr(x)) Step 2 If x Mod i = 0 Then Exit Function Next i End If IsPrime = True End Function Function TwinPrimePairs(max As Long) As Long Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long p2 = True For i = 5 To max Step 2 p1 = p2 p2 = IsPrime(i) If p1 And p2 Then count = count + 1 Next i TwinPrimePairs = count End Function Sub Test(x As Long) Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x)) End Sub Sub Main() Test 10 Test 100 Test 1000 Test 10000 Test 100000 Test 1000000 Test 10000000 End Sub
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
Function IsPrime(x As Long) As Boolean Dim i As Long If x Mod 2 = 0 Then Exit Function Else For i = 3 To Int(Sqr(x)) Step 2 If x Mod i = 0 Then Exit Function Next i End If IsPrime = True End Function Function TwinPrimePairs(max As Long) As Long Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long p2 = True For i = 5 To max Step 2 p1 = p2 p2 = IsPrime(i) If p1 And p2 Then count = count + 1 Next i TwinPrimePairs = count End Function Sub Test(x As Long) Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x)) End Sub Sub Main() Test 10 Test 100 Test 1000 Test 10000 Test 100000 Test 1000000 Test 10000000 End Sub
Maintain the same structure and functionality when rewriting this code in VB.
import java.util.Locale; public class Test { public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); } public static void unity(int n) { System.out.printf("%n%d: ", n); for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) { double real = Math.cos(angle); if (Math.abs(real) < 1.0E-3) real = 0.0; double imag = Math.sin(angle); if (Math.abs(imag) < 1.0E-3) imag = 0.0; System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
Public Sub roots_of_unity() For n = 2 To 9 Debug.Print n; "th roots of 1:" For r00t = 0 To n - 1 Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _ Sin(2 * WorksheetFunction.Pi() * r00t / n)) Next r00t Debug.Print Next n End Sub
Produce a language-to-language conversion: from Java to VB, same semantics.
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
Imports System Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D Structure bd Public hi, lo As Decimal End Structure Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo), String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo)) If Not comma Then Return r Dim rc As String = "" For i As Integer = r.Length - 3 To 0 Step -3 rc = "," & r.Substring(i, 3) & rc : Next toStr = r.Substring(0, r.Length Mod 3) & rc toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0)) End Function Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _ Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas End Function Sub Main(ByVal args As String()) For p As UInteger = 64 To 95 - 1 Step 30 Dim y As bd, x As bd : a = Pow_dec(2D, p) WriteLine("The square of (2^{0}): {1,38:n0}", p, a) x.hi = Math.Floor(a / hm) : x.lo = a Mod hm Dim BS As BI = BI.Pow(CType(a, BI), 2) y.lo = x.lo * x.lo : y.hi = x.hi * x.hi a = x.hi * x.lo * 2D y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm While y.lo > mx : y.lo -= mx : y.hi += 1 : End While WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf, toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to")) Next End Sub End Module
Transform the following Java implementation into VB, maintaining the same output and logic.
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
Imports System Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D Structure bd Public hi, lo As Decimal End Structure Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo), String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo)) If Not comma Then Return r Dim rc As String = "" For i As Integer = r.Length - 3 To 0 Step -3 rc = "," & r.Substring(i, 3) & rc : Next toStr = r.Substring(0, r.Length Mod 3) & rc toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0)) End Function Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _ Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas End Function Sub Main(ByVal args As String()) For p As UInteger = 64 To 95 - 1 Step 30 Dim y As bd, x As bd : a = Pow_dec(2D, p) WriteLine("The square of (2^{0}): {1,38:n0}", p, a) x.hi = Math.Floor(a / hm) : x.lo = a Mod hm Dim BS As BI = BI.Pow(CType(a, BI), 2) y.lo = x.lo * x.lo : y.hi = x.hi * x.hi a = x.hi * x.lo * 2D y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm While y.lo > mx : y.lo -= mx : y.hi += 1 : End While WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf, toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to")) Next End Sub End Module
Translate the given Java code snippet into VB without altering its behavior.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PellsEquation { public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } } private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } } private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b; while ( true ) { int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; } private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; } }
Imports System.Numerics Module Module1 Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer) Dim t As BigInteger = a : a = b : b = b * c + t End Sub Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger) Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1, e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1 While True y = r * z - y : z = (n - y * y) / z : r = (x + y) / z Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x) If a * a - n * b * b = 1 Then Exit Sub End While End Sub Sub Main() Dim x As BigInteger, y As BigInteger For Each n As Integer In {61, 109, 181, 277} SolvePell(n, x, y) Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y) Next End Sub End Module
Produce a functionally identical VB code for the snippet given in Java.
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); } public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
Option Explicit Sub Main_Bulls_and_cows() Dim strNumber As String, strInput As String, strMsg As String, strTemp As String Dim boolEnd As Boolean Dim lngCpt As Long Dim i As Byte, bytCow As Byte, bytBull As Byte Const NUMBER_OF_DIGITS As Byte = 4 Const MAX_LOOPS As Byte = 25 strNumber = Create_Number(NUMBER_OF_DIGITS) Do bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1 If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do strInput = AskToUser(NUMBER_OF_DIGITS) If strInput = "Exit Game" Then strMsg = "User abort": Exit Do For i = 1 To Len(strNumber) If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then bytBull = bytBull + 1 ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then bytCow = bytCow + 1 End If Next i If bytBull = Len(strNumber) Then boolEnd = True: strMsg = "You win in " & lngCpt & " loops!" Else strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows." MsgBox strTemp End If Loop While Not boolEnd MsgBox strMsg End Sub Function Create_Number(NbDigits As Byte) As String Dim myColl As New Collection Dim strTemp As String Dim bytAlea As Byte Randomize Do bytAlea = Int((Rnd * 9) + 1) On Error Resume Next myColl.Add CStr(bytAlea), CStr(bytAlea) If Err <> 0 Then On Error GoTo 0 Else strTemp = strTemp & CStr(bytAlea) End If Loop While Len(strTemp) < NbDigits Create_Number = strTemp End Function Function AskToUser(NbDigits As Byte) As String Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte Do While Not boolGood strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number") If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do If strIn <> "" Then If Len(strIn) = NbDigits Then NbDiff = 0 For i = 1 To Len(strIn) If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then NbDiff = 1 Exit For End If Next i If NbDiff = 0 Then boolGood = True End If End If Loop AskToUser = strIn End Function
Translate the given Java code snippet into VB without altering its behavior.
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sortable.Shuffle() Dim swapped As Boolean Do Dim index, bound As Integer bound = sortable.Ubound While index < bound If sortable(index) > sortable(index + 1) Then Dim s As Integer = sortable(index) sortable.Remove(index) sortable.Insert(index + 1, s) swapped = True End If index = index + 1 Wend Loop Until Not swapped
Convert this Java snippet to VB and keep its semantics consistent.
import java.io.*; public class FileIODemo { public static void main(String[] args) { try { FileInputStream in = new FileInputStream("input.txt"); FileOutputStream out = new FileOutputStream("ouput.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } }
Sub WriteToFile(input As FolderItem, output As FolderItem) Dim tis As TextInputStream Dim tos As TextOutputStream tis = tis.Open(input) tos = tos.Create(output) While Not tis.EOF tos.WriteLine(tis.ReadLine) Wend tis.Close tos.Close End Sub
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.util.Scanner; public class IntegerArithmetic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int sum = a + b; int difference = a - b; int product = a * b; int division = a / b; int remainder = a % b; System.out.println("a + b = " + sum); System.out.println("a - b = " + difference); System.out.println("a * b = " + product); System.out.println("quotient of a / b = " + division); System.out.println("remainder of a / b = " + remainder); } }
START: INPUT "Enter two integers (a,b):"; a!, b! IF a = 0 THEN END IF b = 0 THEN PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder." GOTO START END IF PRINT PRINT " Sum = "; a + b PRINT " Difference = "; a - b PRINT " Product = "; a * b PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0." PRINT " Remainder = "; a MOD b, , "* Sign matches first operand." PRINT " Exponentiation = "; a ^ b PRINT INPUT "Again? (y/N)"; a$ IF UCASE$(a$) = "Y" THEN CLS: GOTO START CLS END
Translate the given Java code snippet into VB without altering its behavior.
import java.util.Arrays; public class Transpose{ public static void main(String[] args){ double[][] m = {{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}, {5, 25, 125, 625}}; double[][] ans = new double[m[0].length][m.length]; for(int rows = 0; rows < m.length; rows++){ for(int cols = 0; cols < m[0].length; cols++){ ans[cols][rows] = m[rows][cols]; } } for(double[] i:ans){ System.out.println(Arrays.toString(i)); } } }
Function transpose(m As Variant) As Variant transpose = WorksheetFunction.transpose(m) End Function
Produce a language-to-language conversion: from Java to VB, same semantics.
module test { @Inject Console console; static Boolean show(String name, Boolean value) { console.print($"{name}()={value}"); return value; } void run() { val a = show("a", _); val b = show("b", _); for (Boolean v1 : False..True) { for (Boolean v2 : False..True) { console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}"); console.print(); console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}"); console.print(); } } } }
Private Function a(i As Variant) As Boolean Debug.Print "a: "; i = 1, a = i End Function Private Function b(j As Variant) As Boolean Debug.Print "b: "; j = 1; b = j End Function Public Sub short_circuit() Dim x As Boolean, y As Boolean Debug.Print "=====AND=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print "======OR=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If Not a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print End Sub
Write the same algorithm in VB as shown in this Java implementation.
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
Port the following code from Java to VB with equivalent syntax and logic.
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
Translate the given Java code snippet into VB without altering its behavior.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.util.Arrays; import java.util.Random; import javax.swing.*; public class ImageNoise { int framecount = 0; int fps = 0; BufferedImage image; Kernel kernel; ConvolveOp cop; JFrame frame = new JFrame("Java Image Noise"); JPanel panel = new JPanel() { private int show_fps = 0; private MouseAdapter ma = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { show_fps = (show_fps + 1) % 3; } }; {addMouseListener(ma);} @Override public Dimension getPreferredSize() { return new Dimension(320, 240); } @Override @SuppressWarnings("fallthrough") public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; drawNoise(); g.drawImage(image, 0, 0, null); switch (show_fps) { case 0: int xblur = getWidth() - 130, yblur = getHeight() - 32; BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32); BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(), BufferedImage.TYPE_BYTE_GRAY); cop.filter(bc, bs); g.drawImage(bs, xblur, yblur , null); case 1: g.setColor(Color.RED); g.setFont(new Font("Monospaced", Font.BOLD, 20)); g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10); } framecount++; } }; Timer repainter = new Timer(1, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.repaint(); } }); Timer framerateChecker = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fps = framecount; framecount = 0; } }); public ImageNoise() { float[] vals = new float[121]; Arrays.fill(vals, 1/121f); kernel = new Kernel(11, 11, vals); cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); repainter.start(); framerateChecker.start(); } void drawNoise() { int w = panel.getWidth(), h = panel.getHeight(); if (null == image || image.getWidth() != w || image.getHeight() != h) { image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); } Random rand = new Random(); int[] data = new int[w * h]; for (int x = 0; x < w * h / 32; x++) { int r = rand.nextInt(); for (int i = 0; i < 32; i++) { data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE; r >>>= 1; } } image.getRaster().setPixels(0, 0, w, h, data); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ImageNoise i = new ImageNoise(); } }); } }
Imports System.Drawing.Imaging Public Class frmSnowExercise Dim bRunning As Boolean = True Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _ Or ControlStyles.OptimizedDoubleBuffer, True) UpdateStyles() FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle MaximizeBox = False Width = 320 + Size.Width - ClientSize.Width Height = 240 + Size.Height - ClientSize.Height Show() Activate() Application.DoEvents() RenderLoop() Close() End Sub Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False End Sub Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _ System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing e.Cancel = bRunning bRunning = False End Sub Private Sub RenderLoop() Const cfPadding As Single = 5.0F Dim b As New Bitmap(ClientSize.Width, ClientSize.Width, PixelFormat.Format32bppArgb) Dim g As Graphics = Graphics.FromImage(b) Dim r As New Random(Now.Millisecond) Dim oBMPData As BitmapData = Nothing Dim oPixels() As Integer = Nothing Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb} Dim oStopwatch As New Stopwatch Dim fElapsed As Single = 0.0F Dim iLoops As Integer = 0 Dim sFPS As String = "0.0 FPS" Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font) Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) g.Clear(Color.Black) oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb) Array.Resize(oPixels, b.Width * b.Height) Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oPixels, 0, oPixels.Length) b.UnlockBits(oBMPData) Do fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F oStopwatch.Reset() : oStopwatch.Start() iLoops += 1 If fElapsed >= 1.0F Then sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS" oFPSSize = g.MeasureString(sFPS, Font) oFPSBG = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) fElapsed -= 1.0F iLoops = 0 End If For i As Integer = 0 To oPixels.GetUpperBound(0) oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length)) Next oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb) Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0, oPixels.Length) b.UnlockBits(oBMPData) g.FillRectangle(Brushes.Black, oFPSBG) g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top) BackgroundImage = b Invalidate(ClientRectangle) Application.DoEvents() Loop While bRunning End Sub End Class
Produce a language-to-language conversion: from Java to VB, same semantics.
public static boolean perf(int n){ int sum= 0; for(int i= 1;i < n;i++){ if(n % i == 0){ sum+= i; } } return sum == n; }
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
Maintain the same structure and functionality when rewriting this code in VB.
public class BeadSort { public static void main(String[] args) { BeadSort now=new BeadSort(); int[] arr=new int[(int)(Math.random()*11)+5]; for(int i=0;i<arr.length;i++) arr[i]=(int)(Math.random()*10); System.out.print("Unsorted: "); now.display1D(arr); int[] sort=now.beadSort(arr); System.out.print("Sorted: "); now.display1D(sort); } int[] beadSort(int[] arr) { int max=a[0]; for(int i=1;i<arr.length;i++) if(arr[i]>max) max=arr[i]; char[][] grid=new char[arr.length][max]; int[] levelcount=new int[max]; for(int i=0;i<max;i++) { levelcount[i]=0; for(int j=0;j<arr.length;j++) grid[j][i]='_'; } for(int i=0;i<arr.length;i++) { int num=arr[i]; for(int j=0;num>0;j++) { grid[levelcount[j]++][j]='*'; num--; } } System.out.println(); display2D(grid); int[] sorted=new int[arr.length]; for(int i=0;i<arr.length;i++) { int putt=0; for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++) putt++; sorted[i]=putt; } return sorted; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display1D(char[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display2D(char[][] arr) { for(int i=0;i<arr.length;i++) display1D(arr[i]); System.out.println(); } }
Option Base 1 Private Function sq_add(arr As Variant, x As Double) As Variant Dim res() As Variant ReDim res(UBound(arr)) For i = 1 To UBound(arr) res(i) = arr(i) + x Next i sq_add = res End Function Private Function beadsort(ByVal a As Variant) As Variant Dim poles() As Variant ReDim poles(WorksheetFunction.Max(a)) For i = 1 To UBound(a) For j = 1 To a(i) poles(j) = poles(j) + 1 Next j Next i For j = 1 To UBound(a) a(j) = 0 Next j For i = 1 To UBound(poles) For j = 1 To poles(i) a(j) = a(j) + 1 Next j Next i beadsort = a End Function Public Sub main() Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ") End Sub
Write the same code in VB as shown below in Java.
import java.math.BigInteger; class IntegerPower { public static void main(String[] args) { BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact()); String str = power.toString(); int len = str.length(); System.out.printf("5**4**3**2 = %s...%s and has %d digits%n", str.substring(0, 20), str.substring(len - 20), len); } }
Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim Implems() As String = {"Built-In", "Recursive", "Iterative"}, powers() As Integer = {5, 4, 3, 2} Function intPowR(val As BI, exp As BI) As BI If exp = 0 Then Return 1 Dim ne As BI, vs As BI = val * val If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val End Function Function intPowI(val As BI, exp As BI) As BI intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val val *= val : exp >>= 1 : End While End Function Sub DoOne(title As String, p() As Integer) Dim st As DateTime = DateTime.Now, res As BI, resStr As String Select Case (Array.IndexOf(Implems, title)) Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3)))))) Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3)))) Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3)))) End Select : resStr = res.ToString() Dim et As TimeSpan = DateTime.Now - st Debug.Assert(resStr.Length = 183231) Debug.Assert(resStr.StartsWith("62060698786608744707")) Debug.Assert(resStr.EndsWith("92256259918212890625")) WriteLine("n = {0}", String.Join("^", powers)) WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20)) WriteLine("n digits = {0}", resStr.Length) WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds) End Sub Sub Main() For Each itm As String in Implems : DoOne(itm, powers) : Next If Debugger.IsAttached Then Console.ReadKey() End Sub End Module
Translate the given Java code snippet into VB without altering its behavior.
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") light = Array(30, 30, -50) Sub Normalize(v) length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length End Sub Function Dot(x, y) d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) If d < 0 Then Dot = -d Else Dot = 0 End If End Function Function Ceil(x) Ceil = Int(x) If Ceil <> x Then Ceil = Ceil + 1 End if End Function Sub DrawSphere(R, k, ambient) Dim i, j, intensity, inten, b, x, y Dim vec(3) For i = Int(-R) to Ceil(R) x = i + 0.5 line = "" For j = Int(-2*R) to Ceil(2*R) y = j / 2 + 0.5 If x * x + y * y <= R*R Then vec(0) = x vec(1) = y vec(2) = Sqr(R * R - x * x - y * y) Normalize vec b = dot(light, vec)^k + ambient intensity = Int((1 - b) * UBound(shades)) If intensity < 0 Then intensity = 0 End If If intensity >= UBound(shades) Then intensity = UBound(shades) End If line = line & shades(intensity) Else line = line & " " End If Next WScript.StdOut.WriteLine line Next End Sub Normalize light DrawSphere 20, 4, 0.1 DrawSphere 10,2,0.4
Change the programming language of this snippet from Java to VB without modifying what it does.
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") light = Array(30, 30, -50) Sub Normalize(v) length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length End Sub Function Dot(x, y) d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) If d < 0 Then Dot = -d Else Dot = 0 End If End Function Function Ceil(x) Ceil = Int(x) If Ceil <> x Then Ceil = Ceil + 1 End if End Function Sub DrawSphere(R, k, ambient) Dim i, j, intensity, inten, b, x, y Dim vec(3) For i = Int(-R) to Ceil(R) x = i + 0.5 line = "" For j = Int(-2*R) to Ceil(2*R) y = j / 2 + 0.5 If x * x + y * y <= R*R Then vec(0) = x vec(1) = y vec(2) = Sqr(R * R - x * x - y * y) Normalize vec b = dot(light, vec)^k + ambient intensity = Int((1 - b) * UBound(shades)) If intensity < 0 Then intensity = 0 End If If intensity >= UBound(shades) Then intensity = UBound(shades) End If line = line & shades(intensity) Else line = line & " " End If Next WScript.StdOut.WriteLine line Next End Sub Normalize light DrawSphere 20, 4, 0.1 DrawSphere 10,2,0.4
Write the same algorithm in VB as shown in this Java implementation.
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
Port the provided Java code into VB while preserving the original functionality.
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
import java.util.Random; Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
Public Sub LoopsBreak() Dim value As Integer Randomize Do While True value = Int(20 * Rnd) Debug.Print value If value = 10 Then Exit Do Debug.Print Int(20 * Rnd) Loop End Sub
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.util.Random; Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
Public Sub LoopsBreak() Dim value As Integer Randomize Do While True value = Int(20 * Rnd) Debug.Print value If value = 10 Then Exit Do Debug.Print Int(20 * Rnd) Loop End Sub
Write a version of this Java function in VB with identical behavior.
public class WaterBetweenTowers { public static void main(String[] args) { int i = 1; int[][] tba = new int[][]{ new int[]{1, 5, 3, 7, 2}, new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, new int[]{5, 5, 5, 5}, new int[]{5, 6, 7, 8}, new int[]{8, 7, 7, 6}, new int[]{6, 7, 10, 7, 6} }; for (int[] tea : tba) { int rht, wu = 0, bof; do { for (rht = tea.length - 1; rht >= 0; rht--) { if (tea[rht] > 0) { break; } } if (rht < 0) { break; } bof = 0; for (int col = 0; col <= rht; col++) { if (tea[col] > 0) { tea[col]--; bof += 1; } else if (bof > 0) { wu++; } } if (bof < 2) { break; } } while (true); System.out.printf("Block %d", i++); if (wu == 0) { System.out.print(" does not hold any"); } else { System.out.printf(" holds %d", wu); } System.out.println(" water units."); } } }
Module Module1 Sub Main(Args() As String) Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 Dim wta As Integer()() = { New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8}, New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}} Dim blk As String, lf As String = vbLf, tb = "██", wr = "≈≈", mt = " " For i As Integer = 0 To wta.Length - 1 Dim bpf As Integer blk = "" Do bpf = 0 : Dim floor As String = "" For j As Integer = 0 To wta(i).Length - 1 If wta(i)(j) > 0 Then floor &= tb : wta(i)(j) -= 1 : bpf += 1 Else floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt) End If Next If bpf > 0 Then blk = floor & lf & blk Loop Until bpf = 0 While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While If shoTow Then Console.Write("{0}{1}", lf, blk) Console.Write("Block {0} retains {1,2} water units.{2}", i + 1, (blk.Length - blk.Replace(wr, "").Length) \ 2, lf) Next End Sub End Module
Generate an equivalent VB version of this Java code.
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long p2 = p * p; if (p2 > limit) break; for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true; for (;;) { p += 2; if (!c[(int)p]) break; } } for (long i = 3; i <= limit; i += 2) { if (!c[(int)i]) primes.add(i); } return primes; } private static List<Long> squareFree(long from, long to) { long limit = (long)Math.sqrt((double)to); List<Long> primes = sieve(limit); List<Long> results = new ArrayList<Long>(); outer: for (long i = from; i <= to; i++) { for (long p : primes) { long p2 = p * p; if (p2 > i) break; if (i % p2 == 0) continue outer; } results.add(i); } return results; } private final static long TRILLION = 1000000000000L; public static void main(String[] args) { System.out.println("Square-free integers from 1 to 145:"); List<Long> sf = squareFree(1, 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 20 == 0) { System.out.println(); } System.out.printf("%4d", sf.get(i)); } System.out.print("\n\nSquare-free integers"); System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145); sf = squareFree(TRILLION, TRILLION + 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 5 == 0) System.out.println(); System.out.printf("%14d", sf.get(i)); } System.out.println("\n\nNumber of square-free integers:\n"); long[] tos = {100, 1000, 10000, 100000, 1000000}; for (long to : tos) { System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size()); } } }
Module Module1 Function Sieve(limit As Long) As List(Of Long) Dim primes As New List(Of Long) From {2} Dim c(limit + 1) As Boolean Dim p = 3L While True Dim p2 = p * p If p2 > limit Then Exit While End If For i = p2 To limit Step 2 * p c(i) = True Next While True p += 2 If Not c(p) Then Exit While End If End While End While For i = 3 To limit Step 2 If Not c(i) Then primes.Add(i) End If Next Return primes End Function Function SquareFree(from As Long, to_ As Long) As List(Of Long) Dim limit = CType(Math.Sqrt(to_), Long) Dim primes = Sieve(limit) Dim results As New List(Of Long) Dim i = from While i <= to_ For Each p In primes Dim p2 = p * p If p2 > i Then Exit For End If If (i Mod p2) = 0 Then i += 1 Continue While End If Next results.Add(i) i += 1 End While Return results End Function ReadOnly TRILLION As Long = 1_000_000_000_000 Sub Main() Console.WriteLine("Square-free integers from 1 to 145:") Dim sf = SquareFree(1, 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 20) = 0 Then Console.WriteLine() End If Console.Write("{0,4}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145) sf = SquareFree(TRILLION, TRILLION + 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 5) = 0 Then Console.WriteLine() End If Console.Write("{0,14}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Number of square-free integers:") For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000} Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count) Next End Sub End Module
Convert this Java snippet to VB and keep its semantics consistent.
public class JaroDistance { public static double jaro(String s, String t) { int s_len = s.length(); int t_len = t.length(); if (s_len == 0 && t_len == 0) return 1; int match_distance = Integer.max(s_len, t_len) / 2 - 1; boolean[] s_matches = new boolean[s_len]; boolean[] t_matches = new boolean[t_len]; int matches = 0; int transpositions = 0; for (int i = 0; i < s_len; i++) { int start = Integer.max(0, i-match_distance); int end = Integer.min(i+match_distance+1, t_len); for (int j = start; j < end; j++) { if (t_matches[j]) continue; if (s.charAt(i) != t.charAt(j)) continue; s_matches[i] = true; t_matches[j] = true; matches++; break; } } if (matches == 0) return 0; int k = 0; for (int i = 0; i < s_len; i++) { if (!s_matches[i]) continue; while (!t_matches[k]) k++; if (s.charAt(i) != t.charAt(k)) transpositions++; k++; } return (((double)matches / s_len) + ((double)matches / t_len) + (((double)matches - transpositions/2.0) / matches)) / 3.0; } public static void main(String[] args) { System.out.println(jaro( "MARTHA", "MARHTA")); System.out.println(jaro( "DIXON", "DICKSONX")); System.out.println(jaro("JELLYFISH", "SMELLYFISH")); } }
Option Explicit Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double Dim dummyChar, match1, match2 As String Dim i, f, t, j, m, l, s1, s2, limit As Integer i = 1 Do dummyChar = Chr(i) i = i + 1 Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0 s1 = Len(text1) s2 = Len(text2) limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1) match1 = String(s1, dummyChar) match2 = String(s2, dummyChar) For l = 1 To WorksheetFunction.Min(4, s1, s2) If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For Next l l = l - 1 For i = 1 To s1 f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2) t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2) j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare) If j > 0 Then m = m + 1 text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j) match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1) match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j) End If Next i match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare) match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare) t = 0 For i = 1 To m If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1 Next i JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3 JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p) End Function
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } } private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) { sum += n % base; n /= base; } sequence.add(sum % base); } return sequence; } }
Module Module1 Function Turn(base As Integer, n As Integer) As Integer Dim sum = 0 While n <> 0 Dim re = n Mod base n \= base sum += re End While Return sum Mod base End Function Sub Fairshare(base As Integer, count As Integer) Console.Write("Base {0,2}:", base) For i = 1 To count Dim t = Turn(base, i - 1) Console.Write(" {0,2}", t) Next Console.WriteLine() End Sub Sub TurnCount(base As Integer, count As Integer) Dim cnt(base) As Integer For i = 1 To base cnt(i - 1) = 0 Next For i = 1 To count Dim t = Turn(base, i - 1) cnt(t) += 1 Next Dim minTurn = Integer.MaxValue Dim maxTurn = Integer.MinValue Dim portion = 0 For i = 1 To base Dim num = cnt(i - 1) If num > 0 Then portion += 1 End If If num < minTurn Then minTurn = num End If If num > maxTurn Then maxTurn = num End If Next Console.Write(" With {0} people: ", base) If 0 = minTurn Then Console.WriteLine("Only {0} have a turn", portion) ElseIf minTurn = maxTurn Then Console.WriteLine(minTurn) Else Console.WriteLine("{0} or {1}", minTurn, maxTurn) End If End Sub Sub Main() Fairshare(2, 25) Fairshare(3, 25) Fairshare(5, 25) Fairshare(11, 25) Console.WriteLine("How many times does each get a turn in 50000 iterations?") TurnCount(191, 50000) TurnCount(1377, 50000) TurnCount(49999, 50000) TurnCount(50000, 50000) TurnCount(50001, 50000) End Sub End Module
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } } private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) { sum += n % base; n /= base; } sequence.add(sum % base); } return sequence; } }
Module Module1 Function Turn(base As Integer, n As Integer) As Integer Dim sum = 0 While n <> 0 Dim re = n Mod base n \= base sum += re End While Return sum Mod base End Function Sub Fairshare(base As Integer, count As Integer) Console.Write("Base {0,2}:", base) For i = 1 To count Dim t = Turn(base, i - 1) Console.Write(" {0,2}", t) Next Console.WriteLine() End Sub Sub TurnCount(base As Integer, count As Integer) Dim cnt(base) As Integer For i = 1 To base cnt(i - 1) = 0 Next For i = 1 To count Dim t = Turn(base, i - 1) cnt(t) += 1 Next Dim minTurn = Integer.MaxValue Dim maxTurn = Integer.MinValue Dim portion = 0 For i = 1 To base Dim num = cnt(i - 1) If num > 0 Then portion += 1 End If If num < minTurn Then minTurn = num End If If num > maxTurn Then maxTurn = num End If Next Console.Write(" With {0} people: ", base) If 0 = minTurn Then Console.WriteLine("Only {0} have a turn", portion) ElseIf minTurn = maxTurn Then Console.WriteLine(minTurn) Else Console.WriteLine("{0} or {1}", minTurn, maxTurn) End If End Sub Sub Main() Fairshare(2, 25) Fairshare(3, 25) Fairshare(5, 25) Fairshare(11, 25) Console.WriteLine("How many times does each get a turn in 50000 iterations?") TurnCount(191, 50000) TurnCount(1377, 50000) TurnCount(49999, 50000) TurnCount(50000, 50000) TurnCount(50001, 50000) End Sub End Module
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) sb.append(ops.charAt(s.pop())).append(' '); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); } else { sb.append(token).append(' '); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())).append(' '); return sb.toString(); } }
Module Module1 Class SymbolType Public ReadOnly symbol As String Public ReadOnly precedence As Integer Public ReadOnly rightAssociative As Boolean Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean) Me.symbol = symbol Me.precedence = precedence Me.rightAssociative = rightAssociative End Sub End Class ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From { {"^", New SymbolType("^", 4, True)}, {"*", New SymbolType("*", 3, False)}, {"/", New SymbolType("/", 3, False)}, {"+", New SymbolType("+", 2, False)}, {"-", New SymbolType("-", 2, False)} } Function ToPostfix(infix As String) As String Dim tokens = infix.Split(" ") Dim stack As New Stack(Of String) Dim output As New List(Of String) Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]") For Each token In tokens Dim iv As Integer Dim op1 As SymbolType Dim op2 As SymbolType If Integer.TryParse(token, iv) Then output.Add(token) Print(token) ElseIf Operators.TryGetValue(token, op1) Then While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2) Dim c = op1.precedence.CompareTo(op2.precedence) If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then output.Add(stack.Pop()) Else Exit While End If End While stack.Push(token) Print(token) ElseIf token = "(" Then stack.Push(token) Print(token) ElseIf token = ")" Then Dim top = "" While stack.Count > 0 top = stack.Pop() If top <> "(" Then output.Add(top) Else Exit While End If End While If top <> "(" Then Throw New ArgumentException("No matching left parenthesis.") End If Print(token) End If Next While stack.Count > 0 Dim top = stack.Pop() If Not Operators.ContainsKey(top) Then Throw New ArgumentException("No matching right parenthesis.") End If output.Add(top) End While Print("pop") Return String.Join(" ", output) End Function Sub Main() Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" Console.WriteLine(ToPostfix(infix)) End Sub End Module
Please provide an equivalent version of this Java code in VB.
public class PrimeTriangle { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i = 2; i <= 20; ++i) { int[] a = new int[i]; for (int j = 0; j < i; ++j) a[j] = j + 1; if (findRow(a, 0, i)) printRow(a); } System.out.println(); StringBuilder s = new StringBuilder(); for (int i = 2; i <= 20; ++i) { int[] a = new int[i]; for (int j = 0; j < i; ++j) a[j] = j + 1; if (i > 2) s.append(" "); s.append(countRows(a, 0, i)); } System.out.println(s); long finish = System.currentTimeMillis(); System.out.printf("\nElapsed time: %d milliseconds\n", finish - start); } private static void printRow(int[] a) { for (int i = 0; i < a.length; ++i) { if (i != 0) System.out.print(" "); System.out.printf("%2d", a[i]); } System.out.println(); } private static boolean findRow(int[] a, int start, int length) { if (length == 2) return isPrime(a[start] + a[start + 1]); for (int i = 1; i + 1 < length; i += 2) { if (isPrime(a[start] + a[start + i])) { swap(a, start + i, start + 1); if (findRow(a, start + 1, length - 1)) return true; swap(a, start + i, start + 1); } } return false; } private static int countRows(int[] a, int start, int length) { int count = 0; if (length == 2) { if (isPrime(a[start] + a[start + 1])) ++count; } else { for (int i = 1; i + 1 < length; i += 2) { if (isPrime(a[start] + a[start + i])) { swap(a, start + i, start + 1); count += countRows(a, start + 1, length - 1); swap(a, start + i, start + 1); } } } return count; } private static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } private static boolean isPrime(int n) { return ((1L << n) & 0x28208a20a08a28acL) != 0; } }
Option Strict On Option Explicit On Imports System.IO Module vMain Public Const maxNumber As Integer = 20 Dim prime(2 * maxNumber) As Boolean Public Function countArrangements(ByVal n As Integer) As Integer If n < 2 Then Return 0 ElseIf n < 4 Then For i As Integer = 1 To n Console.Out.Write(i.ToString.PadLeft(3)) Next i Console.Out.WriteLine() Return 1 Else Dim printSolution As Boolean = true Dim used(n) As Boolean Dim number(n) As Integer For i As Integer = 0 To n - 1 number(i) = i Mod 2 Next i used(1) = True number(n) = n used(n) = True Dim count As Integer = 0 Dim p As Integer = 2 Do While p > 0 Dim p1 As Integer = number(p - 1) Dim current As Integer = number(p) Dim [next] As Integer = current + 2 Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next])) [next] += 2 Loop If [next] >= n Then [next] = 0 End If If p = n - 1 Then If [next] <> 0 Then If prime([next] + n) Then count += 1 If printSolution Then For i As Integer = 1 To n - 2 Console.Out.Write(number(i).ToString.PadLeft(3)) Next i Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3)) printSolution = False End If End If [next] = 0 End If p -= 1 End If If [next] <> 0 Then used(current) = False used([next]) = True number(p) = [next] p += 1 ElseIf p <= 2 Then p = 0 Else used(number(p)) = False number(p) = p Mod 2 p -= 1 End If Loop Return count End If End Function Public Sub Main prime(2) = True For i As Integer = 3 To UBound(prime) Step 2 prime(i) = True Next i For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2 If prime(i) Then For s As Integer = i * i To Ubound(prime) Step i + i prime(s) = False Next s End If Next i Dim arrangements(maxNumber) As Integer For n As Integer = 2 To UBound(arrangements) arrangements(n) = countArrangements(n) Next n For n As Integer = 2 To UBound(arrangements) Console.Out.Write(" " & arrangements(n)) Next n Console.Out.WriteLine() End Sub End Module
Generate a VB translation of this Java snippet without changing its computational steps.
import java.util.*; import java.io.*; public class TPKA { public static void main(String... args) { double[] input = new double[11]; double userInput = 0.0; Scanner in = new Scanner(System.in); for(int i = 0; i < 11; i++) { System.out.print("Please enter a number: "); String s = in.nextLine(); try { userInput = Double.parseDouble(s); } catch (NumberFormatException e) { System.out.println("You entered invalid input, exiting"); System.exit(1); } input[i] = userInput; } for(int j = 10; j >= 0; j--) { double x = input[j]; double y = f(x); if( y < 400.0) { System.out.printf("f( %.2f ) = %.2f\n", x, y); } else { System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE"); } } } private static double f(double x) { return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3))); } }
Function tpk(s) arr = Split(s," ") For i = UBound(arr) To 0 Step -1 n = fx(CDbl(arr(i))) If n > 400 Then WScript.StdOut.WriteLine arr(i) & " = OVERFLOW" Else WScript.StdOut.WriteLine arr(i) & " = " & n End If Next End Function Function fx(x) fx = Sqr(Abs(x))+5*x^3 End Function WScript.StdOut.Write "Please enter a series of numbers:" list = WScript.StdIn.ReadLine tpk(list)
Generate an equivalent VB version of this Java code.
import java.util.*; import java.io.*; public class TPKA { public static void main(String... args) { double[] input = new double[11]; double userInput = 0.0; Scanner in = new Scanner(System.in); for(int i = 0; i < 11; i++) { System.out.print("Please enter a number: "); String s = in.nextLine(); try { userInput = Double.parseDouble(s); } catch (NumberFormatException e) { System.out.println("You entered invalid input, exiting"); System.exit(1); } input[i] = userInput; } for(int j = 10; j >= 0; j--) { double x = input[j]; double y = f(x); if( y < 400.0) { System.out.printf("f( %.2f ) = %.2f\n", x, y); } else { System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE"); } } } private static double f(double x) { return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3))); } }
Function tpk(s) arr = Split(s," ") For i = UBound(arr) To 0 Step -1 n = fx(CDbl(arr(i))) If n > 400 Then WScript.StdOut.WriteLine arr(i) & " = OVERFLOW" Else WScript.StdOut.WriteLine arr(i) & " = " & n End If Next End Function Function fx(x) fx = Sqr(Abs(x))+5*x^3 End Function WScript.StdOut.Write "Please enter a series of numbers:" list = WScript.StdIn.ReadLine tpk(list)
Ensure the translated VB code behaves exactly like the original Java snippet.
public class MiddleThreeDigits { public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE}; final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}; for (long n : passing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); for (int n : failing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); } public static <T> String middleThreeDigits(T n) { String s = String.valueOf(n); if (s.charAt(0) == '-') s = s.substring(1); int len = s.length(); if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; int mid = len / 2; return s.substring(mid - 1, mid + 2); } }
Option Explicit Sub Main_Middle_three_digits() Dim Numbers, i& Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _ 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) For i = 0 To 16 Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i))) Next End Sub Function Middle3digits(strNb As String) As String If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1) If Len(strNb) < 3 Then Middle3digits = "Error ! Number of digits must be >= 3" ElseIf Len(strNb) Mod 2 = 0 Then Middle3digits = "Error ! Number of digits must be odd" Else Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3) End If End Function
Convert this Java block to VB, preserving its control flow and logic.
public class OddWord { interface CharHandler { CharHandler handle(char c) throws Exception; } final CharHandler fwd = new CharHandler() { public CharHandler handle(char c) { System.out.print(c); return (Character.isLetter(c) ? fwd : rev); } }; class Reverser extends Thread implements CharHandler { Reverser() { setDaemon(true); start(); } private Character ch; private char recur() throws Exception { notify(); while (ch == null) wait(); char c = ch, ret = c; ch = null; if (Character.isLetter(c)) { ret = recur(); System.out.print(c); } return ret; } public synchronized void run() { try { while (true) { System.out.print(recur()); notify(); } } catch (Exception e) {} } public synchronized CharHandler handle(char c) throws Exception { while (ch != null) wait(); ch = c; notify(); while (ch != null) wait(); return (Character.isLetter(c) ? rev : fwd); } } final CharHandler rev = new Reverser(); public void loop() throws Exception { CharHandler handler = fwd; int c; while ((c = System.in.read()) >= 0) { handler = handler.handle((char) c); } } public static void main(String[] args) throws Exception { new OddWord().loop(); } }
Private Function OddWordFirst(W As String) As String Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String count = 1 Do flag = Not flag l = FindNextPunct(i, W) - count + 1 If flag Then temp = temp & ExtractWord(W, count, l) Else temp = temp & ReverseWord(W, count, l) End If Loop While count < Len(W) OddWordFirst = temp End Function Private Function FindNextPunct(d As Integer, W As String) As Integer Const PUNCT As String = ",;:." Do d = d + 1 Loop While InStr(PUNCT, Mid(W, d, 1)) = 0 FindNextPunct = d End Function Private Function ExtractWord(W As String, c As Integer, i As Integer) As String ExtractWord = Mid(W, c, i) c = c + Len(ExtractWord) End Function Private Function ReverseWord(W As String, c As Integer, i As Integer) As String Dim temp As String, sep As String temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1) sep = Right(Mid(W, c, i), 1) ReverseWord = StrReverse(temp) & sep c = c + Len(ReverseWord) End Function
Write the same code in VB as shown below in Java.
import java.math.BigInteger; import java.util.LinkedList; public class SternBrocot { static LinkedList<Integer> sequence = new LinkedList<Integer>(){{ add(1); add(1); }}; private static void genSeq(int n){ for(int conIdx = 1; sequence.size() < n; conIdx++){ int consider = sequence.get(conIdx); int pre = sequence.get(conIdx - 1); sequence.add(consider + pre); sequence.add(consider); } } public static void main(String[] args){ genSeq(1200); System.out.println("The first 15 elements are: " + sequence.subList(0, 15)); for(int i = 1; i <= 10; i++){ System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1)); } System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1)); boolean failure = false; for(int i = 0; i < 999; i++){ failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE); } System.out.println("All GCDs are" + (failure ? " not" : "") + " 1"); } }
Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Dim l As List(Of Integer) = {1, 1}.ToList() Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b) End Function Sub Main(ByVal args As String()) Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1, selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1 Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last() Console.Write("The first {0} items In the Stern-Brocot sequence: ", take) Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take))) Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:") For Each ii As Integer In selection Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1 Console.WriteLine("{0,3}: {1:n0}", ii, j) Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For Next Console.WriteLine("The greatest common divisor of all the two consecutive items of the" & " series up to the {0}th item is {1}always one.", max, If(good, "", "not ")) End Sub End Module
Convert this Java snippet to VB and keep its semantics consistent.
public static void main(String[] args){ System.out.println(soundex("Soundex")); System.out.println(soundex("Example")); System.out.println(soundex("Sownteks")); System.out.println(soundex("Ekzampul")); } private static String getCode(char c){ switch(c){ case 'B': case 'F': case 'P': case 'V': return "1"; case 'C': case 'G': case 'J': case 'K': case 'Q': case 'S': case 'X': case 'Z': return "2"; case 'D': case 'T': return "3"; case 'L': return "4"; case 'M': case 'N': return "5"; case 'R': return "6"; default: return ""; } } public static String soundex(String s){ String code, previous, soundex; code = s.toUpperCase().charAt(0) + ""; previous = getCode(s.toUpperCase().charAt(0)); for(int i = 1;i < s.length();i++){ String current = getCode(s.toUpperCase().charAt(i)); if(current.length() > 0 && !current.equals(previous)){ code = code + current; } previous = current; } soundex = (code + "0000").substring(0, 4); return soundex; }
tt=array( _ "Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _ "Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example") tv=array( _ "A261","A261","G200","G200","H416","H416","L000","L300", _ "M220","P236","R163","R163","R150","T522","S532","E251") For i=lbound(tt) To ubound(tt) ts=soundex(tt(i)) If ts<>tv(i) Then ok=" KO "& tv(i) Else ok="" Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok Next Function getCode(c) Select Case c Case "B", "F", "P", "V" getCode = "1" Case "C", "G", "J", "K", "Q", "S", "X", "Z" getCode = "2" Case "D", "T" getCode = "3" Case "L" getCode = "4" Case "M", "N" getCode = "5" Case "R" getCode = "6" Case "W","H" getCode = "-" End Select End Function Function soundex(s) Dim code, previous, i code = UCase(Mid(s, 1, 1)) previous = getCode(UCase(Mid(s, 1, 1))) For i = 2 To Len(s) current = getCode(UCase(Mid(s, i, 1))) If current <> "" And current <> "-" And current <> previous Then code = code & current If current <> "-" Then previous = current Next soundex = Mid(code & "000", 1, 4) End Function
Convert this Java block to VB, preserving its control flow and logic.
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Imports System.Net.Sockets Imports System.Text Imports System.Threading Module Module1 Class State Private ReadOnly client As TcpClient Private ReadOnly sb As New StringBuilder Public Sub New(name As String, client As TcpClient) Me.Name = name Me.client = client End Sub Public ReadOnly Property Name As String Public Sub Send(text As String) Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text)) client.GetStream().Write(bytes, 0, bytes.Length) End Sub End Class ReadOnly connections As New Dictionary(Of Integer, State) Dim listen As TcpListener Dim serverThread As Thread Sub Main() listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004) serverThread = New Thread(New ThreadStart(AddressOf DoListen)) serverThread.Start() End Sub Private Sub DoListen() listen.Start() Console.WriteLine("Server: Started server") Do Console.Write("Server: Waiting...") Dim client = listen.AcceptTcpClient() Console.WriteLine(" Connected") Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient)) clientThread.Start(client) Loop End Sub Private Sub DoClient(client As TcpClient) Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId) Dim bytes = Encoding.ASCII.GetBytes("Enter name: ") client.GetStream().Write(bytes, 0, bytes.Length) Dim done As Boolean Dim name As String Do If Not client.Connected Then Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId) client.Close() Thread.CurrentThread.Abort() End If name = Receive(client) done = True For Each cl In connections Dim state = cl.Value If state.Name = name Then bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ") client.GetStream().Write(bytes, 0, bytes.Length) done = False End If Next Loop While Not done connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client)) Console.WriteLine(vbTab & "Total connections: {0}", connections.Count) Broadcast(String.Format("+++ {0} arrived +++", name)) Do Dim text = Receive(client) If text = "/quit" Then Broadcast(String.Format("Connection from {0} closed.", name)) connections.Remove(Thread.CurrentThread.ManagedThreadId) Console.WriteLine(vbTab & "Total connections: {0}", connections.Count) Exit Do End If If Not client.Connected Then Exit Do End If Broadcast(String.Format("{0}> {1}", name, text)) Loop Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId) client.Close() Thread.CurrentThread.Abort() End Sub Private Function Receive(client As TcpClient) As String Dim sb As New StringBuilder Do If client.Available > 0 Then While client.Available > 0 Dim ch = Chr(client.GetStream.ReadByte()) If ch = vbCr Then Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While Thread.Sleep(100) End If Loop End Function Private Sub Broadcast(text As String) Console.WriteLine(text) For Each client In connections If client.Key <> Thread.CurrentThread.ManagedThreadId Then Dim state = client.Value state.Send(text) End If Next End Sub End Module
Please provide an equivalent version of this Java code in VB.
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Imports System.Net.Sockets Imports System.Text Imports System.Threading Module Module1 Class State Private ReadOnly client As TcpClient Private ReadOnly sb As New StringBuilder Public Sub New(name As String, client As TcpClient) Me.Name = name Me.client = client End Sub Public ReadOnly Property Name As String Public Sub Send(text As String) Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text)) client.GetStream().Write(bytes, 0, bytes.Length) End Sub End Class ReadOnly connections As New Dictionary(Of Integer, State) Dim listen As TcpListener Dim serverThread As Thread Sub Main() listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004) serverThread = New Thread(New ThreadStart(AddressOf DoListen)) serverThread.Start() End Sub Private Sub DoListen() listen.Start() Console.WriteLine("Server: Started server") Do Console.Write("Server: Waiting...") Dim client = listen.AcceptTcpClient() Console.WriteLine(" Connected") Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient)) clientThread.Start(client) Loop End Sub Private Sub DoClient(client As TcpClient) Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId) Dim bytes = Encoding.ASCII.GetBytes("Enter name: ") client.GetStream().Write(bytes, 0, bytes.Length) Dim done As Boolean Dim name As String Do If Not client.Connected Then Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId) client.Close() Thread.CurrentThread.Abort() End If name = Receive(client) done = True For Each cl In connections Dim state = cl.Value If state.Name = name Then bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ") client.GetStream().Write(bytes, 0, bytes.Length) done = False End If Next Loop While Not done connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client)) Console.WriteLine(vbTab & "Total connections: {0}", connections.Count) Broadcast(String.Format("+++ {0} arrived +++", name)) Do Dim text = Receive(client) If text = "/quit" Then Broadcast(String.Format("Connection from {0} closed.", name)) connections.Remove(Thread.CurrentThread.ManagedThreadId) Console.WriteLine(vbTab & "Total connections: {0}", connections.Count) Exit Do End If If Not client.Connected Then Exit Do End If Broadcast(String.Format("{0}> {1}", name, text)) Loop Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId) client.Close() Thread.CurrentThread.Abort() End Sub Private Function Receive(client As TcpClient) As String Dim sb As New StringBuilder Do If client.Available > 0 Then While client.Available > 0 Dim ch = Chr(client.GetStream.ReadByte()) If ch = vbCr Then Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While Thread.Sleep(100) End If Loop End Function Private Sub Broadcast(text As String) Console.WriteLine(text) For Each client In connections If client.Key <> Thread.CurrentThread.ManagedThreadId Then Dim state = client.Value state.Send(text) End If Next End Sub End Module
Translate the given Java code snippet into VB without altering its behavior.
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); long newSize = Long.parseLong(args[1]); outChan.truncate(newSize); outChan.close(); } }
Sub truncate(fpath,n) Set objfso = CreateObject("Scripting.FileSystemObject") If objfso.FileExists(fpath) = False Then WScript.Echo fpath & " does not exist" Exit Sub End If content = "" Set objinstream = CreateObject("Adodb.Stream") With objinstream .Type = 1 .Open .LoadFromFile(fpath) If n <= .Size Then content = .Read(n) Else WScript.Echo "The specified size is larger than the file content" Exit Sub End If .Close End With Set objoutstream = CreateObject("Adodb.Stream") With objoutstream .Type = 1 .Open .Write content .SaveToFile fpath,2 .Close End With Set objinstream = Nothing Set objoutstream = Nothing Set objfso = Nothing End Sub Call truncate("C:\temp\test.txt",30)
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); long newSize = Long.parseLong(args[1]); outChan.truncate(newSize); outChan.close(); } }
Sub truncate(fpath,n) Set objfso = CreateObject("Scripting.FileSystemObject") If objfso.FileExists(fpath) = False Then WScript.Echo fpath & " does not exist" Exit Sub End If content = "" Set objinstream = CreateObject("Adodb.Stream") With objinstream .Type = 1 .Open .LoadFromFile(fpath) If n <= .Size Then content = .Read(n) Else WScript.Echo "The specified size is larger than the file content" Exit Sub End If .Close End With Set objoutstream = CreateObject("Adodb.Stream") With objoutstream .Type = 1 .Open .Write content .SaveToFile fpath,2 .Close End With Set objinstream = Nothing Set objoutstream = Nothing Set objfso = Nothing End Sub Call truncate("C:\temp\test.txt",30)
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function DecimalToBinary(DecimalNum As Long) As String Dim tmp As String Dim n As Long n = DecimalNum tmp = Trim(CStr(n Mod 2)) n = n \ 2 Do While n <> 0 tmp = Trim(CStr(n Mod 2)) & tmp n = n \ 2 Loop DecimalToBinary = tmp End Function Function Dec2Bin(ByVal DecimalIn As Variant, _ Optional NumberOfBits As Variant) As String Dec2Bin = "" DecimalIn = Int(CDec(DecimalIn)) Do While DecimalIn <> 0 Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin DecimalIn = Int(DecimalIn / 2) Loop If Not IsMissing(NumberOfBits) Then If Len(Dec2Bin) > NumberOfBits Then Dec2Bin = "Error - Number exceeds specified bit size" Else Dec2Bin = Right$(String$(NumberOfBits, _ "0") & Dec2Bin, NumberOfBits) End If End If End Function Public Sub base() Time1 = GetTickCount Dim n As Long Dim three(19) As Integer Dim pow3(19) As Variant Dim full3 As Variant Dim trail As Variant Dim check As Long Dim len3 As Integer Dim carry As Boolean Dim i As Integer, j As Integer Dim s As String Dim t As String pow3(0) = CDec(1) For i = 1 To 19 pow3(i) = 3 * pow3(i - 1) Next i Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary"; Debug.Print String$(30, " "); "ternary" n = 0: full3 = 0: t = "0": s = "0" Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " "); Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " "); Debug.Print String$((31 - Len(s)) / 2, " "); s n = 0: full3 = 1: t = "1": s = "1" Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " "); Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " "); Debug.Print String$((31 - Len(s)) / 2, " "); s number = 0 n = 1 len3 = 0 full3 = 3 Do three(0) = three(0) + 1 carry = False If three(0) = 3 Then three(0) = 0 carry = True j = 1 Do While carry three(j) = three(j) + 1 If three(j) = 3 Then three(j) = 0 j = j + 1 Else carry = False End If Loop If len3 < j Then trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1) len3 = j full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail For i = 0 To j - 1 full3 = full3 - 2 * pow3(len3 - i) Next i full3 = full3 + 1 Else full3 = full3 + pow3(len3 + 2) For i = 0 To j - 1 full3 = full3 - 2 * pow3(len3 - i) Next i full3 = full3 + pow3(len3 - j) End If Else full3 = full3 + pow3(len3 + 2) + pow3(len3) End If s = "" For i = 0 To len3 s = s & CStr(three(i)) Next i t = Dec2Bin(full3) If t = StrReverse(t) Then number = number + 1 s = StrReverse(s) & "1" & s If n < 200000 Then Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " "); Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " "); Debug.Print String$((31 - Len(s)) / 2, " "); s If number = 4 Then Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds" Time2 = GetTickCount Application.ScreenUpdating = False End If Else Debug.Print n, full3, Len(t), t, Len(s), s Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds"; Time3 = GetTickCount End If End If n = n + 1 Loop Until number = 5 Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds" Application.ScreenUpdating = True End Sub
Rewrite the snippet below in VB so it works the same as the original Java code.
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private Function DecimalToBinary(DecimalNum As Long) As String Dim tmp As String Dim n As Long n = DecimalNum tmp = Trim(CStr(n Mod 2)) n = n \ 2 Do While n <> 0 tmp = Trim(CStr(n Mod 2)) & tmp n = n \ 2 Loop DecimalToBinary = tmp End Function Function Dec2Bin(ByVal DecimalIn As Variant, _ Optional NumberOfBits As Variant) As String Dec2Bin = "" DecimalIn = Int(CDec(DecimalIn)) Do While DecimalIn <> 0 Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin DecimalIn = Int(DecimalIn / 2) Loop If Not IsMissing(NumberOfBits) Then If Len(Dec2Bin) > NumberOfBits Then Dec2Bin = "Error - Number exceeds specified bit size" Else Dec2Bin = Right$(String$(NumberOfBits, _ "0") & Dec2Bin, NumberOfBits) End If End If End Function Public Sub base() Time1 = GetTickCount Dim n As Long Dim three(19) As Integer Dim pow3(19) As Variant Dim full3 As Variant Dim trail As Variant Dim check As Long Dim len3 As Integer Dim carry As Boolean Dim i As Integer, j As Integer Dim s As String Dim t As String pow3(0) = CDec(1) For i = 1 To 19 pow3(i) = 3 * pow3(i - 1) Next i Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary"; Debug.Print String$(30, " "); "ternary" n = 0: full3 = 0: t = "0": s = "0" Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " "); Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " "); Debug.Print String$((31 - Len(s)) / 2, " "); s n = 0: full3 = 1: t = "1": s = "1" Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " "); Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " "); Debug.Print String$((31 - Len(s)) / 2, " "); s number = 0 n = 1 len3 = 0 full3 = 3 Do three(0) = three(0) + 1 carry = False If three(0) = 3 Then three(0) = 0 carry = True j = 1 Do While carry three(j) = three(j) + 1 If three(j) = 3 Then three(j) = 0 j = j + 1 Else carry = False End If Loop If len3 < j Then trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1) len3 = j full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail For i = 0 To j - 1 full3 = full3 - 2 * pow3(len3 - i) Next i full3 = full3 + 1 Else full3 = full3 + pow3(len3 + 2) For i = 0 To j - 1 full3 = full3 - 2 * pow3(len3 - i) Next i full3 = full3 + pow3(len3 - j) End If Else full3 = full3 + pow3(len3 + 2) + pow3(len3) End If s = "" For i = 0 To len3 s = s & CStr(three(i)) Next i t = Dec2Bin(full3) If t = StrReverse(t) Then number = number + 1 s = StrReverse(s) & "1" & s If n < 200000 Then Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " "); Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " "); Debug.Print String$((31 - Len(s)) / 2, " "); s If number = 4 Then Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds" Time2 = GetTickCount Application.ScreenUpdating = False End If Else Debug.Print n, full3, Len(t), t, Len(s), s Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds"; Time3 = GetTickCount End If End If n = n + 1 Loop Until number = 5 Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds" Application.ScreenUpdating = True End Sub
Write the same code in VB as shown below in Java.
import java.util.*; public class FiniteStateMachine { private enum State { Ready(true, "Deposit", "Quit"), Waiting(true, "Select", "Refund"), Dispensing(true, "Remove"), Refunding(false, "Refunding"), Exiting(false, "Quiting"); State(boolean exp, String... in) { inputs = Arrays.asList(in); explicit = exp; } State nextState(String input, State current) { if (inputs.contains(input)) { return map.getOrDefault(input, current); } return current; } final List<String> inputs; final static Map<String, State> map = new HashMap<>(); final boolean explicit; static { map.put("Deposit", State.Waiting); map.put("Quit", State.Exiting); map.put("Select", State.Dispensing); map.put("Refund", State.Refunding); map.put("Remove", State.Ready); map.put("Refunding", State.Ready); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); State state = State.Ready; while (state != State.Exiting) { System.out.println(state.inputs); if (state.explicit){ System.out.print("> "); state = state.nextState(sc.nextLine().trim(), state); } else { state = state.nextState(state.inputs.get(0), state); } } } }
Enum states READY WAITING DISPENSE REFUND QU1T End Enum Public Sub finite_state_machine() Dim state As Integer: state = READY: ch = " " Do While True Debug.Print ch Select Case state Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :" Do While True If ch = "D" Then state = WAITING Exit Do End If If ch = "Q" Then state = QU1T Exit Do End If ch = InputBox("Machine is READY. (D)eposit or (Q)uit :") Loop Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :" Do While True If ch = "S" Then state = DISPENSE Exit Do End If If ch = "R" Then state = REFUND Exit Do End If ch = InputBox("(S)elect product or choose to (R)efund :") Loop Case DISPENSE: Debug.Print "Dispensing product..." Do While True If ch = "C" Then state = READY Exit Do End If ch = InputBox("Please (C)ollect product. :") Loop Case REFUND: Debug.Print "Please collect refund." state = READY ch = " " Case QU1T: Debug.Print "Thank you, shutting down now." Exit Sub End Select Loop End Sub
Preserve the algorithm and functionality while converting the code from Java to VB.
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Imports System.Numerics Module Module1 ReadOnly BIG = BigInteger.Pow(10, 50) + 151 Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean) Dim n = BigInteger.Parse(ns) Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG) Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p) If ls(n) <> 1 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Dim a = BigInteger.Zero Dim omega2 As BigInteger Do omega2 = (a * a + p - n) Mod p If ls(omega2) = p - 1 Then Exit Do End If a += 1 Loop Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger)) Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p) End Function Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero) Dim s = Tuple.Create(a, BigInteger.One) Dim nn = ((p + 1) >> 1) Mod p While nn > 0 If nn Mod 2 = 1 Then r = mul(r, s) End If s = mul(s, s) nn >>= 1 End While If r.Item2 <> 0 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If If r.Item1 * r.Item1 Mod p <> n Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Return Tuple.Create(r.Item1, p - r.Item1, True) End Function Sub Main() Console.WriteLine(C("10", "13")) Console.WriteLine(C("56", "101")) Console.WriteLine(C("8218", "10007")) Console.WriteLine(C("8219", "10007")) Console.WriteLine(C("331575", "1000003")) Console.WriteLine(C("665165880", "1000000007")) Console.WriteLine(C("881398088036", "1000000000039")) Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")) End Sub End Module
Translate this program into VB but keep the logic exactly as in Java.
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Imports System.Numerics Module Module1 ReadOnly BIG = BigInteger.Pow(10, 50) + 151 Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean) Dim n = BigInteger.Parse(ns) Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG) Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p) If ls(n) <> 1 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Dim a = BigInteger.Zero Dim omega2 As BigInteger Do omega2 = (a * a + p - n) Mod p If ls(omega2) = p - 1 Then Exit Do End If a += 1 Loop Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger)) Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p) End Function Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero) Dim s = Tuple.Create(a, BigInteger.One) Dim nn = ((p + 1) >> 1) Mod p While nn > 0 If nn Mod 2 = 1 Then r = mul(r, s) End If s = mul(s, s) nn >>= 1 End While If r.Item2 <> 0 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If If r.Item1 * r.Item1 Mod p <> n Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Return Tuple.Create(r.Item1, p - r.Item1, True) End Function Sub Main() Console.WriteLine(C("10", "13")) Console.WriteLine(C("56", "101")) Console.WriteLine(C("8218", "10007")) Console.WriteLine(C("8219", "10007")) Console.WriteLine(C("331575", "1000003")) Console.WriteLine(C("665165880", "1000000007")) Console.WriteLine(C("881398088036", "1000000000039")) Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")) End Sub End Module
Please provide an equivalent version of this Java code in VB.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees072) * 2); final int margin = 20; int limit = 0; Random r = new Random(); public SierpinskiPentagon() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(3000, (ActionEvent e) -> { limit++; if (limit >= 5) limit = 0; repaint(); }).start(); } void drawPentagon(Graphics2D g, double x, double y, double side, int depth) { double angle = 3 * degrees072; if (depth == 0) { Path2D p = new Path2D.Double(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { x = x + cos(angle) * side; y = y - sin(angle) * side; p.lineTo(x, y); angle += degrees072; } g.setColor(RandomHue.next()); g.fill(p); } else { side *= scaleFactor; double distance = side + side * cos(degrees072) * 2; for (int i = 0; i < 5; i++) { x = x + cos(angle) * distance; y = y - sin(angle) * distance; drawPentagon(g, x, y, side, depth - 1); angle += degrees072; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int w = getWidth(); double radius = w / 2 - 2 * margin; double side = radius * sin(PI / 5) * 2; drawPentagon(g, w / 2, 3 * margin, side, limit); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Sierpinski Pentagon"); f.setResizable(true); f.add(new SierpinskiPentagon(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } } class RandomHue { final static double goldenRatioConjugate = (sqrt(5) - 1) / 2; private static double hue = Math.random(); static Color next() { hue = (hue + goldenRatioConjugate) % 1; return Color.getHSBColor((float) hue, 1, 1); } }
Private Sub sierpinski(Order_ As Integer, Side As Double) Dim Circumradius As Double, Inradius As Double Dim Height As Double, Diagonal As Double, HeightDiagonal As Double Dim Pi As Double, p(5) As String, Shp As Shape Circumradius = Sqr(50 + 10 * Sqr(5)) / 10 Inradius = Sqr(25 + 10 * Sqr(5)) / 10 Height = Circumradius + Inradius Diagonal = (1 + Sqr(5)) / 2 HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4 Pi = WorksheetFunction.Pi Ratio = Height / (2 * Height + HeightDiagonal) Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _ 2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side) p(0) = Shp.Name Shp.Rotation = 180 Shp.Line.Weight = 0 For j = 1 To Order_ For i = 0 To 4 Set Shp = Shp.Duplicate p(i + 1) = Shp.Name If i = 0 Then Shp.Rotation = 0 Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5) Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5) Shp.Visible = msoTrue Next i Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group p(0) = Shp.Name If j < Order_ Then Shp.ScaleHeight Ratio, False Shp.ScaleWidth Ratio, False Shp.Rotation = 180 Shp.Left = 2 * Side Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side End If Next j End Sub Public Sub main() sierpinski Order_:=5, Side:=200 End Sub
Change the programming language of this snippet from Java to VB without modifying what it does.
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s : %s%n", s, repString(s)); } static String repString(String s) { int len = s.length(); outer: for (int part = len / 2; part > 0; part--) { int tail = len % part; if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail))) continue; for (int j = 0; j < len / part - 1; j++) { int a = j * part; int b = (j + 1) * part; int c = (j + 2) * part; if (!s.substring(a, b).equals(s.substring(b, c))) continue outer; } return s.substring(0, part); } return "none"; } }
Function rep_string(s) max_len = Int(Len(s)/2) tmp = "" If max_len = 0 Then rep_string = "No Repeating String" Exit Function End If For i = 1 To max_len If InStr(i+1,s,tmp & Mid(s,i,1))Then tmp = tmp & Mid(s,i,1) Else Exit For End If Next Do While Len(tmp) > 0 If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then rep_string = tmp Exit Do Else tmp = Mid(tmp,1,Len(tmp)-1) End If Loop If Len(tmp) > 0 Then rep_string = tmp Else rep_string = "No Repeating String" End If End Function arr = Array("1001110011","1110111011","0010010010","1010101010",_ "1111111111","0100101101","0100100","101","11","00","1") For n = 0 To UBound(arr) WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n)) WScript.StdOut.WriteLine Next
Convert this Java block to VB, preserving its control flow and logic.
char a = 'a'; String b = "abc"; char doubleQuote = '"'; char singleQuote = '\''; String singleQuotes = "''"; String doubleQuotes = "\"\"";
Debug.Print "Tom said, ""The fox ran away.""" Debug.Print "Tom said,
Transform the following Java implementation into VB, maintaining the same output and logic.
import java.awt.*; import javax.swing.JFrame; public class Test extends JFrame { public static void main(String[] args) { new Test(); } Test() { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); System.out.println("Physical screen size: " + screenSize); Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration()); System.out.println("Insets: " + insets); screenSize.width -= (insets.left + insets.right); screenSize.height -= (insets.top + insets.bottom); System.out.println("Max available: " + screenSize); } }
TYPE syswindowstru screenheight AS INTEGER screenwidth AS INTEGER maxheight AS INTEGER maxwidth AS INTEGER END TYPE DIM syswindow AS syswindowstru syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
Ensure the translated VB code behaves exactly like the original Java snippet.
enum Fruits{ APPLE, BANANA, CHERRY }
Enum fruits apple banana cherry End Enum Enum fruits2 pear = 5 mango = 10 kiwi = 20 pineapple = 20 End Enum Sub test() Dim f As fruits f = apple Debug.Print "apple equals "; f Debug.Print "kiwi equals "; kiwi Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple End Sub
Maintain the same structure and functionality when rewriting this code in VB.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Sub pentagram() With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400) .Fill.ForeColor.RGB = RGB(255, 0, 0) .Line.Weight = 3 .Line.ForeColor.RGB = RGB(0, 0, 255) End With End Sub
Generate an equivalent VB version of this Java code.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Sub pentagram() With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400) .Fill.ForeColor.RGB = RGB(255, 0, 0) .Line.Weight = 3 .Line.ForeColor.RGB = RGB(0, 0, 255) End With End Sub
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"}; System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port"); for ( String ip : tests ) { try { String [] parsed = parseIP(ip); System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]); } catch (IllegalArgumentException e) { System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage()); } } } private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$"); private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$"); private static String ipv6Pattern; static { ipv6Pattern = "^\\[{0,1}"; for ( int i = 1 ; i <= 7 ; i ++ ) { ipv6Pattern += "([0-9a-f]+):"; } ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$"; } private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern); private static String[] parseIP(String ip) { String hex = ""; String port = ""; Matcher ipv4Matcher = IPV4_PAT.matcher(ip); if ( ipv4Matcher.matches() ) { for ( int i = 1 ; i <= 4 ; i++ ) { hex += toHex4(ipv4Matcher.group(i)); } if ( ipv4Matcher.group(5) != null ) { port = ipv4Matcher.group(5); } return new String[] {hex, port}; } Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip); if ( ipv6DoubleColonMatcher.matches() ) { String p1 = ipv6DoubleColonMatcher.group(1); if ( p1.isEmpty() ) { p1 = "0"; } String p2 = ipv6DoubleColonMatcher.group(2); if ( p2.isEmpty() ) { p2 = "0"; } ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2; if ( ipv6DoubleColonMatcher.group(3) != null ) { ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3); } } Matcher ipv6Matcher = IPV6_PAT.matcher(ip); if ( ipv6Matcher.matches() ) { for ( int i = 1 ; i <= 8 ; i++ ) { hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0"); } if ( ipv6Matcher.group(9) != null ) { port = ipv6Matcher.group(9); } return new String[] {hex, port}; } throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip); } private static int numCount(String s) { return s.split(":").length; } private static String getZero(int count) { StringBuilder sb = new StringBuilder(); sb.append(":"); while ( count > 0 ) { sb.append("0:"); count--; } return sb.toString(); } private static String toHex4(String s) { int val = Integer.parseInt(s); if ( val < 0 || val > 255 ) { throw new IllegalArgumentException("ERROR 101: Invalid value : " + s); } return String.format("%2s", Integer.toHexString(val)).replace(" ", "0"); } private static String toHex6(String s) { int val = Integer.parseInt(s, 16); if ( val < 0 || val > 65536 ) { throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s); } return s; } }
Function parse_ip(addr) Set ipv4_pattern = New RegExp ipv4_pattern.Global = True ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}" Set ipv6_pattern = New RegExp ipv6_pattern.Global = True ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}" If ipv4_pattern.Test(addr) Then port = Split(addr,":") octet = Split(port(0),".") ipv4_hex = "" For i = 0 To UBound(octet) If octet(i) <= 255 And octet(i) >= 0 Then ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2) Else ipv4_hex = "Erroneous Address" Exit For End If Next parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: " & ipv4_hex & vbCrLf If UBound(port) = 1 Then If port(1) <= 65535 And port(1) >= 0 Then parse_ip = parse_ip & "Port: " & port(1) & vbCrLf Else parse_ip = parse_ip & "Port: Invalid" & vbCrLf End If End If End If If ipv6_pattern.Test(addr) Then parse_ip = "Test Case: " & addr & vbCrLf port_v6 = "Port: " ipv6_hex = "" If InStr(1,addr,"[") Then port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1))) addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1)) End If word = Split(addr,":") word_count = 0 For i = 0 To UBound(word) If word(i) = "" Then If i < UBound(word) Then If Int((7-(i+1))/2) = 1 Then k = 1 ElseIf UBound(word) < 6 Then k = Int((7-(i+1))/2) ElseIf UBound(word) >= 6 Then k = Int((7-(i+1))/2)-1 End If For j = 0 To k ipv6_hex = ipv6_hex & "0000" word_count = word_count + 1 Next Else For j = 0 To (7-word_count) ipv6_hex = ipv6_hex & "0000" Next End If Else ipv6_hex = ipv6_hex & Right("0000" & word(i),4) word_count = word_count + 1 End If Next parse_ip = parse_ip & "Address: " & ipv6_hex &_ vbCrLf & port_v6 & vbCrLf End If If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: Invalid Address" & vbCrLf End If End Function ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_ "[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode") For n = 0 To UBound(ip_arr) WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf Next
Write a version of this Java function in VB with identical behavior.
package hu.pj.alg; import hu.pj.obj.Item; import java.text.*; public class UnboundedKnapsack { protected Item [] items = { new Item("panacea", 3000, 0.3, 0.025), new Item("ichor" , 1800, 0.2, 0.015), new Item("gold" , 2500, 2.0, 0.002) }; protected final int n = items.length; protected Item sack = new Item("sack" , 0, 25.0, 0.250); protected Item best = new Item("best" , 0, 0.0, 0.000); protected int [] maxIt = new int [n]; protected int [] iIt = new int [n]; protected int [] bestAm = new int [n]; public UnboundedKnapsack() { for (int i = 0; i < n; i++) { maxIt [i] = Math.min( (int)(sack.getWeight() / items[i].getWeight()), (int)(sack.getVolume() / items[i].getVolume()) ); } calcWithRecursion(0); NumberFormat nf = NumberFormat.getInstance(); System.out.println("Maximum value achievable is: " + best.getValue()); System.out.print("This is achieved by carrying (one solution): "); for (int i = 0; i < n; i++) { System.out.print(bestAm[i] + " " + items[i].getName() + ", "); } System.out.println(); System.out.println("The weight to carry is: " + nf.format(best.getWeight()) + " and the volume used is: " + nf.format(best.getVolume()) ); } public void calcWithRecursion(int item) { for (int i = 0; i <= maxIt[item]; i++) { iIt[item] = i; if (item < n-1) { calcWithRecursion(item+1); } else { int currVal = 0; double currWei = 0.0; double currVol = 0.0; for (int j = 0; j < n; j++) { currVal += iIt[j] * items[j].getValue(); currWei += iIt[j] * items[j].getWeight(); currVol += iIt[j] * items[j].getVolume(); } if (currVal > best.getValue() && currWei <= sack.getWeight() && currVol <= sack.getVolume() ) { best.setValue (currVal); best.setWeight(currWei); best.setVolume(currVol); for (int j = 0; j < n; j++) bestAm[j] = iIt[j]; } } } } public static void main(String[] args) { new UnboundedKnapsack(); } }
Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function Sub Main() Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5 Dim P&, I&, G&, A&, M, Cur(Value To Volume) Dim S As New Collection: S.Add Array(0) Const SackW = 25, SackV = 0.25 Dim Panacea: Panacea = Array(3000, 0.3, 0.025) Dim Ichor: Ichor = Array(1800, 0.2, 0.015) Dim Gold: Gold = Array(2500, 2, 0.002) For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume))) For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume))) For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume))) For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _ S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1 Next G, I, P Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount" For Each M In S If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC) Next End Sub
Produce a functionally identical VB code for the snippet given in Java.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static final Map<Character, Character> mapping; private int total, elements, textonyms, max_found; private String filename, mappingResult; private Vector<String> max_strings; private Map<String, Vector<String>> values; static { mapping = new HashMap<Character, Character>(); mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2'); mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3'); mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4'); mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5'); mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6'); mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7'); mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8'); mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9'); } public RTextonyms(String filename) { this.filename = filename; this.total = this.elements = this.textonyms = this.max_found = 0; this.values = new HashMap<String, Vector<String>>(); this.max_strings = new Vector<String>(); return; } public void add(String line) { String mapping = ""; total++; if (!get_mapping(line)) { return; } mapping = mappingResult; if (values.get(mapping) == null) { values.put(mapping, new Vector<String>()); } int num_strings; num_strings = values.get(mapping).size(); textonyms += num_strings == 1 ? 1 : 0; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.add(mapping); max_found = num_strings; } else if (num_strings == max_found) { max_strings.add(mapping); } values.get(mapping).add(line); return; } public void results() { System.out.printf("Read %,d words from %s%n%n", total, filename); System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements, filename); System.out.printf("They require %,d digit combinations to represent them.%n", values.size()); System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms); System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1); for (String key : max_strings) { System.out.printf("%16s maps to: %s%n", key, values.get(key).toString()); } System.out.println(); return; } public void match(String key) { Vector<String> match; match = values.get(key); if (match == null) { System.out.printf("Key %s not found%n", key); } else { System.out.printf("Key %s matches: %s%n", key, match.toString()); } return; } private boolean get_mapping(String line) { mappingResult = line; StringBuilder mappingBuilder = new StringBuilder(); for (char cc : line.toCharArray()) { if (Character.isAlphabetic(cc)) { mappingBuilder.append(mapping.get(Character.toUpperCase(cc))); } else if (Character.isDigit(cc)) { mappingBuilder.append(cc); } else { return false; } } mappingResult = mappingBuilder.toString(); return true; } public static void main(String[] args) { String filename; if (args.length > 0) { filename = args[0]; } else { filename = "./unixdict.txt"; } RTextonyms tc; tc = new RTextonyms(filename); Path fp = Paths.get(filename); try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) { while (fs.hasNextLine()) { tc.add(fs.nextLine()); } } catch (IOException ex) { ex.printStackTrace(); } List<String> numbers = Arrays.asList( "001", "228", "27484247", "7244967473642", "." ); tc.results(); for (String number : numbers) { if (number.equals(".")) { System.out.println(); } else { tc.match(number); } } return; } }
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1) Set objKeyMap = CreateObject("Scripting.Dictionary") With objKeyMap .Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5" .Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9" End With TotalWords = 0 UniqueCombinations = 0 Set objUniqueWords = CreateObject("Scripting.Dictionary") Set objMoreThanOneWord = CreateObject("Scripting.Dictionary") Do Until objInFile.AtEndOfStream Word = objInFile.ReadLine c = 0 Num = "" If Word <> "" Then For i = 1 To Len(Word) For Each Key In objKeyMap.Keys If InStr(1,Key,Mid(Word,i,1),1) > 0 Then Num = Num & objKeyMap.Item(Key) c = c + 1 End If Next Next If c = Len(Word) Then TotalWords = TotalWords + 1 If objUniqueWords.Exists(Num) = False Then objUniqueWords.Add Num, "" UniqueCombinations = UniqueCombinations + 1 Else If objMoreThanOneWord.Exists(Num) = False Then objMoreThanOneWord.Add Num, "" End If End If End If End If Loop WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_ "They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_ objMoreThanOneWord.Count & " digit combinations represent Textonyms." objInFile.Close
Generate a VB translation of this Java snippet without changing its computational steps.
public class RangeExtraction { public static void main(String[] args) { int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39}; int len = arr.length; int idx = 0, idx2 = 0; while (idx < len) { while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1); if (idx2 - idx > 2) { System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]); idx = idx2; } else { for (; idx < idx2; idx++) System.out.printf("%s,", arr[idx]); } } } }
Public Function RangeExtraction(AList) As String Const RangeDelim = "-" Dim result As String Dim InRange As Boolean Dim Posn, ub, lb, rangestart, rangelen As Integer result = "" ub = UBound(AList) lb = LBound(AList) Posn = lb While Posn < ub rangestart = Posn rangelen = 0 InRange = True While InRange rangelen = rangelen + 1 If Posn = ub Then InRange = False Else InRange = (AList(Posn + 1) = AList(Posn) + 1) Posn = Posn + 1 End If Wend If rangelen > 2 Then result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1)) Else For i = rangestart To rangestart + rangelen - 1 result = result & "," & Format$(AList(i)) Next End If Posn = rangestart + rangelen Wend RangeExtraction = Mid$(result, 2) End Function Public Sub RangeTest() Dim MyList As Variant MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39) Debug.Print "a) "; RangeExtraction(MyList) Dim MyOtherList(1 To 20) As Integer MyOtherList(1) = -6 MyOtherList(2) = -3 MyOtherList(3) = -2 MyOtherList(4) = -1 MyOtherList(5) = 0 MyOtherList(6) = 1 MyOtherList(7) = 3 MyOtherList(8) = 4 MyOtherList(9) = 5 MyOtherList(10) = 7 MyOtherList(11) = 8 MyOtherList(12) = 9 MyOtherList(13) = 10 MyOtherList(14) = 11 MyOtherList(15) = 14 MyOtherList(16) = 15 MyOtherList(17) = 17 MyOtherList(18) = 18 MyOtherList(19) = 19 MyOtherList(20) = 20 Debug.Print "b) "; RangeExtraction(MyOtherList) End Sub
Port the following code from Java to VB with equivalent syntax and logic.
public class TypeDetection { private static void showType(Object a) { if (a instanceof Integer) { System.out.printf("'%s' is an integer\n", a); } else if (a instanceof Double) { System.out.printf("'%s' is a double\n", a); } else if (a instanceof Character) { System.out.printf("'%s' is a character\n", a); } else { System.out.printf("'%s' is some other type\n", a); } } public static void main(String[] args) { showType(5); showType(7.5); showType('d'); showType(true); } }
Public Sub main() Dim c(1) As Currency Dim d(1) As Double Dim dt(1) As Date Dim a(1) As Integer Dim l(1) As Long Dim s(1) As Single Dim e As Variant Dim o As Object Set o = New Application Debug.Print TypeName(o) Debug.Print TypeName(1 = 1) Debug.Print TypeName(CByte(1)) Set o = New Collection Debug.Print TypeName(o) Debug.Print TypeName(1@) Debug.Print TypeName(c) Debug.Print TypeName(CDate(1)) Debug.Print TypeName(dt) Debug.Print TypeName(CDec(1)) Debug.Print TypeName(1#) Debug.Print TypeName(d) Debug.Print TypeName(e) Debug.Print TypeName(CVErr(1)) Debug.Print TypeName(1) Debug.Print TypeName(a) Debug.Print TypeName(1&) Debug.Print TypeName(l) Set o = Nothing Debug.Print TypeName(o) Debug.Print TypeName([A1]) Debug.Print TypeName(1!) Debug.Print TypeName(s) Debug.Print TypeName(CStr(1)) Debug.Print TypeName(Worksheets(1)) End Sub
Change the following Java code into VB without altering its purpose.
import java.nio.file.*; import static java.util.Arrays.stream; public class MaxPathSum { public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::parseInt) .toArray()) .toArray(int[][]::new); for (int r = data.length - 1; r > 0; r--) for (int c = 0; c < data[r].length - 1; c++) data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); System.out.println(data[0][0]); } }
Set objfso = CreateObject("Scripting.FileSystemObject") Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\triangle.txt",1,False) row = Split(objinfile.ReadAll,vbCrLf) For i = UBound(row) To 0 Step -1 row(i) = Split(row(i)," ") If i < UBound(row) Then For j = 0 To UBound(row(i)) If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j)) Else row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1)) End If Next End If Next WScript.Echo row(0)(0) objinfile.Close Set objfso = Nothing
Write a version of this Java function in VB with identical behavior.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "}; final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, {0, 4, 6}}}; static List<Point> toWhite = new ArrayList<>(); static char[][] grid; public static void main(String[] args) { grid = new char[image.length][]; for (int r = 0; r < image.length; r++) grid[r] = image[r].toCharArray(); thinImage(); } static void thinImage() { boolean firstStep = false; boolean hasChanged; do { hasChanged = false; firstStep = !firstStep; for (int r = 1; r < grid.length - 1; r++) { for (int c = 1; c < grid[0].length - 1; c++) { if (grid[r][c] != '#') continue; int nn = numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (numTransitions(r, c) != 1) continue; if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; toWhite.add(new Point(c, r)); hasChanged = true; } } for (Point p : toWhite) grid[p.y][p.x] = ' '; toWhite.clear(); } while (firstStep || hasChanged); printResult(); } static int numNeighbors(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++; return count; } static int numTransitions(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++; } return count; } static boolean atLeastOneIsWhite(int r, int c, int step) { int count = 0; int[][] group = nbrGroups[step]; for (int i = 0; i < 2; i++) for (int j = 0; j < group[i].length; j++) { int[] nbr = nbrs[group[i][j]]; if (grid[r + nbr[1]][c + nbr[0]] == ' ') { count++; break; } } return count > 1; } static void printResult() { for (char[] row : grid) System.out.println(row); } }
Public n As Variant Private Sub init() n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}] End Sub Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant Dim wtb As Integer Dim bn As Integer Dim prev As String: prev = "#" Dim next_ As String Dim p2468 As String For i = 1 To UBound(n) next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1) wtb = wtb - (prev = "." And next_ <= "#") bn = bn - (i > 1 And next_ <= "#") If (i And 1) = 0 Then p2468 = p2468 & prev prev = next_ Next i If step = 2 Then p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2) End If Dim ret(2) As Variant ret(0) = wtb ret(1) = bn ret(2) = p2468 AB = ret End Function Private Sub Zhang_Suen(text As Variant) Dim wtb As Integer Dim bn As Integer Dim changed As Boolean, changes As Boolean Dim p2468 As String Dim x As Integer, y As Integer, step As Integer Do While True changed = False For step = 1 To 2 changes = False For y = 1 To UBound(text) - 1 For x = 2 To Len(text(y)) - 1 If Mid(text(y), x, 1) = "#" Then ret = AB(text, y, x, step) wtb = ret(0) bn = ret(1) p2468 = ret(2) If wtb = 1 _ And bn >= 2 And bn <= 6 _ And InStr(1, Mid(p2468, 1, 3), ".") _ And InStr(1, Mid(p2468, 2, 3), ".") Then changes = True text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x) End If End If Next x Next y If changes Then For y = 1 To UBound(text) - 1 text(y) = Replace(text(y), "!", ".") Next y changed = True End If Next step If Not changed Then Exit Do Loop Debug.Print Join(text, vbCrLf) End Sub Public Sub main() init Dim Small_rc(9) As String Small_rc(0) = "................................" Small_rc(1) = ".#########.......########......." Small_rc(2) = ".###...####.....####..####......" Small_rc(3) = ".###....###.....###....###......" Small_rc(4) = ".###...####.....###............." Small_rc(5) = ".#########......###............." Small_rc(6) = ".###.####.......###....###......" Small_rc(7) = ".###..####..###.####..####.###.." Small_rc(8) = ".###...####.###..########..###.." Small_rc(9) = "................................" Zhang_Suen (Small_rc) End Sub
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "}; final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, {0, 4, 6}}}; static List<Point> toWhite = new ArrayList<>(); static char[][] grid; public static void main(String[] args) { grid = new char[image.length][]; for (int r = 0; r < image.length; r++) grid[r] = image[r].toCharArray(); thinImage(); } static void thinImage() { boolean firstStep = false; boolean hasChanged; do { hasChanged = false; firstStep = !firstStep; for (int r = 1; r < grid.length - 1; r++) { for (int c = 1; c < grid[0].length - 1; c++) { if (grid[r][c] != '#') continue; int nn = numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (numTransitions(r, c) != 1) continue; if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; toWhite.add(new Point(c, r)); hasChanged = true; } } for (Point p : toWhite) grid[p.y][p.x] = ' '; toWhite.clear(); } while (firstStep || hasChanged); printResult(); } static int numNeighbors(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++; return count; } static int numTransitions(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++; } return count; } static boolean atLeastOneIsWhite(int r, int c, int step) { int count = 0; int[][] group = nbrGroups[step]; for (int i = 0; i < 2; i++) for (int j = 0; j < group[i].length; j++) { int[] nbr = nbrs[group[i][j]]; if (grid[r + nbr[1]][c + nbr[0]] == ' ') { count++; break; } } return count > 1; } static void printResult() { for (char[] row : grid) System.out.println(row); } }
Public n As Variant Private Sub init() n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}] End Sub Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant Dim wtb As Integer Dim bn As Integer Dim prev As String: prev = "#" Dim next_ As String Dim p2468 As String For i = 1 To UBound(n) next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1) wtb = wtb - (prev = "." And next_ <= "#") bn = bn - (i > 1 And next_ <= "#") If (i And 1) = 0 Then p2468 = p2468 & prev prev = next_ Next i If step = 2 Then p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2) End If Dim ret(2) As Variant ret(0) = wtb ret(1) = bn ret(2) = p2468 AB = ret End Function Private Sub Zhang_Suen(text As Variant) Dim wtb As Integer Dim bn As Integer Dim changed As Boolean, changes As Boolean Dim p2468 As String Dim x As Integer, y As Integer, step As Integer Do While True changed = False For step = 1 To 2 changes = False For y = 1 To UBound(text) - 1 For x = 2 To Len(text(y)) - 1 If Mid(text(y), x, 1) = "#" Then ret = AB(text, y, x, step) wtb = ret(0) bn = ret(1) p2468 = ret(2) If wtb = 1 _ And bn >= 2 And bn <= 6 _ And InStr(1, Mid(p2468, 1, 3), ".") _ And InStr(1, Mid(p2468, 2, 3), ".") Then changes = True text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x) End If End If Next x Next y If changes Then For y = 1 To UBound(text) - 1 text(y) = Replace(text(y), "!", ".") Next y changed = True End If Next step If Not changed Then Exit Do Loop Debug.Print Join(text, vbCrLf) End Sub Public Sub main() init Dim Small_rc(9) As String Small_rc(0) = "................................" Small_rc(1) = ".#########.......########......." Small_rc(2) = ".###...####.....####..####......" Small_rc(3) = ".###....###.....###....###......" Small_rc(4) = ".###...####.....###............." Small_rc(5) = ".#########......###............." Small_rc(6) = ".###.####.......###....###......" Small_rc(7) = ".###..####..###.####..####.###.." Small_rc(8) = ".###...####.###..########..###.." Small_rc(9) = "................................" Zhang_Suen (Small_rc) End Sub
Rewrite this program in VB while keeping its functionality equivalent to the Java version.
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5}; for (int i = 0; i < s.length; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) System.out.println(i); prev = curr; } int gprev = 0; for (int i = 0; i < s.length; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) System.out.println(i); gprev = curr; } } }
Option Strict On Option Explicit On Imports System.IO Module vMain Public Sub Main Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5} For i As Integer = 0 To Ubound(s) Dim curr As Integer = s(i) Dim prev As Integer If i > 1 AndAlso curr = prev Then Console.Out.WriteLine(i) End If prev = curr Next i End Sub End Module
Convert this Java snippet to VB and keep its semantics consistent.
int l = 300; void setup() { size(400, 400); background(0, 0, 255); stroke(255); translate(width/2.0, height/2.0); translate(-l/2.0, l*sqrt(3)/6.0); for (int i = 1; i <= 3; i++) { kcurve(0, l); rotate(radians(120)); translate(-l, 0); } } void kcurve(float x1, float x2) { float s = (x2-x1)/3; if (s < 5) { pushMatrix(); translate(x1, 0); line(0, 0, s, 0); line(2*s, 0, 3*s, 0); translate(s, 0); rotate(radians(60)); line(0, 0, s, 0); translate(s, 0); rotate(radians(-120)); line(0, 0, s, 0); popMatrix(); return; } pushMatrix(); translate(x1, 0); kcurve(0, s); kcurve(2*s, 3*s); translate(s, 0); rotate(radians(60)); kcurve(0, s); translate(s, 0); rotate(radians(-120)); kcurve(0, s); popMatrix(); }
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: if ori<0 then ori = ori+pi*2 end sub public sub lt(i): ori=(ori + i*iang) if ori>(pi*2) then ori=ori-pi*2 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 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 sub koch (n,le) if n=0 then x.fw le :exit sub koch n-1, le/3 x.lt 1 koch n-1, le/3 x.rt 2 koch n-1, le/3 x.lt 1 koch n-1, le/3 end sub dim x,i set x=new turtle x.iangle=60 x.orient=0 x.incr=3 x.x=100:x.y=300 for i=0 to 3 koch 7,100 x.rt 2 next set x=nothing
Write the same code in VB as shown below in Java.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class DrawAPixel extends JFrame{ public DrawAPixel() { super("Red Pixel"); setSize(320, 240); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void paint(Graphics g) { g.setColor(new Color(255, 0, 0)); g.drawRect(100, 100, 1, 1); } public static void main(String[] args) { new DrawAPixel(); } }
Sub draw() Dim sh As Shape, sl As Shape Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240) Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100) sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0) End Sub
Translate this program into VB but keep the logic exactly as in Java.
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { String line; while ((line = reader.readLine()) != null) { if (line.length() >= minLength) words.add(line); } } Collections.sort(words); String previousWord = null; int count = 0; for (int i = 0, n = words.size(); i + minLength <= n; ++i) { StringBuilder sb = new StringBuilder(minLength); for (int j = 0; j < minLength; ++j) sb.append(words.get(i + j).charAt(j)); String word = sb.toString(); if (word.equals(previousWord)) continue; if (Collections.binarySearch(words, word) >= 0) System.out.printf("%2d. %s\n", ++count, word); previousWord = word; } } catch (Exception e) { e.printStackTrace(); } } }
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d=createobject("scripting.dictionary") redim b(ubound(a)) i=0 for each x in a s=trim(x) if len(s)>=9 then if len(s)= 9 then d.add s,"" b(i)=s i=i+1 end if next redim preserve b(i-1) wscript.echo i j=1 for i=0 to ubound(b)-9 s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_ mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1) if d.exists(s9) then wscript.echo j,s9 d.remove(s9) j=j+1 end if next
Convert the following code from Java to VB, ensuring the logic remains intact.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
Convert this Java snippet to VB and keep its semantics consistent.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.nio.charset.StandardCharsets; import java.util.Formatter; public class UTF8EncodeDecode { public static byte[] utf8encode(int codepoint) { return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8); } public static int utf8decode(byte[] bytes) { return new String(bytes, StandardCharsets.UTF_8).codePointAt(0); } public static void main(String[] args) { System.out.printf("%-7s %-43s %7s\t%s\t%7s%n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded"); for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] encoded = utf8encode(codepoint); Formatter formatter = new Formatter(); for (byte b : encoded) { formatter.format("%02X ", b); } String encodedHex = formatter.toString(); int decoded = utf8decode(encoded); System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n", codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded); } } }
Private Function unicode_2_utf8(x As Long) As Byte() Dim y() As Byte Dim r As Long Select Case x Case 0 To &H7F ReDim y(0) y(0) = x Case &H80 To &H7FF ReDim y(1) y(0) = 192 + x \ 64 y(1) = 128 + x Mod 64 Case &H800 To &H7FFF ReDim y(2) y(2) = 128 + x Mod 64 r = x \ 64 y(1) = 128 + r Mod 64 y(0) = 224 + r \ 64 Case 32768 To 65535 ReDim y(2) y(2) = 128 + x Mod 64 r = x \ 64 y(1) = 128 + r Mod 64 y(0) = 224 + r \ 64 Case &H10000 To &H10FFFF ReDim y(3) y(3) = 128 + x Mod 64 r = x \ 64 y(2) = 128 + r Mod 64 r = r \ 64 y(1) = 128 + r Mod 64 y(0) = 240 + r \ 64 Case Else MsgBox "what else?" & x & " " & Hex(x) End Select unicode_2_utf8 = y End Function Private Function utf8_2_unicode(x() As Byte) As Long Dim first As Long, second As Long, third As Long, fourth As Long Dim total As Long Select Case UBound(x) - LBound(x) Case 0 If x(0) < 128 Then total = x(0) Else MsgBox "highest bit set error" End If Case 1 If x(0) \ 32 = 6 Then first = x(0) Mod 32 If x(1) \ 64 = 2 Then second = x(1) Mod 64 Else MsgBox "mask error" End If Else MsgBox "leading byte error" End If total = 64 * first + second Case 2 If x(0) \ 16 = 14 Then first = x(0) Mod 16 If x(1) \ 64 = 2 Then second = x(1) Mod 64 If x(2) \ 64 = 2 Then third = x(2) Mod 64 Else MsgBox "mask error last byte" End If Else MsgBox "mask error middle byte" End If Else MsgBox "leading byte error" End If total = 4096 * first + 64 * second + third Case 3 If x(0) \ 8 = 30 Then first = x(0) Mod 8 If x(1) \ 64 = 2 Then second = x(1) Mod 64 If x(2) \ 64 = 2 Then third = x(2) Mod 64 If x(3) \ 64 = 2 Then fourth = x(3) Mod 64 Else MsgBox "mask error last byte" End If Else MsgBox "mask error third byte" End If Else MsgBox "mask error second byte" End If Else MsgBox "mask error leading byte" End If total = CLng(262144 * first + 4096 * second + 64 * third + fourth) Case Else MsgBox "more bytes than expected" End Select utf8_2_unicode = total End Function Public Sub program() Dim cp As Variant Dim r() As Byte, s As String cp = [{65, 246, 1046, 8364, 119070}] Debug.Print "ch unicode UTF-8 encoded decoded" For Each cpi In cp r = unicode_2_utf8(CLng(cpi)) On Error Resume Next s = CStr(Hex(cpi)) Debug.Print ChrW(cpi); String$(10 - Len(s), " "); s, If Err.Number = 5 Then Debug.Print "?"; String$(10 - Len(s), " "); s, s = "" For Each yz In r s = s & CStr(Hex(yz)) & " " Next yz Debug.Print String$(13 - Len(s), " "); s; s = CStr(Hex(utf8_2_unicode(r))) Debug.Print String$(8 - Len(s), " "); s Next cpi End Sub