Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in C# while keeping its functionality equivalent to the Python version.
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return "Super(%s)" % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Super method' @staticmethod def supStatic(): return 'static method' class Other(object): def otherMethod(self): return 'other method' class Sub(Other, Super): def __init__(self, name, *args): super(Sub, self).__init__(name); self.rest = args; self.methods = {} def __dir__(self): return list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ + self.methods.keys() \ )) def __getattr__(self, name): if name in self.methods: if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0: if self.methods[name].__code__.co_varnames[0] == 'self': return self.methods[name].__get__(self, type(self)) if self.methods[name].__code__.co_varnames[0] == 'cls': return self.methods[name].__get__(type(self), type) return self.methods[name] raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __str__(self): return "Sub(%s)" % self.name def doSub(): return 'did sub stuff' @classmethod def cls(cls): return 'cls method (in Sub)' @classmethod def subCls(cls): return 'Sub method' @staticmethod def subStatic(): return 'Sub method' sup = Super('sup') sub = Sub('sub', 0, 'I', 'two') sub.methods['incr'] = lambda x: x+1 sub.methods['strs'] = lambda self, x: str(self) * x [method for method in dir(sub) if callable(getattr(sub, method))] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)] [method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)] inspect.getmembers(sub, predicate=inspect.ismethod) map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
using System; using System.Reflection; public class Rosetta { public static void Main() { BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; foreach (var method in typeof(TestForMethodReflection).GetMethods(flags)) Console.WriteLine(method); } class TestForMethodReflection { public void MyPublicMethod() {} private void MyPrivateMethod() {} public static void MyPublicStaticMethod() {} private static void MyPrivateStaticMethod() {} } }
Change the programming language of this snippet from Python to C# without modifying what it does.
var x = 0 var y = 0 There are also multi-line comments Everything inside of ] discard
Change the programming language of this snippet from Python to C# without modifying what it does.
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋' boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)] patterns = boxchar_single_width tiles = [] for row in reversed(minos): tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[0]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i + 1 idices = [[0]*9 for _ in range(9)] for i, j in product(range(9), range(9)): n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1]) idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:]))) return '\n'.join(''.join(patterns[i] for i in row) for row in idices) def tile(board=0, seq=tuple(), tiles=tiles): if not tiles: yield img(seq) return for c in tiles[0]: b = board | c tnext = [] for t in tiles[1:]: tnext.append(tuple(n for n in t if not n&b)) if not tnext[-1]: break else: yield from tile(b, seq + (c,), tnext) for x in tile(): print(x)
using System; using System.Linq; namespace PentominoTiling { class Program { static readonly char[] symbols = "FILNPTUVWXYZ-".ToCharArray(); static readonly int nRows = 8; static readonly int nCols = 8; static readonly int target = 12; static readonly int blank = 12; static int[][] grid = new int[nRows][]; static bool[] placed = new bool[target]; static void Main(string[] args) { var rand = new Random(); for (int r = 0; r < nRows; r++) grid[r] = Enumerable.Repeat(-1, nCols).ToArray(); for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.Next(nRows); randCol = rand.Next(nCols); } while (grid[randRow][randCol] == blank); grid[randRow][randCol] = blank; } if (Solve(0, 0)) { PrintResult(); } else { Console.WriteLine("no solution"); } Console.ReadKey(); } private static void PrintResult() { foreach (int[] r in grid) { foreach (int i in r) Console.Write("{0} ", symbols[i]); Console.WriteLine(); } } private static bool Solve(int pos, int numPlaced) { if (numPlaced == target) return true; int row = pos / nCols; int col = pos % nCols; if (grid[row][col] != -1) return Solve(pos + 1, numPlaced); for (int i = 0; i < shapes.Length; i++) { if (!placed[i]) { foreach (int[] orientation in shapes[i]) { if (!TryPlaceOrientation(orientation, row, col, i)) continue; placed[i] = true; if (Solve(pos + 1, numPlaced + 1)) return true; RemoveOrientation(orientation, row, col); placed[i] = false; } } } return false; } private static void RemoveOrientation(int[] orientation, int row, int col) { grid[row][col] = -1; for (int i = 0; i < orientation.Length; i += 2) grid[row + orientation[i]][col + orientation[i + 1]] = -1; } private static bool TryPlaceOrientation(int[] orientation, int row, int col, int shapeIndex) { for (int i = 0; i < orientation.Length; i += 2) { int x = col + orientation[i + 1]; int y = row + orientation[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; } grid[row][col] = shapeIndex; for (int i = 0; i < orientation.Length; i += 2) grid[row + orientation[i]][col + orientation[i + 1]] = shapeIndex; return true; } static readonly int[][] F = { new int[] {1, -1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 1}, new int[] {1, 0, 1, 1, 2, -1, 2, 0}, new int[] {1, -2, 1, -1, 1, 0, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 1}, new int[] {1, -1, 1, 0, 1, 1, 2, -1}, new int[] {1, -1, 1, 0, 2, 0, 2, 1}}; static readonly int[][] I = { new int[] { 0, 1, 0, 2, 0, 3, 0, 4 }, new int[] { 1, 0, 2, 0, 3, 0, 4, 0 } }; static readonly int[][] L = { new int[] {1, 0, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, 0, 3, -1, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 3}, new int[] {0, 1, 1, 0, 2, 0, 3, 0}, new int[] {0, 1, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 0, 3, 1, 0}, new int[] {1, 0, 2, 0, 3, 0, 3, 1}, new int[] {1, -3, 1, -2, 1, -1, 1, 0}}; static readonly int[][] N = { new int[] {0, 1, 1, -2, 1, -1, 1, 0}, new int[] {1, 0, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 1, -1, 1, 0}, new int[] {1, 0, 2, 0, 2, 1, 3, 1}, new int[] {0, 1, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, -1, 2, 0, 3, -1}, new int[] {0, 1, 0, 2, 1, 2, 1, 3}, new int[] {1, -1, 1, 0, 2, -1, 3, -1}}; static readonly int[][] P = { new int[] {0, 1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 0, 2, 1, 0, 1, 1}, new int[] {1, 0, 1, 1, 2, 0, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 1, 1}, new int[] {0, 1, 1, 0, 1, 1, 1, 2}, new int[] {1, -1, 1, 0, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 1, 1, 2, 0}}; static readonly int[][] T = { new int[] {0, 1, 0, 2, 1, 1, 2, 1}, new int[] {1, -2, 1, -1, 1, 0, 2, 0}, new int[] {1, 0, 2, -1, 2, 0, 2, 1}, new int[] {1, 0, 1, 1, 1, 2, 2, 0}}; static readonly int[][] U = { new int[] {0, 1, 0, 2, 1, 0, 1, 2}, new int[] {0, 1, 1, 1, 2, 0, 2, 1}, new int[] {0, 2, 1, 0, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 2, 0, 2, 1}}; static readonly int[][] V = { new int[] {1, 0, 2, 0, 2, 1, 2, 2}, new int[] {0, 1, 0, 2, 1, 0, 2, 0}, new int[] {1, 0, 2, -2, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 2, 2, 2}}; static readonly int[][] W = { new int[] {1, 0, 1, 1, 2, 1, 2, 2}, new int[] {1, -1, 1, 0, 2, -2, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, -1, 1, 0, 2, -1}}; static readonly int[][] X = { new int[] { 1, -1, 1, 0, 1, 1, 2, 0 } }; static readonly int[][] Y = { new int[] {1, -2, 1, -1, 1, 0, 1, 1}, new int[] {1, -1, 1, 0, 2, 0, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 1}, new int[] {1, 0, 2, 0, 2, 1, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 2}, new int[] {1, 0, 1, 1, 2, 0, 3, 0}, new int[] {1, -1, 1, 0, 1, 1, 1, 2}, new int[] {1, 0, 2, -1, 2, 0, 3, 0}}; static readonly int[][] Z = { new int[] {0, 1, 1, 0, 2, -1, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, 1, 2, 1, 2, 2}, new int[] {1, -2, 1, -1, 1, 0, 2, -2}}; static readonly int[][][] shapes = { F, I, L, N, P, T, U, V, W, X, Y, Z }; } }
Change the programming language of this snippet from Python to C# without modifying what it does.
class Example(object): def foo(self, x): return 42 + x name = "foo" getattr(Example(), name)(5)
using System; class Example { public int foo(int x) { return 42 + x; } } class Program { static void Main(string[] args) { var example = new Example(); var method = "foo"; var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 }); Console.WriteLine("{0}(5) = {1}", method, result); } }
Preserve the algorithm and functionality while converting the code from Python to C#.
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
int j;
Please provide an equivalent version of this Python code in C#.
from numpy import ndarray from math import isqrt def pritchard(limit): members = ndarray(limit + 1, dtype=bool) members.fill(False) members[1] = True steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2 primes = [] while prime <= rtlim: if steplength < limit: for w in range(1, len(members)): if members[w]: n = w + steplength while n <= nlimit: members[n] = True n += steplength steplength = nlimit np = 5 mcpy = members.copy() for w in range(1, len(members)): if mcpy[w]: if np == 5 and w > prime: np = w n = prime * w if n > nlimit: break members[n] = False if np < prime: break primes.append(prime) prime = 3 if prime == 2 else np nlimit = min(steplength * prime, limit) newprimes = [i for i in range(2, len(members)) if members[i]] return sorted(primes + newprimes) print(pritchard(150)) print('Number of primes up to 1,000,000:', len(pritchard(1000000)))
using System; using System.Collections.Generic; class Program { static List<int> PrimesUpTo(int limit, bool verbose = false) { var sw = System.Diagnostics.Stopwatch.StartNew(); var members = new SortedSet<int>{ 1 }; int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1; List<int> primes = new List<int>(), tl = new List<int>(); while (prime < rtlim) { nl = Math.Min(prime * stp, limit); if (stp < limit) { tl.Clear(); foreach (var w in members) for (n = w + stp; n <= nl; n += stp) tl.Add(n); members.UnionWith(tl); ac += tl.Count; } stp = nl; nxtpr = 5; tl.Clear(); foreach (var w in members) { if (nxtpr == 5 && w > prime) nxtpr = w; if ((n = prime * w) > nl) break; else tl.Add(n); } foreach (var itm in tl) members.Remove(itm); rc += tl.Count; primes.Add(prime); prime = prime == 2 ? 3 : nxtpr; } members.Remove(1); primes.AddRange(members); sw.Stop(); if (verbose) Console.WriteLine("Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds); return primes; } static void Main(string[] args) { Console.WriteLine("[{0}]", string.Join(", ", PrimesUpTo(150, true))); PrimesUpTo(1000000, true); } }
Preserve the algorithm and functionality while converting the code from Python to C#.
import math import random INFINITY = 1 << 127 MAX_INT = 1 << 31 class Parameters: def __init__(self, omega, phip, phig): self.omega = omega self.phip = phip self.phig = phig class State: def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims): self.iter = iter self.gbpos = gbpos self.gbval = gbval self.min = min self.max = max self.parameters = parameters self.pos = pos self.vel = vel self.bpos = bpos self.bval = bval self.nParticles = nParticles self.nDims = nDims def report(self, testfunc): print "Test Function :", testfunc print "Iterations  :", self.iter print "Global Best Position :", self.gbpos print "Global Best Value  : %.16f" % self.gbval def uniform01(): v = random.random() assert 0.0 <= v and v < 1.0 return v def psoInit(min, max, parameters, nParticles): nDims = len(min) pos = [min[:]] * nParticles vel = [[0.0] * nDims] * nParticles bpos = [min[:]] * nParticles bval = [INFINITY] * nParticles iter = 0 gbpos = [INFINITY] * nDims gbval = INFINITY return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); def pso(fn, y): p = y.parameters v = [0.0] * (y.nParticles) bpos = [y.min[:]] * (y.nParticles) bval = [0.0] * (y.nParticles) gbpos = [0.0] * (y.nDims) gbval = INFINITY for j in xrange(0, y.nParticles): v[j] = fn(y.pos[j]) if v[j] < y.bval[j]: bpos[j] = y.pos[j][:] bval[j] = v[j] else: bpos[j] = y.bpos[j][:] bval[j] = y.bval[j] if bval[j] < gbval: gbval = bval[j] gbpos = bpos[j][:] rg = uniform01() pos = [[None] * (y.nDims)] * (y.nParticles) vel = [[None] * (y.nDims)] * (y.nParticles) for j in xrange(0, y.nParticles): rp = uniform01() ok = True vel[j] = [0.0] * (len(vel[j])) pos[j] = [0.0] * (len(pos[j])) for k in xrange(0, y.nDims): vel[j][k] = p.omega * y.vel[j][k] \ + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \ + p.phig * rg * (gbpos[k] - y.pos[j][k]) pos[j][k] = y.pos[j][k] + vel[j][k] ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k] if not ok: for k in xrange(0, y.nDims): pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01() iter = 1 + y.iter return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); def iterate(fn, n, y): r = y old = y if n == MAX_INT: while True: r = pso(fn, r) if r == old: break old = r else: for _ in xrange(0, n): r = pso(fn, r) return r def mccormick(x): (a, b) = x return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a def michalewicz(x): m = 10 d = len(x) sum = 0.0 for i in xrange(1, d): j = x[i - 1] k = math.sin(i * j * j / math.pi) sum += math.sin(j) * k ** (2.0 * m) return -sum def main(): state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100) state = iterate(mccormick, 40, state) state.report("McCormick") print "f(-.54719, -1.54719) : %.16f" % (mccormick([-.54719, -1.54719])) print state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000) state = iterate(michalewicz, 30, state) state.report("Michalewicz (2D)") print "f(2.20, 1.57)  : %.16f" % (michalewicz([2.2, 1.57])) main()
using System; namespace ParticleSwarmOptimization { public struct Parameters { public double omega, phip, phig; public Parameters(double omega, double phip, double phig) : this() { this.omega = omega; this.phip = phip; this.phig = phig; } } public struct State { public int iter; public double[] gbpos; public double gbval; public double[] min; public double[] max; public Parameters parameters; public double[][] pos; public double[][] vel; public double[][] bpos; public double[] bval; public int nParticles; public int nDims; public State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) : this() { this.iter = iter; this.gbpos = gbpos; this.gbval = gbval; this.min = min; this.max = max; this.parameters = parameters; this.pos = pos; this.vel = vel; this.bpos = bpos; this.bval = bval; this.nParticles = nParticles; this.nDims = nDims; } public void Report(string testfunc) { Console.WriteLine("Test Function  : {0}", testfunc); Console.WriteLine("Iterations  : {0}", iter); Console.WriteLine("Global Best Position : {0}", string.Join(", ", gbpos)); Console.WriteLine("Global Best Value  : {0}", gbval); } } class Program { public static State PsoInit(double[] min, double[] max, Parameters parameters, int nParticles) { var nDims = min.Length; double[][] pos = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { pos[i] = new double[min.Length]; min.CopyTo(pos[i], 0); } double[][] vel = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { vel[i] = new double[nDims]; } double[][] bpos = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { bpos[i] = new double[min.Length]; min.CopyTo(bpos[i], 0); } double[] bval = new double[nParticles]; for (int i = 0; i < nParticles; i++) { bval[i] = double.PositiveInfinity; } int iter = 0; double[] gbpos = new double[nDims]; for (int i = 0; i < nDims; i++) { gbpos[i] = double.PositiveInfinity; } double gbval = double.PositiveInfinity; return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); } static Random r = new Random(); public static State Pso(Func<double[], double> fn, State y) { var p = y.parameters; double[] v = new double[y.nParticles]; double[][] bpos = new double[y.nParticles][]; for (int i = 0; i < y.nParticles; i++) { bpos[i] = new double[y.min.Length]; y.min.CopyTo(bpos[i], 0); } double[] bval = new double[y.nParticles]; double[] gbpos = new double[y.nDims]; double gbval = double.PositiveInfinity; for (int j = 0; j < y.nParticles; j++) { v[j] = fn.Invoke(y.pos[j]); if (v[j] < y.bval[j]) { y.pos[j].CopyTo(bpos[j], 0); bval[j] = v[j]; } else { y.bpos[j].CopyTo(bpos[j], 0); bval[j] = y.bval[j]; } if (bval[j] < gbval) { gbval = bval[j]; bpos[j].CopyTo(gbpos, 0); } } double rg = r.NextDouble(); double[][] pos = new double[y.nParticles][]; double[][] vel = new double[y.nParticles][]; for (int i = 0; i < y.nParticles; i++) { pos[i] = new double[y.nDims]; vel[i] = new double[y.nDims]; } for (int j = 0; j < y.nParticles; j++) { double rp = r.NextDouble(); bool ok = true; for (int k = 0; k < y.nDims; k++) { vel[j][k] = 0.0; pos[j][k] = 0.0; } for (int k = 0; k < y.nDims; k++) { vel[j][k] = p.omega * y.vel[j][k] + p.phip * rp * (bpos[j][k] - y.pos[j][k]) + p.phig * rg * (gbpos[k] - y.pos[j][k]); pos[j][k] = y.pos[j][k] + vel[j][k]; ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]; } if (!ok) { for (int k = 0; k < y.nDims; k++) { pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.NextDouble(); } } } var iter = 1 + y.iter; return new State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); } public static State Iterate(Func<double[], double> fn, int n, State y) { State r = y; if (n == int.MaxValue) { State old = y; while (true) { r = Pso(fn, r); if (r.Equals(old)) break; old = r; } } else { for (int i = 0; i < n; i++) { r = Pso(fn, r); } } return r; } public static double Mccormick(double[] x) { var a = x[0]; var b = x[1]; return Math.Sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a; } public static double Michalewicz(double[] x) { int m = 10; int d = x.Length; double sum = 0.0; for (int i = 1; i < d; i++) { var j = x[i - 1]; var k = Math.Sin(i * j * j / Math.PI); sum += Math.Sin(j) * Math.Pow(k, 2.0 * m); } return -sum; } static void Main(string[] args) { var state = PsoInit( new double[] { -1.5, -3.0 }, new double[] { 4.0, 4.0 }, new Parameters(0.0, 0.6, 0.3), 100 ); state = Iterate(Mccormick, 40, state); state.Report("McCormick"); Console.WriteLine("f(-.54719, -1.54719) : {0}", Mccormick(new double[] { -.54719, -1.54719 })); Console.WriteLine(); state = PsoInit( new double[] { -0.0, -0.0 }, new double[] { Math.PI, Math.PI }, new Parameters(0.3, 0.3, 0.3), 1000 ); state = Iterate(Michalewicz, 30, state); state.Report("Michalewicz (2D)"); Console.WriteLine("f(2.20, 1.57)  : {0}", Michalewicz(new double[] { 2.20, 1.57 })); } } }
Change the programming language of this snippet from Python to C# without modifying what it does.
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
Change the programming language of this snippet from Python to C# without modifying what it does.
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
Produce a functionally identical C# code for the snippet given in Python.
class empty(object): pass e = empty()
using System; using System.Dynamic; namespace DynamicClassVariable { internal static class Program { #region Static Members private static void Main() { dynamic sampleObj = new ExpandoObject(); sampleObj.bar = 1; Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } }
Change the following VB code into Java without altering its purpose.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant  : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
Generate an equivalent Java version of this VB code.
Imports System.Math Module RayCasting Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}} Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}} Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}} Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}} Private shapes As Integer()()() = {square, squareHole, strange, hexagon} Public Sub Main() Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}} For Each shape As Integer()() In shapes For Each point As Double() In testPoints Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7))) Next Console.WriteLine() Next End Sub Private Function Contains(shape As Integer()(), point As Double()) As Boolean Dim inside As Boolean = False Dim length As Integer = shape.Length For i As Integer = 0 To length - 1 If Intersects(shape(i), shape((i + 1) Mod length), point) Then inside = Not inside End If Next Return inside End Function Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean If a(1) > b(1) Then Return Intersects(b, a, p) If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001 If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False If p(0) < Min(a(0), b(0)) Then Return True Dim red As Double = (p(1) - a(1)) / (p(0) - a(0)) Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0)) Return red >= blue End Function End Module
import static java.lang.Math.*; public class RayCasting { static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P); if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
Function CountSubstring(str,substr) CountSubstring = 0 For i = 1 To Len(str) If Len(str) >= Len(substr) Then If InStr(i,str,substr) Then CountSubstring = CountSubstring + 1 i = InStr(i,str,substr) + Len(substr) - 1 End If Else Exit For End If Next End Function WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
public class CountSubstring { public static int countSubstring(String subStr, String str){ return (str.length() - str.replace(subStr, "").length()) / subStr.length(); } public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("abab", "ababababab")); System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); } }
Write the same code in Java as shown below in VB.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
Please provide an equivalent version of this VB code in Java.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
Port the provided VB code into Java while preserving the original functionality.
Imports System.IO Module Notes Function Main(ByVal cmdArgs() As String) As Integer Try If cmdArgs.Length = 0 Then Using sr As New StreamReader("NOTES.TXT") Console.WriteLine(sr.ReadToEnd) End Using Else Using sw As New StreamWriter("NOTES.TXT", True) sw.WriteLine(Date.Now.ToString()) sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs)) End Using End If Catch End Try End Function End Module
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
Write a version of this VB function in Java with identical behavior.
Public Function CommonDirectoryPath(ParamArray Paths()) As String Dim v As Variant Dim Path() As String, s As String Dim i As Long, j As Long, k As Long Const PATH_SEPARATOR As String = "/" For Each v In Paths ReDim Preserve Path(0 To i) Path(i) = v i = i + 1 Next v k = 1 Do For i = 0 To UBound(Path) If i Then If InStr(k, Path(i), PATH_SEPARATOR) <> j Then Exit Do ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then Exit Do End If Else j = InStr(k, Path(i), PATH_SEPARATOR) If j = 0 Then Exit Do End If End If Next i s = Left$(Path(0), j + CLng(k <> 1)) k = j + 1 Loop CommonDirectoryPath = s End Function Sub Main() Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/home/user1/tmp" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members", _ "/home/user1/abc/coven/members") = _ "/home/user1" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/hope/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/" End Sub
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
Generate an equivalent Java version of this VB code.
Option Explicit sub verifydistribution(calledfunction, samples, delta) Dim i, n, maxdiff Dim d : Set d = CreateObject("Scripting.Dictionary") wscript.echo "Running """ & calledfunction & """ " & samples & " times..." for i = 1 to samples Execute "n = " & calledfunction d(n) = d(n) + 1 next n = d.Count maxdiff = 0 wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets." for each i in d.Keys dim diff : diff = abs(1 - d(i) / (samples/n)) if diff > maxdiff then maxdiff = diff wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _ & vbTab & " difference from expected=" & FormatPercent(diff, 2) next wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _ & ", desired limit is " & FormatPercent(delta, 2) & "." if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!" end sub
import static java.lang.Math.abs; import java.util.*; import java.util.function.IntSupplier; public class Test { static void distCheck(IntSupplier f, int nRepeats, double delta) { Map<Integer, Integer> counts = new HashMap<>(); for (int i = 0; i < nRepeats; i++) counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1); double target = nRepeats / (double) counts.size(); int deltaCount = (int) (delta / 100.0 * target); counts.forEach((k, v) -> { if (abs(target - v) >= deltaCount) System.out.printf("distribution potentially skewed " + "for '%s': '%d'%n", k, v); }); counts.keySet().stream().sorted().forEach(k -> System.out.printf("%d %d%n", k, counts.get(k))); } public static void main(String[] a) { distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1); } }
Can you help me rewrite this code in Java instead of VB, keeping it the same logically?
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Write a version of this VB function in Java with identical behavior.
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Convert this VB snippet to Java and keep its semantics consistent.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Port the provided VB code into Java while preserving the original functionality.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Convert this VB block to Java, preserving its control flow and logic.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
Translate the given VB code snippet into Java without altering its behavior.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
Keep all operations the same but rewrite the snippet in Java.
Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine If r.Test(line) Then WScript.StdOut.WriteLine "IP Version " &_ ver & ": " & r.Replace(line,"$1") End If Loop End Function Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Convert this VB snippet to Java and keep its semantics consistent.
Const WIDTH = 243 Dim n As Long Dim points() As Single Dim flag As Boolean Private Sub lineto(x As Integer, y As Integer) If flag Then points(n, 1) = x points(n, 2) = y End If n = n + 1 End Sub Private Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _ ByVal i1 As Integer, ByVal i2 As Integer) If (lg = 1) Then Call lineto(x * 3, y * 3) Exit Sub End If lg = lg / 3 Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Call Peano(x + lg, y + lg, lg, i1, 1 - i2) Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub Sub main() n = 1: flag = False Call Peano(0, 0, WIDTH, 0, 0) ReDim points(1 To n - 1, 1 To 2) n = 1: flag = True Call Peano(0, 0, WIDTH, 0, 0) ActiveSheet.Shapes.AddPolyline points End Sub
import java.io.*; public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.currentX = length; s.currentY = length; s.lineLength = length; s.begin(656); s.execute(rewrite(4)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private PeanoCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = "L"; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'L') sb.append("LFRFL-F-RFLFR+F+LFRFL"); else if (ch == 'R') sb.append("RFLFR+F+LFRFL-F-RFLFR"); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final int ANGLE = 90; }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print "Chi-squared test for given frequencies" Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Private Function Dice5() As Integer Dice5 = Int(5 * Rnd + 1) End Function Private Function Dice7() As Integer Dim i As Integer Do i = 5 * (Dice5 - 1) + Dice5 Loop While i > 21 Dice7 = i Mod 7 + 1 End Function Sub TestDice7() Dim i As Long, roll As Integer Dim Bins(1 To 7) As Variant For i = 1 To 1000000 roll = Dice7 Bins(roll) = Bins(roll) + 1 Next i Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """" End Sub
import java.util.Random; public class SevenSidedDice { private static final Random rnd = new Random(); public static void main(String[] args) { SevenSidedDice now=new SevenSidedDice(); System.out.println("Random number from 1 to 7: "+now.seven()); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1+rnd.nextInt(5); } }
Keep all operations the same but rewrite the snippet in Java.
Imports System, System.Console Module Module1 Dim np As Boolean() Sub ms(ByVal lmt As Long) np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True Dim n As Integer = 2, j As Integer = 1 : While n < lmt If Not np(n) Then Dim k As Long = CLng(n) * n While k < lmt : np(CInt(k)) = True : k += n : End While End If : n += j : j = 2 : End While End Sub Function is_Mag(ByVal n As Integer) As Boolean Dim res, rm As Integer, p As Integer = 10 While n >= p res = Math.DivRem(n, p, rm) If np(res + rm) Then Return False p = p * 10 : End While : Return True End Function Sub Main(ByVal args As String()) ms(100_009) : Dim mn As String = " magnanimous numbers:" WriteLine("First 45{0}", mn) : Dim l As Integer = 0, c As Integer = 0 While c < 400 : If is_Mag(l) Then c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, "{0,4} ", "{0,8:n0} "), l) If c < 45 AndAlso c Mod 15 = 0 Then WriteLine() If c = 240 Then WriteLine(vbLf & vbLf & "241st through 250th{0}", mn) If c = 390 Then WriteLine(vbLf & vbLf & "391st through 400th{0}", mn) End If : l += 1 : End While End Sub End Module
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
Convert the following code from VB to Java, ensuring the logic remains intact.
Option Explicit Sub Main() Dim Primes() As Long, n As Long, temp$ Dim t As Single t = Timer n = 133218295 Primes = ListPrimes(n) Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _ Format(Timer - t, "0.000 s") & ", " & _ Format(UBound(Primes) + 1, "#,##0") & " primes numbers." For n = 0 To 19 temp = temp & ", " & Primes(n) Next Debug.Print "First twenty primes : "; Mid(temp, 3) n = 0: temp = vbNullString Do While Primes(n) < 100 n = n + 1 Loop Do While Primes(n) < 150 temp = temp & ", " & Primes(n) n = n + 1 Loop Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3) Dim ccount As Long n = 0 Do While Primes(n) < 7700 n = n + 1 Loop Do While Primes(n) < 8000 ccount = ccount + 1 n = n + 1 Loop Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount n = 1 Do While n <= 100000 n = n * 10 Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0") Loop Debug.Print "VBA has a limit in array Debug.Print "With my computer, the limit for an array of Long is : 133 218 295" Debug.Print "The last prime I could find is the : " & _ Format(UBound(Primes), "#,##0") & "th, Value : " & _ Format(Primes(UBound(Primes)), "#,##0") End Sub Function ListPrimes(MAX As Long) As Long() Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long ReDim t(2 To MAX) ReDim L(MAX \ 2) s = Sqr(MAX) For i = 3 To s Step 2 If t(i) = False Then For j = i * i To MAX Step i t(j) = True Next End If Next i L(0) = 2 For i = 3 To MAX Step 2 If t(i) = False Then c = c + 1 L(c) = i End If Next i ReDim Preserve L(c) ListPrimes = L End Function
import java.util.*; public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0; public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); } public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); } public int count() { return count_; } private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } } private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); } private static int nextOddNumber(int n) { return 1 + 2 * (n/2); } public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
Write the same code in Java as shown below in VB.
Module Program Sub Main() Console.WriteLine("Enter two space-delimited integers:") Dim input = Console.ReadLine().Split() Dim rows = Integer.Parse(input(0)) Dim cols = Integer.Parse(input(1)) Dim arr(rows - 1, cols - 1) As Integer arr(0, 0) = 2 Console.WriteLine(arr(0, 0)) End Sub End Module
import java.util.Scanner; public class twoDimArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nbr1 = in.nextInt(); int nbr2 = in.nextInt(); double[][] array = new double[nbr1][nbr2]; array[0][0] = 42.0; System.out.println("The number at place [0 0] is " + array[0][0]); } }
Please provide an equivalent version of this VB code in Java.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Generate a Java translation of this VB snippet without changing its computational steps.
Option Explicit Sub Main() Const VECSIZE As Long = 3350 Const BUFSIZE As Long = 201 Dim buffer(1 To BUFSIZE) As Long Dim vect(1 To VECSIZE) As Long Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long For n = 1 To VECSIZE vect(n) = 2 Next n For n = 1 To BUFSIZE karray = 0 For l = VECSIZE To 1 Step -1 num = 100000 * vect(l) + karray * l karray = num \ (2 * l - 1) vect(l) = num - karray * (2 * l - 1) Next l k = karray \ 100000 buffer(n) = more + k more = karray - k * 100000 Next n Debug.Print CStr(buffer(1)); Debug.Print "." l = 0 For n = 2 To BUFSIZE Debug.Print Format$(buffer(n), "00000"); l = l + 1 If l = 10 Then l = 0 Debug.Print End If Next n End Sub
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
Transform the following VB implementation into Java, maintaining the same output and logic.
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Can you help me rewrite this code in Java instead of VB, keeping it the same logically?
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Change the programming language of this snippet from VB to Java without modifying what it does.
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Please provide an equivalent version of this VB code in Java.
Type Contact Name As String firstname As String Age As Byte End Type Function SetContact(N As String, Fn As String, A As Byte) As Contact SetContact.Name = N SetContact.firstname = Fn SetContact.Age = A End Function Sub Test_SetContact() Dim Cont As Contact Cont = SetContact("SMITH", "John", 23) Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old." End Sub
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
Maintain the same structure and functionality when rewriting this code in Java.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
Rewrite the snippet below in Java so it works the same as the original VB code.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Change the following VB code into Java without altering its purpose.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Rewrite the snippet below in Java so it works the same as the original VB code.
For i = 1 To 10 Console.Write(i) If i Mod 5 = 0 Then Console.WriteLine() Else Console.Write(", ") End If Next
for(int i = 1;i <= 10; i++){ System.out.print(i); if(i % 5 == 0){ System.out.println(); continue; } System.out.print(", "); }
Maintain the same structure and functionality when rewriting this code in Java.
Option Base 1 Private Function pivotize(m As Variant) As Variant Dim n As Integer: n = UBound(m) Dim im() As Double ReDim im(n, n) For i = 1 To n For j = 1 To n im(i, j) = 0 Next j im(i, i) = 1 Next i For i = 1 To n mx = Abs(m(i, i)) row_ = i For j = i To n If Abs(m(j, i)) > mx Then mx = Abs(m(j, i)) row_ = j End If Next j If i <> Row Then For j = 1 To n tmp = im(i, j) im(i, j) = im(row_, j) im(row_, j) = tmp Next j End If Next i pivotize = im End Function Private Function lu(a As Variant) As Variant Dim n As Integer: n = UBound(a) Dim l() As Double ReDim l(n, n) For i = 1 To n For j = 1 To n l(i, j) = 0 Next j Next i u = l p = pivotize(a) a2 = WorksheetFunction.MMult(p, a) For j = 1 To n l(j, j) = 1# For i = 1 To j sum1 = 0# For k = 1 To i sum1 = sum1 + u(k, j) * l(i, k) Next k u(i, j) = a2(i, j) - sum1 Next i For i = j + 1 To n sum2 = 0# For k = 1 To j sum2 = sum2 + u(k, j) * l(i, k) Next k l(i, j) = (a2(i, j) - sum2) / u(j, j) Next i Next j Dim res(4) As Variant res(1) = a res(2) = l res(3) = u res(4) = p lu = res End Function Public Sub main() a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print result(i)(j, k), Next k Debug.Print Next j Debug.Print Next i a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print Format(result(i)(j, k), "0.#####"), Next k Debug.Print Next j Debug.Print Next i End Sub
import static java.util.Arrays.stream; import java.util.Locale; import static java.util.stream.IntStream.range; public class Test { static double dotProduct(double[] a, double[] b) { return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum(); } static double[][] matrixMul(double[][] A, double[][] B) { double[][] result = new double[A.length][B[0].length]; double[] aux = new double[B.length]; for (int j = 0; j < B[0].length; j++) { for (int k = 0; k < B.length; k++) aux[k] = B[k][j]; for (int i = 0; i < A.length; i++) result[i][j] = dotProduct(A[i], aux); } return result; } static double[][] pivotize(double[][] m) { int n = m.length; double[][] id = range(0, n).mapToObj(j -> range(0, n) .mapToDouble(i -> i == j ? 1 : 0).toArray()) .toArray(double[][]::new); for (int i = 0; i < n; i++) { double maxm = m[i][i]; int row = i; for (int j = i; j < n; j++) if (m[j][i] > maxm) { maxm = m[j][i]; row = j; } if (i != row) { double[] tmp = id[i]; id[i] = id[row]; id[row] = tmp; } } return id; } static double[][][] lu(double[][] A) { int n = A.length; double[][] L = new double[n][n]; double[][] U = new double[n][n]; double[][] P = pivotize(A); double[][] A2 = matrixMul(P, A); for (int j = 0; j < n; j++) { L[j][j] = 1; for (int i = 0; i < j + 1; i++) { double s1 = 0; for (int k = 0; k < i; k++) s1 += U[k][j] * L[i][k]; U[i][j] = A2[i][j] - s1; } for (int i = j; i < n; i++) { double s2 = 0; for (int k = 0; k < j; k++) s2 += U[k][j] * L[i][k]; L[i][j] = (A2[i][j] - s2) / U[j][j]; } } return new double[][][]{L, U, P}; } static void print(double[][] m) { stream(m).forEach(a -> { stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n)); System.out.println(); }); System.out.println(); } public static void main(String[] args) { double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}}; double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1}, {2.0, 5, 7, 1}}; for (double[][] m : lu(a)) print(m); System.out.println(); for (double[][] m : lu(b)) print(m); } }
Please provide an equivalent version of this VB code in Java.
Option Explicit Private Type Choice Number As Integer Name As String End Type Private MaxNumber As Integer Sub Main() Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$ MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1) For i = 1 To 3 U(i) = UserChoice Next For i = 1 To MaxNumber t = vbNullString For j = 1 To 3 If i Mod U(j).Number = 0 Then t = t & U(j).Name Next Debug.Print IIf(t = vbNullString, i, t) Next i End Sub Private Function UserChoice() As Choice Dim ok As Boolean Do While Not ok UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1) UserChoice.Name = InputBox("Enter the corresponding word : ") If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True Loop End Function
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
Preserve the algorithm and functionality while converting the code from VB to Java.
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)
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)"); } } } }
Port the following code from VB to Java with equivalent syntax and logic.
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)
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)"); } } } }
Generate a Java translation of this VB snippet without changing its computational steps.
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
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")); } } }
Produce a language-to-language conversion: from VB to Java, same semantics.
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
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("äàâáçñßæεбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
Convert this VB block to Java, preserving its control flow and logic.
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
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]); } } }
Change the programming language of this snippet from VB to Java without modifying what it does.
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
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); } } }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
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
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)); } }
Translate this program into Java but keep the logic exactly as in VB.
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
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)); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
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
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); } }
Rewrite the snippet below in Java so it works the same as the original VB code.
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
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(); } }
Change the programming language of this snippet from VB to Java without modifying what it does.
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
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."); } }
Keep all operations the same but rewrite the snippet in Java.
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
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."); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
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
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}"); } }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
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
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(); }
Port the provided VB code into Java while preserving the original functionality.
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
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(); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
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
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; } } } }
Convert this VB block to Java, preserving its control flow and logic.
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
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
Change the programming language of this snippet from VB to Java without modifying what it does.
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
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(); } }
Write a version of this VB function in Java with identical behavior.
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
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 ) ); } } }
Transform the following VB implementation into Java, maintaining the same output and logic.
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
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 + " "); } }
Translate the given VB code snippet into Java without altering its behavior.
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
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); } }
Translate the given VB code snippet into Java without altering its behavior.
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
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); } }
Port the following code from VB to Java with equivalent syntax and logic.
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
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()) ; } }
Produce a language-to-language conversion: from VB to Java, same semantics.
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")
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; } }
Write the same algorithm in Java as shown in this VB implementation.
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
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); } }); } }
Can you help me rewrite this code in Java instead of VB, keeping it the same logically?
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
String dog = "Benjamin"; String Dog = "Samba"; String DOG = "Bernie"; @Inject Console console; console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
Port the following code from VB to Java with equivalent syntax and logic.
For i = 10 To 0 Step -1 Debug.Print i Next i
for (int i = 10; i >= 0; i--) { System.out.println(i); }
Port the provided VB code into Java while preserving the original functionality.
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
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"); } } }
Convert the following code from VB to Java, ensuring the logic remains intact.
Public OutConsole As Scripting.TextStream For i = 0 To 4 For j = 0 To i OutConsole.Write "*" Next j OutConsole.WriteLine Next i
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); }
Please provide an equivalent version of this VB code in Java.
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
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); } }
Keep all operations the same but rewrite the snippet in Java.
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
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); } }
Convert this VB block to Java, preserving its control flow and logic.
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"
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); } } }
Generate an equivalent Java version of this VB code.
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
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; } }
Write a version of this VB function in Java with identical behavior.
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
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; } }
Please provide an equivalent version of this VB code in Java.
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
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); } } }
Rewrite this program in Java while keeping its functionality equivalent to the VB version.
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
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")); } }
Write the same code in Java as shown below in VB.
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
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")); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
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
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; } }
Maintain the same structure and functionality when rewriting this code in Java.
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
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; } }
Write the same code in Java as shown below in VB.
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
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); }
Please provide an equivalent version of this VB code in Java.
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
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(); } } }
Translate this program into Java but keep the logic exactly as in VB.
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
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); } }
Preserve the algorithm and functionality while converting the code from VB to Java.
Function transpose(m As Variant) As Variant transpose = WorksheetFunction.transpose(m) End Function
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)); } } }
Rewrite the snippet below in Java so it works the same as the original VB code.
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
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(); } } } }
Translate this program into Java but keep the logic exactly as in VB.
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
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); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
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
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); } }
Can you help me rewrite this code in Java instead of VB, keeping it the same logically?
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
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(); } }); } }
Produce a language-to-language conversion: from VB to Java, same semantics.
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
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; }
Rewrite the snippet below in Java so it works the same as the original VB code.
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
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(); } }
Transform the following VB implementation into Java, maintaining the same output and logic.
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
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); } }
Write a version of this VB function in Java with identical behavior.
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
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(); } } }
Please provide an equivalent version of this VB code in Java.
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
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(); } } }
Translate this program into Java but keep the logic exactly as in VB.
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
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); } }
Convert the following code from VB to Java, ensuring the logic remains intact.
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
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); } }
Preserve the algorithm and functionality while converting the code from VB to Java.
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
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); }