Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in Lua as shown below in Java.
public class Tau { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; ...
function divisor_count(n) local total = 1 while (n & 1) == 0 do total = total + 1 n = n >> 1 end local p = 3 while p * p <= n do local count = 1 while n % p == 0 do count = count + 1 n = math.floor(n / p) end total = ...
Write the same code in Lua as shown below in Java.
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...
function prime_digits_sum_13(n) local sum = 0 while n > 0 do local r = n % 10 if r ~= 2 and r ~= 3 and r ~= 5 and r ~= 7 then return false end n = math.floor(n / 10) sum = sum + r end return sum == 13 end local c = 0 for i=1,999999 do if prime_dig...
Write the same code in Lua as shown below in Java.
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...
function prime_digits_sum_13(n) local sum = 0 while n > 0 do local r = n % 10 if r ~= 2 and r ~= 3 and r ~= 5 and r ~= 7 then return false end n = math.floor(n / 10) sum = sum + r end return sum == 13 end local c = 0 for i=1,999999 do if prime_dig...
Generate an equivalent Lua version of this Java code.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class DeepCopy { public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center"...
function _deepcopy(o, tables) if type(o) ~= 'table' then return o end if tables[o] ~= nil then return tables[o] end local new_o = {} tables[o] = new_o for k, v in next, o, nil do local new_k = _deepcopy(k, tables) local new_v = _deepcopy(v, tables) new_o[new_k] = new_v end ...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class DeepCopy { public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center"...
function _deepcopy(o, tables) if type(o) ~= 'table' then return o end if tables[o] ~= nil then return tables[o] end local new_o = {} tables[o] = new_o for k, v in next, o, nil do local new_k = _deepcopy(k, tables) local new_v = _deepcopy(v, tables) new_o[new_k] = new_v end ...
Change the programming language of this snippet from Java to Lua without modifying what it does.
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0...
local function isprime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end for f = 5, math.sqrt(n), 6 do if n % f == 0 or n % (f+2) == 0 then return false end end return true end local function iscircularprime(p) local n = math.floor(math.log10(p))...
Can you help me rewrite this code in Lua instead of Java, keeping it the same logically?
import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class PermutationSort { public static void main(String[] args) { int[] a={3,2,1,8,9,4,6}; System.out.println("Unsorted: " + Arrays.toString(a)); a=pSort(a); System.out.println("Sorted: " + Arrays.toString(a)); } public stat...
function permute (list) local function perm (list, n) if n == 0 then coroutine.yield(list) end for i = 1, n do list[i], list[n] = list[n], list[i] perm(list, n - 1) list[i], list[n] = list[n], list[i] end end return coroutine.wrap(function() perm(list, #list) end) end function inO...
Translate this program into Lua but keep the logic exactly as in Java.
import java.math.BigInteger; public class IntegerRoots { private static BigInteger iRoot(BigInteger base, int n) { if (base.compareTo(BigInteger.ZERO) < 0 || n <= 0) { throw new IllegalArgumentException(); } int n1 = n - 1; BigInteger n2 = BigInteger.valueOf(n); ...
function root(base, n) if base < 2 then return base end if n == 0 then return 1 end local n1 = n - 1 local n2 = n local n3 = n1 local c = 1 local d = math.floor((n3 + base) / n2) local e = math.floor((n3 * d + base / math.pow(d, n1)) / n2) while c ~= d and c ~= e do c = d ...
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
import java.math.BigInteger; public class IntegerRoots { private static BigInteger iRoot(BigInteger base, int n) { if (base.compareTo(BigInteger.ZERO) < 0 || n <= 0) { throw new IllegalArgumentException(); } int n1 = n - 1; BigInteger n2 = BigInteger.valueOf(n); ...
function root(base, n) if base < 2 then return base end if n == 0 then return 1 end local n1 = n - 1 local n2 = n local n3 = n1 local c = 1 local d = math.floor((n3 + base) / n2) local e = math.floor((n3 * d + base / math.pow(d, n1)) / n2) while c ~= d and c ~= e do c = d ...
Write the same algorithm in Lua as shown in this Java implementation.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
#!/usr/bin/env lua function meaningoflife() return 42 end function main(arg) print("Main: The meaning of life is " .. meaningoflife()) end if type(package.loaded[(...)]) ~= "userdata" then main(arg) else module(..., package.seeall) end
Port the following code from Java to Lua with equivalent syntax and logic.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
#!/usr/bin/env lua function meaningoflife() return 42 end function main(arg) print("Main: The meaning of life is " .. meaningoflife()) end if type(package.loaded[(...)]) ~= "userdata" then main(arg) else module(..., package.seeall) end
Produce a language-to-language conversion: from Java to Lua, same semantics.
public class NicePrimes { private static boolean isPrime(long n) { if (n < 2) { return false; } if (n % 2 == 0L) { return n == 2L; } if (n % 3 == 0L) { return n == 3L; } var p = 5L; while (p * p <= n) { ...
function isPrime(n) if n < 2 then return false end if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end local p = 5 while p * p <= n do if n % p == 0 then return false end p = p + 2 if n % p == 0 th...
Transform the following Java implementation into Lua, maintaining the same output and logic.
public class NicePrimes { private static boolean isPrime(long n) { if (n < 2) { return false; } if (n % 2 == 0L) { return n == 2L; } if (n % 3 == 0L) { return n == 3L; } var p = 5L; while (p * p <= n) { ...
function isPrime(n) if n < 2 then return false end if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end local p = 5 while p * p <= n do if n % p == 0 then return false end p = p + 2 if n % p == 0 th...
Change the following Java code into Lua without altering its purpose.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31...
function isLeapYear (y) return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0 end function dayOfWeek (y, m, d) local t = os.time({year = y, month = m, day = d}) return os.date("%A", t) end function lastWeekdays (wday, year) local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} if...
Generate a Lua translation of this Java snippet without changing its computational steps.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31...
function isLeapYear (y) return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0 end function dayOfWeek (y, m, d) local t = os.time({year = y, month = m, day = d}) return os.date("%A", t) end function lastWeekdays (wday, year) local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} if...
Ensure the translated Lua code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } }...
function turn(base, n) local sum = 0 while n ~= 0 do local re = n % base n = math.floor(n / base) sum = sum + re end return sum % base end function fairShare(base, count) io.write(string.format("Base %2d:", base)) for i=1,count do local t = turn(base, i - 1) ...
Maintain the same structure and functionality when rewriting this code in Lua.
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream; public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); } private static boolean isEsthetic(long n, long b) { if (n == 0) { ...
function to(n, b) local BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" if n == 0 then return "0" end local ss = "" while n > 0 do local idx = (n % b) + 1 n = math.floor(n / b) ss = ss .. BASE:sub(idx, idx) end return string.reverse(ss) end function isEstheti...
Convert this Java snippet to Lua and keep its semantics consistent.
package org.rosettacode.java; import java.util.Arrays; import java.util.stream.IntStream; public class HeapsAlgorithm { public static void main(String[] args) { Object[] array = IntStream.range(0, 4) .boxed() .toArray(); HeapsAlgorithm algorithm = new HeapsAlgorithm(); algorithm.recursive(array); Sy...
_JT={} function JT(dim) local n={ values={}, positions={}, directions={}, sign=1 } setmetatable(n,{__index=_JT}) for i=1,dim do n.values[i]=i n.positions[i]=i n.directions[i]=-1 end return n end function _JT:largestMobile() for i=#self.values,1,-1 do local loc=self.positions[i]+self.directi...
Port the provided Java code into Lua while preserving the original functionality.
import java.util.Arrays; public class Kolakoski { private static class Crutch { final int len; int[] s; int i; Crutch(int len) { this.len = len; s = new int[len]; i = 0; } void repeat(int count) { for (int j = 0; j < ...
function next_in_cycle(c,length,index) local pos = index % length return c[pos] end function kolakoski(c,s,clen,slen) local i = 0 local k = 0 while true do s[i] = next_in_cycle(c,clen,k) if s[k] > 1 then for j=1,s[k]-1 do i = i + 1 if i =...
Convert the following code from Java to Lua, ensuring the logic remains intact.
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>(); for (E x : n) { Node<E> node = new Node<E>(); node.value = x; int i = Collections.binarySearch(pileTops, ...
function buildLIS(seq) local piles = { { {table.remove(seq, 1), nil} } } while #seq>0 do local x=table.remove(seq, 1) for j=1,#piles do if piles[j][#piles[j]][1]>x then table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])}) break elseif ...
Preserve the algorithm and functionality while converting the code from Java to Lua.
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { ...
wordlist, wordhash = {}, {} for word in io.open("unixdict.txt", "r"):lines() do if #word >= 9 then wordlist[#wordlist+1] = word wordhash[word] = #wordlist end end for n = 1, #wordlist-8 do local word = "" for i = 0, 8 do word = word .. wordlist[n+i]:sub(i+1,i+1) end if wordhash[word] then ...
Change the programming language of this snippet from Java to Lua without modifying what it does.
public static void main(String... args){ HashMap<String, Integer> vars = new HashMap<String, Integer>(); vars.put("Variable name", 3); vars.put("Next variable name", 5); Scanner sc = new Scanner(System.in); String str = sc.next(); vars.put(str,...
_G[io.read()] = 5
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
import java.util.Arrays; import java.util.BitSet; import org.apache.commons.lang3.ArrayUtils; public class OrderDisjointItems { public static void main(String[] args) { final String[][] MNs = {{"the cat sat on the mat", "mat cat"}, {"the cat sat on the mat", "cat mat"}, {"A B C A B C A B C...
function split (str) local t = {} for word in str:gmatch("%S+") do table.insert(t, word) end return t end function orderList (dataStr, orderStr) local data, order = split(dataStr), split(orderStr) for orderPos, orderWord in pairs(order) do for dataPos, dataWord in pairs(data) do ...
Convert this Java snippet to Lua and keep its semantics consistent.
public static void main(String[] args) { System.out.println(concat("Rosetta", "Code", ":")); } public static String concat(String a, String b, String c) { return a + c + c + b; } Rosetta::Code
$ lua Lua 5.1.2 Copyright (C) 1994-2007 Lua.org, PUC-Rio > function conc(a, b, c) >> return a..c..c..b >> end > print(conc("Rosetta", "Code", ":")) Rosetta::Code >
Convert the following code from Java to Lua, ensuring the logic remains intact.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class...
code = loadstring"return x^2" val1 = setfenv(code, {x = io.read() + 0})() val2 = setfenv(code, {x = io.read() + 0})() print(val2 - val1)
Can you help me rewrite this code in Lua instead of Java, keeping it the same logically?
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class...
code = loadstring"return x^2" val1 = setfenv(code, {x = io.read() + 0})() val2 = setfenv(code, {x = io.read() + 0})() print(val2 - val1)
Ensure the translated Lua code behaves exactly like the original Java snippet.
public class ReallyLameTranslationOfJ { public static void main(String[] args) { String s = "She was a soul stripper. She took my heart!"; System.out.println(cheapTrick(s)); System.out.println(cheapTrick(cheapTrick(s))); } static String cheapTrick(String s) { if (s.contains...
function sufficient(s) local xref = { She="He", He="She" } return (s:gsub("(%w+)", function(s) return xref[s] or s end)) end s = "She was a soul stripper. She took my heart!" print(sufficient(s)) print(sufficient(sufficient(s))) print(sufficient(sufficient(s)) == s)
Produce a functionally identical Lua code for the snippet given in Java.
public class ReallyLameTranslationOfJ { public static void main(String[] args) { String s = "She was a soul stripper. She took my heart!"; System.out.println(cheapTrick(s)); System.out.println(cheapTrick(cheapTrick(s))); } static String cheapTrick(String s) { if (s.contains...
function sufficient(s) local xref = { She="He", He="She" } return (s:gsub("(%w+)", function(s) return xref[s] or s end)) end s = "She was a soul stripper. She took my heart!" print(sufficient(s)) print(sufficient(sufficient(s))) print(sufficient(sufficient(s)) == s)
Produce a functionally identical Lua code for the snippet given in Java.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.Fo...
f = loadstring(s) one = loadstring"return 1" two = loadstring"return ..."
Please provide an equivalent version of this Java code in Lua.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.Fo...
f = loadstring(s) one = loadstring"return 1" two = loadstring"return ..."
Maintain the same structure and functionality when rewriting this code in Lua.
import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) throws IOException { final int endOfFile = -1; try ( FileReader reader = new FileReader("input.txt", StandardCharsets.UTF_8) ) { while (...
function is_ascii (str) return string.match(str, "[\0-\x7F]") end function is_init (str) return string.match(str, "[\xC2-\xF4]") end function is_cont (str) return string.match(str, "[\x80-\xBF]") end function read_char (file) local multibyte for c in file:lines(1) do if is_ascii(c) t...
Port the provided Java code into Lua while preserving the original functionality.
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; ...
Bitmap.render = function(self) for y = 1, self.height do print(table.concat(self.pixels[y], " ")) end end math.randomseed(os.time()) local W, H, MIDX = 15, 40, 7 local bitmap = Bitmap(W, H) local AIR, PIN, BALL, FLOOR = ".", "▲", "☻", "■" local nballs, balls = 60, {} local frame, showEveryFrame = 1, false b...
Convert this Java block to Lua, preserving its control flow and logic.
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toS...
function innerCircle (t, lo, hi, swaps) if lo == hi then return swaps end local high, low, mid = hi, lo, math.floor((hi - lo) / 2) while lo < hi do if t[lo] > t[hi] then t[lo], t[hi] = t[hi], t[lo] swaps = swaps + 1 end lo = lo + 1 hi = hi - 1 end if lo == hi then if t[lo] > t...
Transform the following Java implementation into Lua, maintaining the same output and logic.
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cas...
local function wrapEachItem(items, prefix, suffix) local itemsWrapped = {} for i, item in ipairs(items) do itemsWrapped[i] = prefix .. item .. suffix end return itemsWrapped end local function getAllItemCombinationsConcatenated(aItems, bItems) local combinations = {} for _, a in ipairs(aItems) do for _, b...
Ensure the translated Lua code behaves exactly like the original Java snippet.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
function distance(p1, p2) local dx = (p1.x-p2.x) local dy = (p1.y-p2.y) return math.sqrt(dx*dx + dy*dy) end function findCircles(p1, p2, radius) local seperation = distance(p1, p2) if seperation == 0.0 then if radius == 0.0 then print("No circles can be drawn through ("..p1.x.."...
Produce a functionally identical Lua code for the snippet given in Java.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
function distance(p1, p2) local dx = (p1.x-p2.x) local dy = (p1.y-p2.y) return math.sqrt(dx*dx + dy*dy) end function findCircles(p1, p2, radius) local seperation = distance(p1, p2) if seperation == 0.0 then if radius == 0.0 then print("No circles can be drawn through ("..p1.x.."...
Please provide an equivalent version of this Java code in Lua.
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arr...
function initN() local n = {} for i=1,15 do n[i] = {} for j=1,11 do n[i][j] = " " end n[i][6] = "x" end return n end function horiz(n, c1, c2, r) for c=c1,c2 do n[r+1][c+1] = "x" end end function verti(n, r1, r2, c) for r=r1,r2 do ...
Generate an equivalent Lua version of this Java code.
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arr...
function initN() local n = {} for i=1,15 do n[i] = {} for j=1,11 do n[i][j] = " " end n[i][6] = "x" end return n end function horiz(n, c1, c2, r) for c=c1,c2 do n[r+1][c+1] = "x" end end function verti(n, r1, r2, c) for r=r1,r2 do ...
Write the same algorithm in Lua as shown in this Java implementation.
import java.util.Arrays; import java.util.Collections; import java.util.HashSet; public class PokerHandAnalyzer { final static String faces = "AKQJT98765432"; final static String suits = "HDSC"; final static String[] deck = buildDeck(); public static void main(String[] args) { System.out.prin...
function valid (t) if #t ~= 5 then return false end for k, v in pairs(t) do for key, card in pairs(t) do if v.value == card.value and v.suit == card.suit and k ~= key then return false end end end retur...
Maintain the same structure and functionality when rewriting this code in Lua.
import java.util.Arrays; import java.util.Collections; import java.util.HashSet; public class PokerHandAnalyzer { final static String faces = "AKQJT98765432"; final static String suits = "HDSC"; final static String[] deck = buildDeck(); public static void main(String[] args) { System.out.prin...
function valid (t) if #t ~= 5 then return false end for k, v in pairs(t) do for key, card in pairs(t) do if v.value == card.value and v.suit == card.suit and k ~= key then return false end end end retur...
Convert this Java snippet to Lua and keep its semantics consistent.
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n)...
RIGHT, LEFT, UP, DOWN = 1, 2, 4, 8 function drawFractals( w ) love.graphics.setCanvas( canvas ) love.graphics.clear() love.graphics.setColor( 255, 255, 255 ) local dir, facing, lineLen, px, py, c = RIGHT, UP, 1, 10, love.graphics.getHeight() - 20, 1 local x, y = 0, -lineLen local pts = {} ta...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.util.*; public class PenneysGame { public static void main(String[] args) { Random rand = new Random(); String compChoice = "", playerChoice; if (rand.nextBoolean()) { for (int i = 0; i < 3; i++) compChoice += "HT".charAt(rand.nextInt(2)); ...
function penny_game() local player, computer = "", "" function player_choose() io.write( "Enter your sequence of three H and/or T: " ) local t = io.read():upper() if #t > 3 then t = t:sub( 1, 3 ) elseif #t < 3 then return "" end for i = 1, 3 do c = t:...
Write a version of this Java function in Lua with identical behavior.
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 le...
function sierpinski (tri, order) local new, p, t = {} if order > 0 then for i = 1, #tri do p = i + 2 if p > #tri then p = p - #tri end new[i] = (tri[i] + tri[p]) / 2 end sierpinski({tri[1],tri[2],new[1],new[2],new[5],new[6]}, order-1) sierpins...
Convert this Java block to Lua, preserving its control flow and logic.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting le...
function sierpinski (tri, order) local new, p, t = {} if order > 0 then for i = 1, #tri do p = i + 2 if p > #tri then p = p - #tri end new[i] = (tri[i] + tri[p]) / 2 end sierpinski({tri[1],tri[2],new[1],new[2],new[5],new[6]}, order-1) sierpins...
Rewrite the snippet below in Lua so it works the same as the original Java code.
import java.util.*; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; public class Nonoblock { public static void main(String[] args) { printBlock("21", 5); printBlock("", 5); printBlock("8", 10); printBlock("2323", 15); printBlock("23...
local examples = { {5, {2, 1}}, {5, {}}, {10, {8}}, {15, {2, 3, 2, 3}}, {5, {2, 3}}, } function deep (blocks, iBlock, freedom, str) if iBlock == #blocks then for takenFreedom = 0, freedom do print (str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. string.rep("0", freedom - takenFreed...
Change the programming language of this snippet from Java to Lua without modifying what it does.
import java.util.*; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; public class Nonoblock { public static void main(String[] args) { printBlock("21", 5); printBlock("", 5); printBlock("8", 10); printBlock("2323", 15); printBlock("23...
local examples = { {5, {2, 1}}, {5, {}}, {10, {8}}, {15, {2, 3, 2, 3}}, {5, {2, 3}}, } function deep (blocks, iBlock, freedom, str) if iBlock == #blocks then for takenFreedom = 0, freedom do print (str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. string.rep("0", freedom - takenFreed...
Can you help me rewrite this code in Lua instead of Java, keeping it the same logically?
import java.util.List; public class Main { private static class Range { int start; int end; boolean print; public Range(int s, int e, boolean p) { start = s; end = e; print = p; } } public static void main(String[] args) { ...
function makeInterval(s,e,p) return {start=s, end_=e, print_=p} end function main() local intervals = { makeInterval( 2, 1000, true), makeInterval(1000, 4000, true), makeInterval( 2, 10000, false), makeInterval( 2, 1000000, false), makeInterval(...
Produce a language-to-language conversion: from Java to Lua, same semantics.
import java.util.List; public class Main { private static class Range { int start; int end; boolean print; public Range(int s, int e, boolean p) { start = s; end = e; print = p; } } public static void main(String[] args) { ...
function makeInterval(s,e,p) return {start=s, end_=e, print_=p} end function main() local intervals = { makeInterval( 2, 1000, true), makeInterval(1000, 4000, true), makeInterval( 2, 10000, false), makeInterval( 2, 1000000, false), makeInterval(...
Maintain the same structure and functionality when rewriting this code in Lua.
public class Test { static boolean valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) if (nuts % n != 1) return false; return nuts != 0 && (nuts % n == 0); } public static void main(String[] args) { int x = 0; for (int n ...
function valid(n,nuts) local k = n local i = 0 while k ~= 0 do if (nuts % n) ~= 1 then return false end k = k - 1 nuts = nuts - 1 - math.floor(nuts / n) end return nuts ~= 0 and (nuts % n == 0) end for n=2, 9 do local x = 0 while not valid(n, x) d...
Can you help me rewrite this code in Lua instead of Java, keeping it the same logically?
public class Test { static boolean valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) if (nuts % n != 1) return false; return nuts != 0 && (nuts % n == 0); } public static void main(String[] args) { int x = 0; for (int n ...
function valid(n,nuts) local k = n local i = 0 while k ~= 0 do if (nuts % n) ~= 1 then return false end k = k - 1 nuts = nuts - 1 - math.floor(nuts / n) end return nuts ~= 0 and (nuts % n == 0) end for n=2, 9 do local x = 0 while not valid(n, x) d...
Write a version of this Java function in Lua with identical behavior.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
c = string.char midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96) midi = midi .. "MTrk" .. c(0,0,0,8*8+4) for _,note in ipairs{60,62,64,65,67,69,71,72} do midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0) end midi = midi .. c(0, 0xFF, 0x2F, 0) file = io.open("scale.mid", "wb") file:write(midi) file:close() mid...
Transform the following Java implementation into Lua, maintaining the same output and logic.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
c = string.char midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96) midi = midi .. "MTrk" .. c(0,0,0,8*8+4) for _,note in ipairs{60,62,64,65,67,69,71,72} do midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0) end midi = midi .. c(0, 0xFF, 0x2F, 0) file = io.open("scale.mid", "wb") file:write(midi) file:close() mid...
Produce a language-to-language conversion: from Java to Lua, same semantics.
import java.awt.*; import java.awt.event.ActionEvent; import javax.swing.*; public class PolySpiral extends JPanel { double inc = 0; public PolySpiral() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(40, (ActionEvent e) -> { inc = (inc +...
function love.load () love.window.setTitle("Polyspiral") incr = 0 end function love.update (dt) incr = (incr + 0.05) % 360 x1 = love.graphics.getWidth() / 2 y1 = love.graphics.getHeight() / 2 length = 5 angle = incr end function love.draw () for i = 1, 150 do x2 = x1 + math.cos...
Change the following Java code into Lua without altering its purpose.
import java.awt.*; import java.awt.event.ActionEvent; import javax.swing.*; public class PolySpiral extends JPanel { double inc = 0; public PolySpiral() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(40, (ActionEvent e) -> { inc = (inc +...
function love.load () love.window.setTitle("Polyspiral") incr = 0 end function love.update (dt) incr = (incr + 0.05) % 360 x1 = love.graphics.getWidth() / 2 y1 = love.graphics.getHeight() / 2 length = 5 angle = incr end function love.draw () for i = 1, 150 do x2 = x1 + math.cos...
Produce a functionally identical Lua code for the snippet given in Java.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { st...
function love.load( ) love.math.setRandomSeed( os.time( ) ) keys = { } number_cells = 50 voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells ) end function hypot( x, y ) return math.sqrt( x*x + y*y ) end function generateVoronoi( width, height, num_cells ) ...
Produce a functionally identical Lua code for the snippet given in Java.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { st...
function love.load( ) love.math.setRandomSeed( os.time( ) ) keys = { } number_cells = 50 voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells ) end function hypot( x, y ) return math.sqrt( x*x + y*y ) end function generateVoronoi( width, height, num_cells ) ...
Preserve the algorithm and functionality while converting the code from Java to Lua.
import java.text.DecimalFormat; public class AnglesNormalizationAndConversion { public static void main(String[] args) { DecimalFormat formatAngle = new DecimalFormat("######0.000000"); DecimalFormat formatConv = new DecimalFormat("###0.0000"); System.out.printf(" ...
range = { degrees=360, gradians=400, mils=6400, radians=2.0*math.pi } function convert(value, fromunit, tounit) return math.fmod(value * range[tounit] / range[fromunit], range[tounit]) end testvalues = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 } testunits = { "degrees", "gradians", "mils"...
Ensure the translated Lua code behaves exactly like the original Java snippet.
import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class XMLPars...
require 'lxp' data = [[<inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitatio...
Change the programming language of this snippet from Java to Lua without modifying what it does.
import java.util.HashMap; import java.util.Map; import java.util.regex.*; public class StraddlingCheckerboard { final static String[] keyvals = {"H:0", "O:1", "L:2", "M:4", "E:5", "S:6", "R:8", "T:9", "A:30", "B:31", "C:32", "D:33", "F:34", "G:35", "I:36", "J:37", "K:38", "N:39", "P:70", "Q:71", "...
local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" } local dicE, dicD, s1, s2 = {}, {}, 0, 0 function dec( txt ) local i, numb, s, t, c = 1, false while( i < #txt ) do c = txt:sub( i, i ) if not numb then if tonumber( c ) == s1 then i = i + 1; s = string.format( ...
Change the following Java code into Lua without altering its purpose.
import java.io.BufferedReader; import java.io.FileReader; public class IbeforeE { public static void main(String[] args) { IbeforeE now=new IbeforeE(); String wordlist="unixdict.txt"; if(now.isPlausibleRule(wordlist)) System.out.println("Rule is plausible."); else System.out.println("Rule is not plaus...
local http = require("socket.http") function count (pattern, wordList) local total = 0 for word in wordList:gmatch("%S+") do if word:match(pattern) then total = total + 1 end end return total end function plaus (case, opposite, words) if count(case, words) > 2 * count(opposite, words) t...
Convert the following code from Java to Lua, ensuring the logic remains intact.
import java.io.BufferedReader; import java.io.FileReader; public class IbeforeE { public static void main(String[] args) { IbeforeE now=new IbeforeE(); String wordlist="unixdict.txt"; if(now.isPlausibleRule(wordlist)) System.out.println("Rule is plausible."); else System.out.println("Rule is not plaus...
local http = require("socket.http") function count (pattern, wordList) local total = 0 for word in wordList:gmatch("%S+") do if word:match(pattern) then total = total + 1 end end return total end function plaus (case, opposite, words) if count(case, words) > 2 * count(opposite, words) t...
Keep all operations the same but rewrite the snippet in Lua.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AbelianSandpile { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Frame frame = new Frame(); frame.setVisible(true); ...
local sandpile = { init = function(self, dim, val) self.cell, self.dim = {}, dim for r = 1, dim do self.cell[r] = {} for c = 1, dim do self.cell[r][c] = 0 end end self.cell[math.floor(dim/2)+1][math.floor(dim/2)+1] = val end, iter = function(self) local dim, cel, more...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AbelianSandpile { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Frame frame = new Frame(); frame.setVisible(true); ...
local sandpile = { init = function(self, dim, val) self.cell, self.dim = {}, dim for r = 1, dim do self.cell[r] = {} for c = 1, dim do self.cell[r][c] = 0 end end self.cell[math.floor(dim/2)+1][math.floor(dim/2)+1] = val end, iter = function(self) local dim, cel, more...
Write a version of this Java function in Lua with identical behavior.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class NextHighestIntFromDigits { public static void main(String[] args) { for ( String s : new String[] {"0", ...
unpack = unpack or table.unpack function nexthighestint(n) local digits, index = {}, {[0]={},{},{},{},{},{},{},{},{},{}} for d in tostring(n):gmatch("%d") do digits[#digits+1]=tonumber(d) end for i,d in ipairs(digits) do index[d][#index[d]+1]=i end local function findswap(i,d) for D=d+1,9 do for I...
Please provide an equivalent version of this Java code in Lua.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class NextHighestIntFromDigits { public static void main(String[] args) { for ( String s : new String[] {"0", ...
unpack = unpack or table.unpack function nexthighestint(n) local digits, index = {}, {[0]={},{},{},{},{},{},{},{},{},{}} for d in tostring(n):gmatch("%d") do digits[#digits+1]=tonumber(d) end for i,d in ipairs(digits) do index[d][#index[d]+1]=i end local function findswap(i,d) for D=d+1,9 do for I...
Convert this Java snippet to Lua and keep its semantics consistent.
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { ...
local oneslist = { [0]="", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" } local teenlist = { [0]="ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" } local tenslist = { [0]="", "", "twenty", "thirty", "forty", "fifty", "sixty", "sevent...
Translate the given Java code snippet into Lua without altering its behavior.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees0...
Bitmap.chaosgame = function(self, n, r, niters) local w, h, vertices = self.width, self.height, {} for i = 1, n do vertices[i] = { x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n), y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n) } end local x, y = w/2, h/2 for i = 1, niters do ...
Translate the given Java code snippet into Lua without altering its behavior.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", ...
function zhangSuenThin(img) local dirs={ { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}, { 0,-1}, } local black=1 local white=0 function A(x, y) local c=0 local current=img[y+dirs[1][2]]...
Please provide an equivalent version of this Java code in Lua.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().repl...
function randomInsert (t, str, left, right) local pos repeat pos = math.random(left, right) until not t[pos] t[pos] = str return pos end function chess960 () local t, b1, b2 = {} local kingPos = randomInsert(t, "K", 2, 7) randomInsert(t, "R", 1, kingPos - 1) randomInsert(t, "R", kingP...
Convert the following code from Java to Lua, ensuring the logic remains intact.
import java.util.*; import java.awt.geom.*; public class LineCircleIntersection { public static void main(String[] args) { try { demo(); } catch (Exception e) { e.printStackTrace(); } } private static void demo() throws NoninvertibleTransformException { ...
EPS = 1e-14 function pts(p) local x, y = p.x, p.y if x == 0 then x = 0 end if y == 0 then y = 0 end return "(" .. x .. ", " .. y .. ")" end function lts(pl) local str = "[" for i,p in pairs(pl) do if i > 1 then str = str .. ", " end s...
Rewrite the snippet below in Lua so it works the same as the original Java code.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
require"lpeg" P, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V expression = P{"expr"; ws = P" "^0, number = C(R"09"^1) * V"ws", lp = "(" * V"ws", rp = ")" * V"ws", sym = C(S"+-*/") * V"ws", more = (V"sym" * V"expr")^0, expr = V"number" * V"more" + V"lp" * lpeg.Ct(V"expr" * V"more") * V"rp" * V"more"} functio...
Keep all operations the same but rewrite the snippet in Lua.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
require"lpeg" P, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V expression = P{"expr"; ws = P" "^0, number = C(R"09"^1) * V"ws", lp = "(" * V"ws", rp = ")" * V"ws", sym = C(S"+-*/") * V"ws", more = (V"sym" * V"expr")^0, expr = V"number" * V"more" + V"lp" * lpeg.Ct(V"expr" * V"more") * V"rp" * V"more"} functio...
Maintain the same structure and functionality when rewriting this code in Lua.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class FixCodeTags { public static void main(String[] args) { String sourcefile=args[0]; String convertedfile=args[1]; convert(sourcefile,convertedfile); } static String[] languages = {"abap", "a...
langs = {'ada', 'cpp-qt', 'pascal', 'lscript', 'z80', 'visualprolog', 'html4strict', 'cil', 'objc', 'asm', 'progress', 'teraterm', 'hq9plus', 'genero', 'tsql', 'email', 'pic16', 'tcl', 'apt_sources', 'io', 'apache', 'vhdl', 'avisynth', 'winbatch', 'vbnet', 'ini', 'scilab', 'ocaml-brief', 'sas', 'actionscript3', 'qbasi...
Change the following Java code into Lua without altering its purpose.
import java.util.Map; import java.util.Random; public class Game { private static final Map<Integer, Integer> snl = Map.ofEntries( Map.entry(4, 14), Map.entry(9, 31), Map.entry(17, 7), Map.entry(20, 38), Map.entry(28, 84), Map.entry(40, 59), Map.entry(51, 67)...
local sixesThrowAgain = true function rollDice() return math.random(6) end function nextSquare(square) if square == 4 then return 14 elseif square == 9 then return 31 elseif square == 17 then return 7 elseif square == 20 then return 38 elseif square == 28 then ...
Generate an equivalent Lua version of this Java code.
import java.util.Map; import java.util.Random; public class Game { private static final Map<Integer, Integer> snl = Map.ofEntries( Map.entry(4, 14), Map.entry(9, 31), Map.entry(17, 7), Map.entry(20, 38), Map.entry(28, 84), Map.entry(40, 59), Map.entry(51, 67)...
local sixesThrowAgain = true function rollDice() return math.random(6) end function nextSquare(square) if square == 4 then return 14 elseif square == 9 then return 31 elseif square == 17 then return 7 elseif square == 20 then return 38 elseif square == 28 then ...
Preserve the algorithm and functionality while converting the code from Java to Lua.
module shop.acme.com { const Point(Int x, Int y); enum Color {Red, Green, Blue} interface Callback { Boolean active; void onEvent(String event); void onError(Exception e); } String DefaultLogin = "guest"; Int MAX_QUANTITY = 100; ...
local DISTANCE_MAXIMUM = 1 local distance_to_target = 0 local function distanceToTarget() end local function TargetFactory() end for _,v in ipairs(table) do print(v) end
Preserve the algorithm and functionality while converting the code from Java to Lua.
import java.util.TreeSet; public class Farey{ private static class Frac implements Comparable<Frac>{ int num; int den; public Frac(int num, int den){ this.num = num; this.den = den; } @Override public String toString(){ return num + "/" + den; } @Override public int compareTo(Frac o){ ...
function farey (n) local a, b, c, d, k = 0, 1, 1, n local farTab = {{a, b}} while c <= n do k = math.floor((n + b) / d) a, b, c, d = c, d, k * c - a, k * d - b table.insert(farTab, {a, b}) end return farTab end for i = 1, 11 do io.write(i .. ": ") for _, frac in pa...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.util.TreeSet; public class Farey{ private static class Frac implements Comparable<Frac>{ int num; int den; public Frac(int num, int den){ this.num = num; this.den = den; } @Override public String toString(){ return num + "/" + den; } @Override public int compareTo(Frac o){ ...
function farey (n) local a, b, c, d, k = 0, 1, 1, n local farTab = {{a, b}} while c <= n do k = math.floor((n + b) / d) a, b, c, d = c, d, k * c - a, k * d - b table.insert(farTab, {a, b}) end return farTab end for i = 1, 11 do io.write(i .. ": ") for _, frac in pa...
Preserve the algorithm and functionality while converting the code from Java to Lua.
public class ImplicitTypeConversion{ public static void main(String...args){ System.out.println( "Primitive conversions" ); byte by = -1; short sh = by; int in = sh; long lo = in; System.out.println( "byte value -1 to 3 integral types: " + lo ); float fl = ...
type(123 .. "123") type(123 + "123") type(123 + "foo") function noop () end local a = noop() print(a) local x, y, z = noop() print(x, y, z) print(not not nil, not not false, not not 1, not not "foo", not not { })
Convert this Java snippet to Lua and keep its semantics consistent.
public class ImplicitTypeConversion{ public static void main(String...args){ System.out.println( "Primitive conversions" ); byte by = -1; short sh = by; int in = sh; long lo = in; System.out.println( "byte value -1 to 3 integral types: " + lo ); float fl = ...
type(123 .. "123") type(123 + "123") type(123 + "foo") function noop () end local a = noop() print(a) local x, y, z = noop() print(x, y, z) print(not not nil, not not false, not not 1, not not "foo", not not { })
Generate a Lua translation of this Java snippet without changing its computational steps.
import java.math.BigInteger; public class MersennePrimes { private static final int MAX = 20; private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TWO = BigInteger.valueOf(2); private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 =...
function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end local i, p = 0 repeat i = i + 1 p = 2 ^ i - 1 if isPrime(p) then print("2 ^ " .. i .. "...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.math.BigInteger; public class MersennePrimes { private static final int MAX = 20; private static final BigInteger ONE = BigInteger.ONE; private static final BigInteger TWO = BigInteger.valueOf(2); private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 =...
function isPrime (x) if x < 2 then return false end if x < 4 then return true end if x % 2 == 0 then return false end for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end local i, p = 0 repeat i = i + 1 p = 2 ^ i - 1 if isPrime(p) then print("2 ^ " .. i .. "...
Convert the following code from Java to Lua, ensuring the logic remains intact.
import java.util.ArrayList; import java.util.List; public class SexyPrimes { public static void main(String[] args) { sieve(); int pairs = 0; List<String> pairList = new ArrayList<>(); int triples = 0; List<String> tripleList = new ArrayList<>(); int quadruplets = 0...
local N = 1000035 local function T(t) return setmetatable(t, {__index=table}) end table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end table.lastn = function(t,n)...
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
import java.util.PriorityQueue; import java.util.ArrayList; import java.util.List; import java.util.Iterator; class CubeSum implements Comparable<CubeSum> { public long x, y, value; public CubeSum(long x, long y) { this.x = x; this.y = y; this.value = x*x*x + y*y*y; } public String toString() { return St...
sums, taxis, limit = {}, {}, 1200 for i = 1, limit do for j = 1, i-1 do sum = i^3 + j^3 sums[sum] = sums[sum] or {} table.insert(sums[sum], i.."^3 + "..j.."^3") end end for k,v in pairs(sums) do if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end end table.sort(taxis...
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
public class StrongAndWeakPrimes { private static int MAX = 10_000_000 + 1000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { sieve(); System.out.println("First 36 strong primes:"); displayStrongPrimes(36); for ( int n :...
function primeList (n) local function isPrime (x) for d = 3, math.sqrt(x), 2 do if x % d == 0 then return false end end return true end local pTable, j = {2, 3} for i = 5, n, 2 do if isPrime(i) then table.insert(pTable, i) end j = i end repeat j = j + 2 until isPrime(j) ...
Produce a language-to-language conversion: from Java to Lua, same semantics.
import java.math.BigInteger; public class LeftFac{ public static BigInteger factorial(BigInteger n){ BigInteger ans = BigInteger.ONE; for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){ ans = ans.multiply(x); } return ans; } public static BigInteger leftFact(BigInteger n...
require("bc") function facsUpTo (n) local f, fList = bc.number(1), {} fList[0] = 1 for i = 1, n do f = bc.mul(f, i) fList[i] = f end return fList end function leftFac (n) local sum = bc.number(0) for k = 0, n - 1 do sum = bc.add(sum, facList[k]) end return bc.tostrin...
Can you help me rewrite this code in Lua instead of Java, keeping it the same logically?
import java.math.BigInteger; public class LeftFac{ public static BigInteger factorial(BigInteger n){ BigInteger ans = BigInteger.ONE; for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){ ans = ans.multiply(x); } return ans; } public static BigInteger leftFact(BigInteger n...
require("bc") function facsUpTo (n) local f, fList = bc.number(1), {} fList[0] = 1 for i = 1, n do f = bc.mul(f, i) fList[i] = f end return fList end function leftFac (n) local sum = bc.number(0) for k = 0, n - 1 do sum = bc.add(sum, facList[k]) end return bc.tostrin...
Maintain the same structure and functionality when rewriting this code in Lua.
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isP...
local function T(t) return setmetatable(t, {__index=table}) end table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end local sieve, S = {}, 50000 for i = 2,S do sieve[i]=true end for i = 2,S do if sieve[i] then for j=i*i,S,i do sieve[j]=nil end end end local digs, can...
Please provide an equivalent version of this Java code in Lua.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { D...
_ = love.graphics p1, p2, points = {}, {}, {} function hypotenuse( a, b ) return a * a + b * b end function love.load() size = _.getWidth() currentTime, doub, half = 0, size * 2, size / 2 local b1, b2 for j = 0, size * 2 do for i = 0, size * 2 do b1 = math.floor( 128 + 127 * ...
Translate the given Java code snippet into Lua without altering its behavior.
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long ...
function squareFree (n) for root = 2, math.sqrt(n) do if n % (root * root) == 0 then return false end end return true end function run (lo, hi, showValues) io.write("From " .. lo .. " to " .. hi) io.write(showValues and ":\n" or " = ") local count = 0 for i = lo, hi do if squareFree(i) then ...
Generate an equivalent Lua version of this Java code.
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); ...
local N = 2200 local ar = {} for i=1,N do ar[i] = false end for a=1,N do for b=a,N do if (a % 2 ~= 1) or (b % 2 ~= 1) then local aabb = a * a + b * b for c=b,N do local aabbcc = aabb + c * c local d = math.floor(math.sqrt(aabbcc)) ...
Change the following Java code into Lua without altering its purpose.
package org.rosettacode; import java.util.ArrayList; import java.util.List; public class SumAndProductPuzzle { private final long beginning; private final int maxSum; private static final int MIN_VALUE = 2; private List<int[]> firstConditionExcludes = new ArrayList<>(); private List<int[]> secon...
function print_count(t) local cnt = 0 for k,v in pairs(t) do cnt = cnt + 1 end print(cnt .. ' candidates') end function make_pair(a,b) local t = {} table.insert(t, a) table.insert(t, b) return t end function setup() local candidates = {} for x = 2, 98 do for y...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.math.BigDecimal; import java.util.List; public class TestIntegerness { private static boolean isLong(double d) { return isLong(d, 0.0); } private static boolean isLong(double d, double tolerance) { return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance; ...
function isInt (x) return type(x) == "number" and x == math.floor(x) end print("Value\tInteger?") print("=====\t========") local testCases = {2, 0, -1, 3.5, "String!", true} for _, input in pairs(testCases) do print(input, isInt(input)) end
Produce a functionally identical Lua code for the snippet given in Java.
public class UlamNumbers { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int n = 1; n <= 100000; n *= 10) { System.out.printf("Ulam(%d) = %d\n", n, ulam(n)); } long finish = System.currentTimeMillis(); System.out.printf("El...
function ulam(n) local ulams, nways, i = { 1,2 }, { 0,0,1 }, 3 repeat if nways[i] == 1 then for j = 1, #ulams do local sum = i + ulams[j] nways[sum] = (nways[sum] or 0) + 1 end ulams[#ulams+1] = i end i = i + 1 until #ulams == n return ulams[#ulams] end for _,n in ...
Transform the following Java implementation into Lua, maintaining the same output and logic.
public class TypeDetection { private static void showType(Object a) { if (a instanceof Integer) { System.out.printf("'%s' is an integer\n", a); } else if (a instanceof Double) { System.out.printf("'%s' is a double\n", a); } else if (a instanceof Character) { ...
function writeValue(v) local t = type(v) if t == "number" then io.write(v) elseif t == "string" then io.write("`" .. v .. "`") elseif t == "table" then local c = 0 io.write("{") for k,v in pairs(v) do if c > 0 then io.write(", ") ...
Generate a Lua translation of this Java snippet without changing its computational steps.
public class SafePrimes { public static void main(String... args) { int SIEVE_SIZE = 10_000_000; boolean[] isComposite = new boolean[SIEVE_SIZE]; isComposite[0] = true; isComposite[1] = true; for (int n = 2; n < SIEVE_SIZE; n++) { if (isComposite...
local function T(t) return setmetatable(t, {__index=table}) end table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end table.firstn = function(t,n) local s=T{} n=n>#...
Produce a functionally identical Lua code for the snippet given in Java.
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan...
local function recA(age, name) return { Age=age, Name=name } end local tabA = { recA(27,"Jonah"), recA(18,"Alan"), recA(28,"Glory"), recA(18,"Popeye"), recA(28,"Alan") } local function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end local tabB = { recB("Jonah","Whales"), recB("Jonah","Spid...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.util.function.IntPredicate; import java.util.stream.IntStream; public class Test { public static void main(String[] args) throws Exception { print("Java Identifier start: ", 0, 0x10FFFF, 72, Character::isJavaIdentifierStart, "%c"); print("Java Identifier part: ...
function isValidIdentifier(id) local reserved = { ["and"]=true, ["break"]=true, ["do"]=true, ["end"]=true, ["else"]=true, ["elseif"]=true, ["end"]=true, ["false"]=true, ["for"]=true, ["function"]=true, ["goto"]=true, ["if"]=true, ["in"]=true, ["local"]=true, ["nil"]=true, ["not"]=true, ["or"]=true, ["repe...
Write the same algorithm in Lua as shown in this Java implementation.
import com.sun.javafx.application.PlatformImpl; import java.io.File; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; public class AudioAlarm { public static void main(String[] ...
SDL = require "SDL" mixer = require "SDL.mixer" lfs = require "lfs" print("Enter a number of seconds: ") sec = tonumber(io.read()) print("Enter the MP3 file to be played") mp3filepath = lfs.currentdir() .. "/" .. io.read() .. ".mp3" mixer.openAudio(44100, SDL.audioFormat.S16, 1, 1024) Music = mixer.loadMUS(mp3filepat...
Preserve the algorithm and functionality while converting the code from Java to Lua.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void...
local SIZE = #arg[1] local GOAL = tonumber(arg[2]) or 24 local input = {} for v in arg[1]:gmatch("%d") do table.insert(input, v) end assert(#input == SIZE, 'Invalid input') local operations = {'+', '-', '*', '/'} local function BinaryTrees(vert) if vert == 0 then return {false} else local buf = {} for lefte...