Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Java to Lua with equivalent syntax and logic.
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...
Port the provided Java code into Lua while preserving the original functionality.
import java.util.LinkedList; public class DoublyLinkedList { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addFirst("Add First"); list.addLast("Add Last 1"); list.addLast("Add Last 2"); list.addLast("Add Last 1"); ...
local function Node(data) return { data=data } end local List = { head = nil, tail = nil, insertHead = function(self, data) local node = Node(data) if (self.head) then self.head.prev = node node.next = self.head self.head = node else self.head = node self.tail = ...
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
import java.util.Objects; import java.util.function.Predicate; public class RealNumberSet { public enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN, } public static class RealSet { private Double low; private Double high; private Predicate<D...
function createSet(low,high,rt) local l,h = tonumber(low), tonumber(high) if l and h then local t = {low=l, high=h} if type(rt) == "string" then if rt == "open" then t.contains = function(d) return low< d and d< high end elseif rt == "closed" then ...
Convert this Java snippet to Lua and keep its semantics consistent.
import java.util.Objects; import java.util.function.Predicate; public class RealNumberSet { public enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN, } public static class RealSet { private Double low; private Double high; private Predicate<D...
function createSet(low,high,rt) local l,h = tonumber(low), tonumber(high) if l and h then local t = {low=l, high=h} if type(rt) == "string" then if rt == "open" then t.contains = function(d) return low< d and d< high end elseif rt == "closed" then ...
Change the programming language of this snippet from Java to Lua without modifying what it does.
import java.math.BigInteger; public class SuperDNumbers { public static void main(String[] args) { for ( int i = 2 ; i <= 9 ; i++ ) { superD(i, 10); } } private static final void superD(int d, int max) { long start = System.currentTimeMillis(); String test ...
for d = 2, 5 do local n, found = 0, {} local dds = string.rep(d, d) while #found < 10 do local dnd = string.format("%15.f", d * n ^ d) if string.find(dnd, dds) then found[#found+1] = n end n = n + 1 end print("super-" .. d .. ": " .. table.concat(found,", ")) end
Rewrite the snippet below in Lua so it works the same as the original Java code.
import java.math.BigInteger; public class SuperDNumbers { public static void main(String[] args) { for ( int i = 2 ; i <= 9 ; i++ ) { superD(i, 10); } } private static final void superD(int d, int max) { long start = System.currentTimeMillis(); String test ...
for d = 2, 5 do local n, found = 0, {} local dds = string.rep(d, d) while #found < 10 do local dnd = string.format("%15.f", d * n ^ d) if string.find(dnd, dds) then found[#found+1] = n end n = n + 1 end print("super-" .. d .. ": " .. table.concat(found,", ")) end
Generate a Lua translation of this Java snippet without changing its computational steps.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static fin...
http = require("socket.http") keys = {"VOICEMAIL", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} dictFile = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" function keySequence (str) local sequence, noMatch, letter = "" for pos = 1, #str do letter = str:sub(pos, pos) for i, c...
Write the same algorithm in Lua as shown in this Java implementation.
package lvijay; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class Church { public static interface ChurchNum extends Function<ChurchNum, ChurchNum> { } public static ChurchNum zero() { return f -> x -> x; } public static ChurchNum next(Chu...
function churchZero() return function(x) return x end end function churchSucc(c) return function(f) return function(x) return f(c(f)(x)) end end end function churchAdd(c, d) return function(f) return function(x) return c(f)(d(f)(x)) end end end function churchMul(c, d...
Convert this Java block to Lua, preserving its control flow and logic.
package lvijay; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class Church { public static interface ChurchNum extends Function<ChurchNum, ChurchNum> { } public static ChurchNum zero() { return f -> x -> x; } public static ChurchNum next(Chu...
function churchZero() return function(x) return x end end function churchSucc(c) return function(f) return function(x) return f(c(f)(x)) end end end function churchAdd(c, d) return function(f) return function(x) return c(f)(d(f)(x)) end end end function churchMul(c, d...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.lang.reflect.Method; public class ListMethods { public int examplePublicInstanceMethod(char c, double d) { return 42; } private boolean examplePrivateInstanceMethod(String s) { return true; } public static void main(String[] args) { Class clazz = ListMethod...
function helloWorld() print "Hello World" end function printFunctions(t) local s={} local n=0 for k in pairs(t) do n=n+1 s[n]=k end table.sort(s) for k,v in ipairs(s) do f = t[v] if type(f) == "function" then print(v) end end end printFuncti...
Convert this Java snippet to Lua and keep its semantics consistent.
import java.lang.reflect.Method; class Example { public int foo(int x) { return 42 + x; } } public class Main { public static void main(String[] args) throws Exception { Object example = new Example(); String name = "foo"; Class<?> clazz = example.getClass(); Method meth = clazz.getMethod(na...
local example = { } function example:foo (x) return 42 + x end local name = "foo" example[name](example, 5)
Rewrite the snippet below in Lua so it works the same as the original Java code.
import java.util.Arrays; public class SpecialVariables { public static void main(String[] args) { System.out.println(Arrays.toString(args)); System.out.println(SpecialVariables.class); System.out.println(System.getenv()); ...
for n in pairs(_G) do print(n) end
Write the same code in Lua as shown below in Java.
import java.text.MessageFormat; import java.text.ParseException; public class CanonicalizeCIDR { public static void main(String[] args) { for (String test : TESTS) { try { CIDR cidr = new CIDR(test); System.out.printf("%-18s -> %s\n", test, cidr.toString()); ...
inet = require 'inet' test_cases = { '87.70.141.1/22', '36.18.154.103/12', '62.62.197.11/29', '67.137.119.181/4', '161.214.74.21/24', '184.232.176.184/18' } for i, cidr in ipairs(test_cases) do print( inet(cidr):network() ) end
Please provide an equivalent version of this Java code in Lua.
import java.text.MessageFormat; import java.text.ParseException; public class CanonicalizeCIDR { public static void main(String[] args) { for (String test : TESTS) { try { CIDR cidr = new CIDR(test); System.out.printf("%-18s -> %s\n", test, cidr.toString()); ...
inet = require 'inet' test_cases = { '87.70.141.1/22', '36.18.154.103/12', '62.62.197.11/29', '67.137.119.181/4', '161.214.74.21/24', '184.232.176.184/18' } for i, cidr in ipairs(test_cases) do print( inet(cidr):network() ) end
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
import static java.lang.Math.*; import java.util.function.Function; public class Test { final static int N = 5; static double[] lroots = new double[N]; static double[] weight = new double[N]; static double[][] lcoef = new double[N + 1][N + 1]; static void legeCoef() { lcoef[0][0] = lcoef[...
local order = 0 local legendreRoots = {} local legendreWeights = {} local function legendre(term, z) if (term == 0) then return 1 elseif (term == 1) then return z else return ((2 * term - 1) * z * legendre(term - 1, z) - (term - 1) * legendre(term - 2, z)) / term end end local...
Please provide an equivalent version of this Java code in Lua.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) ...
function array1D(w, d) local t = {} for i=1,w do table.insert(t, d) end return t end function array2D(h, w, d) local t = {} for i=1,h do table.insert(t, array1D(w, d)) end return t end function push(s, v) s[#s + 1] = v end function pop(s) return table.remove(s,...
Maintain the same structure and functionality when rewriting this code in Lua.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) ...
function array1D(w, d) local t = {} for i=1,w do table.insert(t, d) end return t end function array2D(h, w, d) local t = {} for i=1,h do table.insert(t, array1D(w, d)) end return t end function push(s, v) s[#s + 1] = v end function pop(s) return table.remove(s,...
Convert the following code from Java to Lua, ensuring the logic remains intact.
public class CubanPrimes { private static int MAX = 1_400_000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { preCompute(); cubanPrime(200, true); for ( int i = 1 ; i <= 5 ; i++ ) { int max = (int) Math.pow(10, i); ...
local primes = {3, 5} local cutOff = 200 local bigUn = 100000 local chunks = 50 local little = math.floor(bigUn / chunks) local tn = " cuban prime" print(string.format("The first %d%ss", cutOff, tn)) local showEach = true local c = 0 local u = 0 local v = 1 for i=1,10000000000000 do local found = false u = u + ...
Transform the following Java implementation into Lua, maintaining the same output and logic.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex; ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = ...
math.randomseed( os.time() ) colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {} function love.load() wid, hei = love.graphics.getWidth(), love.graphics.getHeight() orig[1] = { wid / 2, 3 } orig[2] = { 3, hei - 3 } orig[3] = { wid - 3, hei - 3 } local w, h = math.random( 10, 40 ...
Port the provided Java code into Lua while preserving the original functionality.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex; ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = ...
math.randomseed( os.time() ) colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {} function love.load() wid, hei = love.graphics.getWidth(), love.graphics.getHeight() orig[1] = { wid / 2, 3 } orig[2] = { 3, hei - 3 } orig[3] = { wid - 3, hei - 3 } local w, h = math.random( 10, 40 ...
Please provide an equivalent version of this Java code in Lua.
import java.util.Arrays; public class GroupStage{ static String[] games = {"12", "13", "14", "23", "24", "34"}; static String results = "000000"; private static boolean nextResult(){ if(results.equals("222222")) return false; int res = Integer.parseInt(results, 3) + 1; result...
function array1D(a, d) local m = {} for i=1,a do table.insert(m, d) end return m end function array2D(a, b, d) local m = {} for i=1,a do table.insert(m, array1D(b, d)) end return m end function fromBase3(num) local out = 0 for i=1,#num do local c = num:s...
Translate the given Java code snippet into Lua without altering its behavior.
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String ...
local OPERATOR_PRECEDENCE = { ['-'] = { 2, true }; ['+'] = { 2, true }; ['/'] = { 3, true }; ['*'] = { 3, true }; ['^'] = { 4, false }; } local function shuntingYard(expression) local outputQueue = { } local operatorStack = { } local number, operator, parenthesis, fcall ...
Convert the following code from Java to Lua, ensuring the logic remains intact.
public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255, Z = (int)Math.floor(z) & 255; x -= Math.floor(x); y...
local p = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 13...
Translate the given Java code snippet into Lua without altering its behavior.
package astar; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.Comparator; import java.util.LinkedList; import java.util.Queue; class AStar { private final List<Node> open; private final List<Node> closed; private final Lis...
Queue = {} function Queue:new() local q = {} self.__index = self return setmetatable( q, self ) end function Queue:push( v ) table.insert( self, v ) end function Queue:pop() return table.remove( self, 1 ) end function Queue:getSmallestF() local s, i = nil, 2 while( self[i] ~= nil and self[1...
Produce a functionally identical Lua code for the snippet given in Java.
package astar; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.Comparator; import java.util.LinkedList; import java.util.Queue; class AStar { private final List<Node> open; private final List<Node> closed; private final Lis...
Queue = {} function Queue:new() local q = {} self.__index = self return setmetatable( q, self ) end function Queue:push( v ) table.insert( self, v ) end function Queue:pop() return table.remove( self, 1 ) end function Queue:getSmallestF() local s, i = nil, 2 while( self[i] ~= nil and self[1...
Change the following Java code into Lua without altering its purpose.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PierpontPrimes { public static void main(String[] args) { NumberFormat nf = NumberFormat.getNumberInstance(); display("First 50 Pierpont primes of the first kind:", pierpontP...
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 local f, limit = 5, math.sqrt(n) for f = 5, limit, 6 do if n % f == 0 then return false end if n % (f+2) == 0 then return false end end return true end local function s3i...
Transform the following Java implementation into Lua, maintaining the same output and logic.
import java.util.Locale; public class Test { public static void main(String[] args) { System.out.println(new Vec2(5, 7).add(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).mult(11)); System.out.println(new Vec2(5, 7).div(2...
vector = {mt = {}} function vector.new (x, y) local new = {x = x or 0, y = y or 0} setmetatable(new, vector.mt) return new end function vector.mt.__add (v1, v2) return vector.new(v1.x + v2.x, v1.y + v2.y) end function vector.mt.__sub (v1, v2) return vector.new(v1.x - v2.x, v1.y - v2.y) end func...
Translate this program into Lua but keep the logic exactly as in Java.
import static java.lang.Math.*; import java.util.function.Function; public class ChebyshevCoefficients { static double map(double x, double min_x, double max_x, double min_to, double max_to) { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to; } static void chebyshevCo...
function map(x, min_x, max_x, min_to, max_to) return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to end function chebyshevCoef(func, minn, maxx, coef) local N = table.getn(coef) for j=1,N do local i = j - 1 local m = map(math.cos(math.pi * (i + 0.5) / N), -1, 1, minn, maxx) ...
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
import static java.lang.Math.*; import java.util.function.Function; public class ChebyshevCoefficients { static double map(double x, double min_x, double max_x, double min_to, double max_to) { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to; } static void chebyshevCo...
function map(x, min_x, max_x, min_to, max_to) return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to end function chebyshevCoef(func, minn, maxx, coef) local N = table.getn(coef) for j=1,N do local i = j - 1 local m = map(math.cos(math.pi * (i + 0.5) / N), -1, 1, minn, maxx) ...
Generate a Lua translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.List; public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003"; private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String canno...
STX = string.char(tonumber(2,16)) ETX = string.char(tonumber(3,16)) function bwt(s) if s:find(STX, 1, true) then error("String cannot contain STX") end if s:find(ETX, 1, true) then error("String cannot contain ETX") end local ss = STX .. s .. ETX local tbl = {} for i=1,#ss ...
Change the programming language of this snippet from Java to Lua without modifying what it does.
import java.util.ArrayList; import java.util.List; public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003"; private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String canno...
STX = string.char(tonumber(2,16)) ETX = string.char(tonumber(3,16)) function bwt(s) if s:find(STX, 1, true) then error("String cannot contain STX") end if s:find(ETX, 1, true) then error("String cannot contain ETX") end local ss = STX .. s .. ETX local tbl = {} for i=1,#ss ...
Change the programming language of this snippet from Java to Lua without modifying what it does.
import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; public class CardShuffles{ private static final Random rand = new Random(); public static <T> LinkedList<T> riffleShuffle(List<T> list, int flips){ LinkedList<T> newList = new Linke...
function newDeck () local cards, suits = {}, {"C", "D", "H", "S"} for _, suit in pairs(suits) do for value = 2, 14 do if value == 10 then value = "T" end if value == 11 then value = "J" end if value == 12 then value = "Q" end if value == 13 then value = "...
Port the following code from Java to Lua with equivalent syntax and logic.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream; public class FaulhabersTriangle { private static final MathContext MC = new MathContext(256); private static long gcd(long a, long b) { if (b == 0) { return a; } ...
function binomial(n,k) if n<0 or k<0 or n<k then return -1 end if n==0 or k==0 then return 1 end local num = 1 for i=k+1,n do num = num * i end local denom = 1 for i=2,n-k do denom = denom * i end return num / denom end function gcd(a,b) while b ~= 0 do ...
Can you help me rewrite this code in Lua instead of Java, keeping it the same logically?
import java.util.Arrays; import java.util.stream.IntStream; public class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static class Frac implements Comparable<Frac> { private long num; ...
function binomial(n,k) if n<0 or k<0 or n<k then return -1 end if n==0 or k==0 then return 1 end local num = 1 for i=k+1,n do num = num * i end local denom = 1 for i=2,n-k do denom = denom * i end return num / denom end function gcd(a,b) while b ~= 0 do ...
Translate this program into Lua but keep the logic exactly as in Java.
public class PrimeConspiracy { public static void main(String[] args) { final int limit = 1000_000; final int sieveLimit = 15_500_000; int[][] buckets = new int[10][10]; int prevDigit = 2; boolean[] notPrime = sieve(sieveLimit); for (int n = 3, primeCount = 1; prim...
function isPrime (n) if n <= 1 then return false end if n <= 3 then return true end if n % 2 == 0 or n % 3 == 0 then return false end local i = 5 while i * i <= n do if n % i == 0 or n % (i + 2) == 0 then return false end i = i + 6 end return true end function primeCon (l...
Write the same algorithm in Lua as shown in this Java implementation.
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET....
tree_list = {} offset = {} function init() for i=1,32 do if i == 2 then table.insert(offset, 1) else table.insert(offset, 0) end end end function append(t) local v = 1 | (t << 1) table.insert(tree_list, v) end function show(t, l) while l > 0 do ...
Keep all operations the same but rewrite the snippet in Lua.
import static java.lang.Math.*; import static java.util.Arrays.stream; import java.util.Locale; import java.util.function.DoubleSupplier; import static java.util.stream.Collectors.joining; import java.util.stream.DoubleStream; import static java.util.stream.IntStream.range; public class Test implements DoubleSupplier ...
function gaussian (mean, variance) return math.sqrt(-2 * variance * math.log(math.random())) * math.cos(2 * math.pi * math.random()) + mean end function mean (t) local sum = 0 for k, v in pairs(t) do sum = sum + v end return sum / #t end function std (t) local squares, a...
Generate an equivalent Lua version of this Java code.
import java.util.Arrays; import static java.util.Arrays.stream; import java.util.concurrent.*; public class VogelsApproximationMethod { final static int[] demand = {30, 20, 70, 30, 60}; final static int[] supply = {50, 60, 50, 50}; final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, ...
function initArray(n,v) local tbl = {} for i=1,n do table.insert(tbl,v) end return tbl end function initArray2(m,n,v) local tbl = {} for i=1,m do table.insert(tbl,initArray(n,v)) end return tbl end supply = {50, 60, 50, 50} demand = {30, 20, 70, 30, 60} costs = { {1...
Convert the following code from Java to Lua, ensuring the logic remains intact.
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class MinimumNumberOnlyZeroAndOne { public static void main(String[] args) { for ( int n : getTestCases() ) { BigInteger result = getA004290(n); System.out.printf("A004290(%d) = %s = %s * %s%n"...
function array1D(n, v) local tbl = {} for i=1,n do table.insert(tbl, v) end return tbl end function array2D(h, w, v) local tbl = {} for i=1,h do table.insert(tbl, array1D(w, v)) end return tbl end function mod(m, n) m = math.floor(m) local result = m % n if ...
Rewrite the snippet below in Lua so it works the same as the original Java code.
import java.util.ArrayList; import java.util.List; public class WeirdNumbers { public static void main(String[] args) { int n = 2; for ( int count = 1 ; count <= 25 ; n += 2 ) { if ( isWeird(n) ) { System.out.printf("w(%d) = %d%n", count, n); co...
function make(n, d) local a = {} for i=1,n do table.insert(a, d) end return a end function reverse(t) local n = #t local i = 1 while i < n do t[i],t[n] = t[n],t[i] i = i + 1 n = n - 1 end end function tail(list) return { select(2, unpack(list)) } end...
Keep all operations the same but rewrite the snippet in Lua.
import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID ...
local function validate(diagram) local lines = {} for s in diagram:gmatch("[^\r\n]+") do s = s:match("^%s*(.-)%s*$") if s~="" then lines[#lines+1]=s end end assert(#lines>0, "FAIL: no non-empty lines") assert(#lines%2==1, "FAIL: even number of lines") return lines end local function parse(line...
Convert the following code from Java to Lua, ensuring the logic remains intact.
public class AdditionChains { private static class Pair { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1]; result[0] = n; System.arrayc...
function index(a,i) return a[i + 1] end function checkSeq(pos, seq, n, minLen) if pos > minLen or index(seq,0) > n then return minLen, 0 elseif index(seq,0) == n then return pos, 1 elseif pos < minLen then return tryPerm(0, pos, seq, n, minLen) else return minLen, 0 ...
Translate this program into Lua but keep the logic exactly as in Java.
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); Sys...
a = 1 b = 2.0 c = "hello world" function listProperties(t) if type(t) == "table" then for k,v in pairs(t) do if type(v) ~= "function" then print(string.format("%7s: %s", type(v), k)) end end end end print("Global properties") listProperties(_G) print("Pa...
Please provide an equivalent version of this Java code in Lua.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.IntConsumer; import java.util.stream.Collectors; public class Kosaraju { static class Recursive<I> { I func; } ...
function write_array(a) io.write("[") for i=0,#a do if i>0 then io.write(", ") end io.write(tostring(a[i])) end io.write("]") end function kosaraju(g) local size = #g local vis = {} for i=0,size do vis[i] = false end local ...
Generate an equivalent Lua version of this Java code.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; public class MarkovChain { pr...
local function pick(t) local i = math.ceil(math.random() * #t) return t[i] end local n_prevs = tonumber(arg[1]) or 2 local n_words = tonumber(arg[2]) or 8 local dict, wordset = {}, {} local prevs, pidx = {}, 1 local function add(word) local prev = '' local i, len = pidx, #prevs for _ = 1, len do i ...
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class WordBreak { public static void main(String[] args) { List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab"); for ( String testString : Arrays.asList...
function genDict(ws) local d,dup,head,rest = {},{} for w in ws:gmatch"%w+" do local lw = w:lower() if not dup[lw] then dup[lw], head,rest = true, lw:match"^(%w)(.-)$" d[head] = d[head] or {n=-1} local len = #rest d[head][len] = d[head][len] or {} d[head][len][rest] = true ...
Ensure the translated Lua code behaves exactly like the original Java snippet.
import java.util.Random; public class KMeansWithKpp{ public Point[] points; public Point[] centroids; Random rand; public int n; public int k; private KMeansWithKpp(){ } KMeansWithKpp(Point[] p, int clusters){ points = p; n = p.length; k = Math.max(1, clusters); centroids = new ...
local function load_data(npoints, radius) for i = 1,npoints do local ang = math.random() * (2.0 * math.pi) local rad = math.random() * radius data[i] = {x = math.cos(ang) * rad, y = math.sin(ang) * rad} end return data end local function print_eps(data, nclusters, centers, cluster) local WIDT...
Produce a functionally identical Lua code for the snippet given in Java.
import java.awt.*; import javax.swing.*; public class ColorWheel { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ColorWheelFrame frame = new ColorWheelFrame(); frame.setVisible(true); } ...
local function hsv_to_rgb (h, s, v) local r = math.min (math.max (3*math.abs (((h )/180)%2-1)-1, 0), 1) local g = math.min (math.max (3*math.abs (((h -120)/180)%2-1)-1, 0), 1) local b = math.min (math.max (3*math.abs (((h +120)/180)%2-1)-1, 0), 1) local k1 = v*(1-s) local k2 = v - k1 ...
Ensure the translated Lua code behaves exactly like the original Java snippet.
import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class Perceptron extends JPanel { class Trainer { double[] inputs; int answer; Trainer(double x, double y, int a) { inputs = new double[]{x, y, 1}; ...
local Perceptron = {} Perceptron.__index = Perceptron function Perceptron.new(numInputs) local cell = {} setmetatable(cell, Perceptron) cell.weights = {} cell.bias = math.random() cell.output = 0 for i = 1, numInputs do cell.weights[i] = math.random() end return cell end fu...
Ensure the translated Lua code behaves exactly like the original Java snippet.
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; import java.util.Scanner; public class csprngBBS { public static Scanner input = new Scann...
size = 500 math.randomseed(os.time()) function writePgm(data, fn, comment) local rows = #data local cols = #data[1] local file = io.open(fn, "wb") file:write("P5", "\n") if comment ~= nil then file:write("# ", comment, "\n") end file:write(cols, " ", rows, "\n") file:write("255", "\n") fo...
Port the following code from Java to Lua with equivalent syntax and logic.
module test { @Inject Console console; void run() { Char ch = 'x'; console.print( $"ch={ch.quoted()}"); String greeting = "Hello"; console.print( $"greeting={greeting.quoted()}"); String lines = \|first line ...
s1 = "This is a double-quoted 'string' with embedded single-quotes." s2 = 'This is a single-quoted "string" with embedded double-quotes.' s3 = "this is a double-quoted \"string\" with escaped double-quotes." s4 = 'this is a single-quoted \'string\' with escaped single-quotes.' s5 = [[This is a long-bracket "'string'" w...
Write the same algorithm in Lua as shown in this Java implementation.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numb...
local function T(t) return setmetatable(t, {__index=table}) end table.head = 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 table.tail = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[#t-n+i] end return s end local printf = function(s,...) io.write(s:format(.....
Port the following code from Java to Lua with equivalent syntax and logic.
import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class PowerfulNumbers { public static void main(String[] args) { System.out.printf("Task: For k = 2..10, generate the set of k-powerful numb...
local function T(t) return setmetatable(t, {__index=table}) end table.head = 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 table.tail = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[#t-n+i] end return s end local printf = function(s,...) io.write(s:format(.....
Translate this program into Lua but keep the logic exactly as in Java.
int abscissae[]={171,185,202,202,328,208,241,164,69,139,72,168}; int ordinates[] = {171,111,109,189 ,160,254 ,330 ,252,278 ,208 ,148 ,172}; void setup() { size(450, 450); background(255); smooth(); noFill(); stroke(0); beginShape(); for(int i=0;i<abscissae.length;i++){ curveVertex(abscissae[i],...
local function Range(from, to) local range = {} for n = from, to do table.insert(range, n) end return range end local function Bspline(controlPoints, k) return { controlPoints = controlPoints, n = #controlPoints, k = k, t = Range(1, #controlPoints+k), } end local function helper(bspline, i, k, x) ret...
Rewrite this program in Lua while keeping its functionality equivalent to the Java version.
int abscissae[]={171,185,202,202,328,208,241,164,69,139,72,168}; int ordinates[] = {171,111,109,189 ,160,254 ,330 ,252,278 ,208 ,148 ,172}; void setup() { size(450, 450); background(255); smooth(); noFill(); stroke(0); beginShape(); for(int i=0;i<abscissae.length;i++){ curveVertex(abscissae[i],...
local function Range(from, to) local range = {} for n = from, to do table.insert(range, n) end return range end local function Bspline(controlPoints, k) return { controlPoints = controlPoints, n = #controlPoints, k = k, t = Range(1, #controlPoints+k), } end local function helper(bspline, i, k, x) ret...
Convert the following code from Go to Fortran, ensuring the logic remains intact.
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i ...
module Polygons use Points_Module implicit none type polygon type(point), dimension(:), allocatable :: points integer, dimension(:), allocatable :: vertices end type polygon contains function create_polygon(pts, vt) type(polygon) :: create_polygon type(point), dimension(:), intent(in) :: ...
Generate a Fortran translation of this Go snippet without changing its computational steps.
package main func main() { s := "immutable" s[0] = 'a' }
real, parameter :: pi = 3.141593
Keep all operations the same but rewrite the snippet in Fortran.
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Count("the three truths", "th")) fmt.Println(strings.Count("ababababab", "abab")) }
program Example implicit none integer :: n n = countsubstring("the three truths", "th") write(*,*) n n = countsubstring("ababababab", "abab") write(*,*) n n = countsubstring("abaabba*bbaba*bbab", "a*b") write(*,*) n contains function countsubstring(s1, s2) result(c) character(*), intent(in) :: s...
Keep all operations the same but rewrite the snippet in Fortran.
package main import "fmt" func mod(n, m int) int { return ((n % m) + m) % m } func isPrime(n int) bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } d := 5 for d * d <= n { if n % d == 0 { return false } d += 2 if n % d ==...
LOGICAL FUNCTION ISPRIME(N) INTEGER N INTEGER F ISPRIME = .FALSE. DO F = 2,SQRT(DFLOAT(N)) IF (MOD(N,F).EQ.0) RETURN END DO ISPRIME = .TRUE. END FUNCTION ISPRIME PROGRAM CHASE INTEGER P1,P2,P3 INTEGER H3,D ...
Write the same code in Fortran as shown below in Go.
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int ...
-*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat May 18 01:13:00 a=./f && make $a && $a f95 -Wall -ffree-form f.F -o f 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW 0.30...
Write the same algorithm in Fortran as shown in this Go implementation.
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Den...
program hickerson implicit none integer, parameter :: q = selected_real_kind(30) integer, parameter :: l = selected_int_kind(15) real(q) :: s, l2 integer :: i, n, k l2 = log(2.0_q) do n = 1, 17 s = 0.5_q / l2 do i = 1, n s = (s * i) / l2 end do k...
Port the provided Go code into Fortran while preserving the original functionality.
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string ...
program readconfig implicit none integer, parameter :: strlen = 100 logical :: needspeeling = .false., seedsremoved =.false. character(len=strlen) :: favouritefruit = "", fullname = "", fst, snd character(len=strlen), allocatable :: otherfamily(:), tmp(:) character(len=1000) :: line int...
Convert this Go block to Fortran, preserving its control flow and logic.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] ...
program Stooge implicit none integer :: i integer :: array(50) = (/ (i, i = 50, 1, -1) /) call Stoogesort(array) write(*,"(10i5)") array contains recursive subroutine Stoogesort(a) integer, intent(in out) :: a(:) integer :: j, t, temp j = size(a) if(a(j) < a(1)) then temp = a(j) a...
Rewrite the snippet below in Fortran so it works the same as the original Go code.
import ( "fmt" "os" ) if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
SUBROUTINE CROAK(GASP) CHARACTER*(*) GASP WRITE (6,*) "Oh dear. ",GASP STOP "++ungood." END SUBROUTINE FILEHACK(FNAME,NB) CHARACTER*(*) FNAME INTEGER NB INTEGER L INTEGER F,T PARAMETER (F=66,T=67) LOGICAL EXIST C...
Translate the given Go code snippet into Fortran without altering its behavior.
import ( "fmt" "os" ) if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
SUBROUTINE CROAK(GASP) CHARACTER*(*) GASP WRITE (6,*) "Oh dear. ",GASP STOP "++ungood." END SUBROUTINE FILEHACK(FNAME,NB) CHARACTER*(*) FNAME INTEGER NB INTEGER L INTEGER F,T PARAMETER (F=66,T=67) LOGICAL EXIST C...
Write a version of this Go function in Fortran with identical behavior.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { for i := inc; i < len(a); i++ { j, temp := i, a[i] for ; j >= inc && a[j-inc] > temp; j -= inc { ...
MODULE sort CONTAINS SUBROUTINE Shell_Sort(a) IMPLICIT NONE INTEGER :: i, j, increment REAL :: temp REAL, INTENT(in out) :: a(:) increment = SIZE(a) / 2 DO WHILE (increment > 0) DO i = increment+1, SIZE(a) j = i temp = a(i) DO WHILE (j >= increment+1 .AND. a(j-increment...
Rewrite the snippet below in Fortran so it works the same as the original Go code.
package main import "fmt" func main() { h := []float64{-8, -9, -3, -1, -6, 7} f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1} g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7} fmt.Println(h) fmt.Println(deconv(...
program deconv use mkl95_lapack, only : gelsd implicit none real(8), allocatable :: g(:), href(:), A(:,:), f(:) real(8), pointer :: h(:), r(:) integer :: N character(len=16) :: cbuff integer :: i intrinsic :: nint allocate(g(21),f(16)) g = [24,...
Write the same code in Fortran as shown below in Go.
package main import "fmt" type ibool bool const itrue ibool = true func (ib ibool) iif(cond bool) bool { if cond { return bool(ib) } return bool(!ib) } func main() { var needUmbrella bool raining := true if raining { needUmbrella = true } fmt.Printf("Is it rain...
INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT)
Keep all operations the same but rewrite the snippet in Fortran.
type cell string type spec struct { less func(cell, cell) bool column int reverse bool } func newSpec() (s spec) { return } t.sort(newSpec()) s := newSpec s.reverse = true t.sort(s)
module ExampleOptionalParameter implicit none contains subroutine sort_table(table, ordering, column, reverse) type(table_type), intent(inout) :: table integer, optional :: column logical, optional :: reverse optional :: ordering interface integer function ordering(a, b) t...
Change the following Go code into Fortran without altering its purpose.
package main import ( "fmt" "runtime" "sync" ) func main() { p := sync.Pool{New: func() interface{} { fmt.Println("pool empty") return new(int) }} i := new(int) j := new(int) *i = 1 *j = 2 fmt.Println(*i + *j) p.P...
SUBROUTINE CHECK(A,N) REAL A(:,:) INTEGER N REAL B(N,N) INTEGER, ALLOCATABLE::TROUBLE(:) INTEGER M M = COUNT(A(1:N,1:N).LE.0) ALLOCATE (TROUBLE(1:M**3)) DEALLOCATE(TROUBLE) END SUBROUTINE CHECK
Rewrite this program in Fortran while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, ฯƒ := range p { pr *= m[i][ฯƒ] } ...
program f implicit none real, dimension(3,3) :: j, m data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/ data m/2, 9, 4, 7, 5, 3, 6, 1, 8/ write(6,*) 'j example, determinant: ',det(j,3,-1) write(6,*) 'j example, permanent: ',det(j,3,1) write(6,*) 'maxima, determinant: ',det(m,3,-1)...
Rewrite the snippet below in Fortran so it works the same as the original Go code.
package main import "fmt" func sameDigits(n, b int) bool { f := n % b n /= b for n > 0 { if n%b != f { return false } n /= b } return true } func isBrazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return true...
PROGRAM BRAZILIAN IMPLICIT NONE INTEGER , PARAMETER :: MAX_NUMBER = 2000000 , NUMVARS = 20 LOGICAL , DIMENSION(1:MAX_NUMBER) :: b INTEGER :: bcount INTEGER :: bpos CHARACTER(15) :: holder CHARACTER(100) :: outline LOGICAL , DIMENSION(1:MAX_NUMBER...
Rewrite this program in Fortran while keeping its functionality equivalent to the Go version.
package main import "fmt" func sumDivisors(n int) int { sum := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } i += k } return...
program DivSum implicit none integer i, j, col, divs(100) do 10 i=1, 100, 1 10 divs(i) = 1 do 20 i=2, 100, 1 do 20 j=i, 100, i 20 divs(j) = divs(j) + i col = 0 do 30 i=1, 100, 1 write (*,'(I4)',advance='no') divs(i) ...
Port the following code from Go to Fortran with equivalent syntax and logic.
package main import "fmt" func mรถbius(to int) []int { if to < 1 { to = 1 } mobs := make([]int, to+1) primes := []int{2} for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break ...
program moebius use iso_fortran_env, only: output_unit integer, parameter :: mu_max=1000000, line_break=20 integer, parameter :: sqroot=int(sqrt(real(mu_max))) integer :: i, j integer, dimension(mu_max) :: mu mu = 1 do i = 2, sqroot if (mu(i)...
Write the same code in Fortran as shown below in Go.
package main import "fmt" func mertens(to int) ([]int, int, int) { if to < 1 { to = 1 } merts := make([]int, to+1) primes := []int{2} var sum, zeros, crosses int for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { ...
program Mertens implicit none integer M(1000), n, k, zero, cross C Generate Mertens numbers M(1) = 1 do 10 n=2, 1000 M(n) = 1 do 10 k=2, n M(n) = M(n) - M(n/k) 10 continue C Print table write (*,"('The first 99 Mertens num...
Produce a language-to-language conversion: from Go to Fortran, same semantics.
package main import "fmt" func twoSum(a []int, targetSum int) (int, int, bool) { len := len(a) if len < 2 { return 0, 0, false } for i := 0; i < len - 1; i++ { if a[i] <= targetSum { for j := i + 1; j < len; j++ { sum := a[i] + a[j] if sum ==...
program twosum implicit none integer, parameter, dimension(5) :: list = (/ 0, 2, 11, 19, 90/) integer, parameter :: target_val = 21 integer :: nelem integer :: i, j logical :: success = .false. nelem = size(list) outer:do i = 1,nelem do j = i+1,nelem success = list(i) + list(j) == target_...
Write a version of this Go function in Fortran with identical behavior.
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe on...
program circles implicit none double precision :: P1(2), P2(2), R P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.8765d0,0.2345d0/) R = 2.0d0 call print_centers(P1,P2,R) P1 = (/0.0d0, 2.0d0/) P2 = (/0.0d0,0.0d0/) R = 1.0d0 call print_centers(P1,P2,R) P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.1234d0, 0.9876d0/) R = 2.0d0 call prin...
Write the same code in Fortran as shown below in Go.
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { cas...
PROGRAM TEST CHARACTER*28 FAVOURITEFRUIT LOGICAL NEEDSPEELING LOGICAL SEEDSREMOVED INTEGER NUMBEROFBANANAS NAMELIST /FRUIT/ FAVOURITEFRUIT,NEEDSPEELING,SEEDSREMOVED, 1 NUMBEROFBANANAS INTEGER F F = 10 Create an example file to show its format. OPEN(F,FILE="...
Port the following code from Go to Fortran with equivalent syntax and logic.
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei ...
program cia implicit none character (len=256) :: s integer :: ie, ei, cie, cei integer :: ios data ie, ei, cie, cei/4*0/ do while (.true.) read(5,*,iostat = ios)s if (0 .ne. ios) then exit endif call lower_case(s) cie = cie + occurrences(s, 'cie') cei = cei + occu...
Generate an equivalent Fortran version of this Go code.
package main import ( "fmt" "log" "os" "strings" ) const dim = 16 func check(err error) { if err != nil { log.Fatal(err) } } func drawPile(pile [][]uint) { chars:= []rune(" โ–‘โ–“โ–ˆ") for _, row := range pile { line := make([]rune, len(row)) for i, elem := range ...
module abelian_sandpile_m implicit none private public :: pile type :: pile integer, allocatable :: grid(:,:) integer :: n(2) contains procedure :: init procedure :: run procedure, private :: process_node procedure, private :: inside end type contai...
Please provide an equivalent version of this Go code in Fortran.
package main import ( "container/heap" "fmt" "strings" ) type CubeSum struct { x, y uint16 value uint64 } func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] } type CubeSumHeap []*CubeSum func (h CubeSumHeap) Len() int { return len(h) } func (h CubeSumHeap) Less(i, j int) bool { retu...
PROGRAM POOKA IMPLICIT NONE INTEGER , PARAMETER :: NVARS = 25 REAL :: f1 REAL :: f2 INTEGER :: hits INTEGER :: s INTEGER :: TAXICAB hits = 0 s = 0 f1 = SECOND() DO WHILE ( hits<NVARS ) s = s + 1 hits = hits + TA...
Transform the following Go implementation into Fortran, maintaining the same output and logic.
type dlNode struct { int next, prev *dlNode } type dlList struct { members map[*dlNode]int head, tail **dlNode }
module dlist implicit none type node type(node), pointer :: next => null() type(node), pointer :: prev => null() integer :: data end type node type dll type(node), pointer :: head => null() type(node), pointer :: tail => null() integer :: num_nodes = 0 end type dll public ::...
Maintain the same structure and functionality when rewriting this code in Fortran.
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) t := new(big.Float).SetPrec(prec) u := new(big.Float).SetP...
program CalcPi use iso_fortran_env, only: rf => real128 implicit none real(rf) :: a,g,s,old_pi,new_pi real(rf) :: a1,g1,s1 integer :: k,k1,i old_pi = 0.0_rf; a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0 do i=1,100 call approx_pi_step(a,g,s,k,a1,g1,s1,k1) ...
Generate an equivalent Fortran version of this Go code.
package main import ( "fmt" "math/big" "time" "github.com/jbarham/primegen.go" ) func main() { start := time.Now() pg := primegen.New() var i uint64 p := big.NewInt(1) tmp := new(big.Int) for i <= 9 { fmt.Printf("primorial(%v) = %v\n", i, p) i++ p = p.Mul(p, tmp.SetUint64(pg.Next())) } for _, j := ...
B.DIGIT(I) = MOD(D,BIGBASE) C = D/BIGBASE
Transform the following Go implementation into Fortran, maintaining the same output and logic.
package main import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" ) var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, } func main() { const ( width ...
PROGRAM CHAOS IMPLICIT NONE REAL, DIMENSION(3):: KA, KN REAL, DIMENSION(3):: DA, DB, DC INTEGER:: I, Z INTEGER, PARAMETER:: UT = 17 DA = (/ 0., 0., 0. /) DB = (/ 600., 0., 0. /) DC = (/ 500., 0., 400. /) KA = (/ 500., 0., 100. /) OPEN (UNIT = UT, FILE = 'aus.csv') DO I=1, 1000000 Z = ZAHL()...
Translate the given Rust code snippet into C# without altering its behavior.
use std::env::args; use time::{Date, Duration}; fn main() { let year = args().nth(1).unwrap().parse::<i32>().unwrap(); (1..=12) .map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1)) .filter_map(|date| date.ok()) .for_each(|date| { let days_back = ...
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
Write the same algorithm in C# as shown in this Rust implementation.
use std::env::args; use time::{Date, Duration}; fn main() { let year = args().nth(1).unwrap().parse::<i32>().unwrap(); (1..=12) .map(|month| Date::try_from_ymd(year + month / 12, ((month % 12) + 1) as u8, 1)) .filter_map(|date| date.ok()) .for_each(|date| { let days_back = ...
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= ...
Transform the following Rust implementation into C#, maintaining the same output and logic.
use rand::distributions::Uniform; use rand::prelude::{thread_rng, ThreadRng}; use rand::Rng; fn main() { for _ in 0..=10 { attributes_engine(); } } #[derive(Copy, Clone, Debug)] pub struct Dice { amount: i32, range: Uniform<i32>, rng: ThreadRng, } impl Dice { pub fn new...
using System; using System.Collections.Generic; using System.Linq; static class Module1 { static Random r = new Random(); static List<int> getThree(int n) { List<int> g3 = new List<int>(); for (int i = 0; i < 4; i++) g3.Add(r.Next(n) + 1); g3.Sort(); g3.RemoveAt(0); return g3; ...
Produce a functionally identical C# code for the snippet given in Rust.
use itertools::Itertools; fn get_kolakoski_sequence(iseq: &[usize], size: &usize) -> Vec<usize> { assert!(*size > 0); assert!(!iseq.is_empty()); let mut kseq: Vec<usize> = Vec::default(); let repeater = iseq.iter().cloned().cycle(); kseq.extend_from_slice(&vec![*iseq.get(0).unwrap()].r...
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KolakoskiSequence { class Crutch { public readonly int len; public int[] s; public int i; public Crutch(int len) { this.len = len; s...
Preserve the algorithm and functionality while converting the code from Rust to C#.
fn lis(x: &[i32])-> Vec<i32> { let n = x.len(); let mut m = vec![0; n]; let mut p = vec![0; n]; let mut l = 0; for i in 0..n { let mut lo = 1; let mut hi = l; while lo <= hi { let mid = (lo + hi) / 2; if x[m[mid]] <= x[i] { lo = mid ...
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.E...
Write the same algorithm in C# as shown in this Rust implementation.
*/ fn example() { } #[doc = "Unsugared outer Rustdoc comments. (outer attributes are not terminated by a semi-colon)"] fn example() { #[doc = "Unsugared inner Rustdoc comments. (inner attributes are terminated by a semi-colon) See also https: }
Port the provided Rust code into C# while preserving the original functionality.
use std::{ convert::TryFrom, fmt::{Debug, Display, Formatter}, io::Read, }; pub struct ReadUtf8<I: Iterator> { source: std::iter::Peekable<I>, } impl<R: Read> From<R> for ReadUtf8<std::io::Bytes<R>> { fn from(source: R) -> Self { ReadUtf8 { source: source.bytes().peekable(), ...
using System; using System.IO; using System.Text; namespace RosettaFileByChar { class Program { static char GetNextCharacter(StreamReader streamReader) => (char)streamReader.Read(); static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; char c...
Change the programming language of this snippet from Rust to C# without modifying what it does.
const OPEN_CHAR: char = '{'; const CLOSE_CHAR: char = '}'; const SEPARATOR: char = ','; const ESCAPE: char = '\\'; #[derive(Debug, PartialEq, Clone)] enum Token { Open, Close, Separator, Payload(String), Branches(Branches), } impl From<char> for Token { fn from(ch: char) -> Token { mat...
using System; using System.Collections; using System.Collections.Generic; using System.Text; using static System.Linq.Enumerable; public static class BraceExpansion { enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat } const char L = '{', R = '}', S = ','; public static void M...
Port the following code from Rust to C# with equivalent syntax and logic.
use std::fmt; #[derive(Clone,Copy)] struct Point { x: f64, y: f64 } fn distance (p1: Point, p2: Point) -> f64 { ((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt() } impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({:.4}, {:.4})", self.x, sel...
using System; public class CirclesOfGivenRadiusThroughTwoPoints { public static void Main() { double[][] values = new double[][] { new [] { 0.1234, 0.9876, 0.8765, 0.2345, 2 }, new [] { 0.0, 2.0, 0.0, 0.0, 1 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, ...
Produce a language-to-language conversion: from Rust to C#, same semantics.
use std::fmt; #[derive(Clone,Copy)] struct Point { x: f64, y: f64 } fn distance (p1: Point, p2: Point) -> f64 { ((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt() } impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({:.4}, {:.4})", self.x, sel...
using System; public class CirclesOfGivenRadiusThroughTwoPoints { public static void Main() { double[][] values = new double[][] { new [] { 0.1234, 0.9876, 0.8765, 0.2345, 2 }, new [] { 0.0, 2.0, 0.0, 0.0, 1 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, ...
Change the programming language of this snippet from Rust to C# without modifying what it does.
use std::cmp::{max, min}; static TENS: [u64; 20] = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, 10000000000000000, 1000000...
using System; namespace RosettaVampireNumber { class Program { static void Main(string[] args) { int i, j, n; ulong x; var f = new ulong[16]; var bigs = new ulong[] { 16758243290880UL, 24959017348650UL, 14593825548650UL, 0 }; ulong[] t...
Maintain the same structure and functionality when rewriting this code in C#.
fn main() { let hands = vec![ "๐Ÿ‚ก ๐Ÿ‚ฎ ๐Ÿ‚ญ ๐Ÿ‚ซ ๐Ÿ‚ช", "๐Ÿƒ ๐Ÿƒ‚ ๐Ÿ‚ข ๐Ÿ‚ฎ ๐Ÿƒ", "๐Ÿƒ ๐Ÿ‚ต ๐Ÿƒ‡ ๐Ÿ‚จ ๐Ÿƒ‰", "๐Ÿƒ ๐Ÿƒ‚ ๐Ÿ‚ฃ ๐Ÿ‚ค ๐Ÿ‚ฅ", "๐Ÿƒ ๐Ÿ‚ณ ๐Ÿƒ‚ ๐Ÿ‚ฃ ๐Ÿƒƒ", "๐Ÿƒ ๐Ÿ‚ท ๐Ÿƒ‚ ๐Ÿ‚ฃ ๐Ÿƒƒ", "๐Ÿƒ ๐Ÿ‚ท ๐Ÿƒ‡ ๐Ÿ‚ง ๐Ÿƒ—", "๐Ÿƒ ๐Ÿ‚ป ๐Ÿ‚ฝ ๐Ÿ‚พ ๐Ÿ‚ฑ", "๐Ÿƒ ๐Ÿƒ” ๐Ÿƒž ๐Ÿƒ… ๐Ÿ‚ช", "๐Ÿƒ ๐Ÿƒž ๐Ÿƒ— ๐Ÿƒ– ๐Ÿƒ”", "๐Ÿƒ ๐Ÿƒ‚ ๐ŸƒŸ ๐Ÿ‚ค ๐Ÿ‚ฅ", ...
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class PokerHandAnalyzer { private enum Hand { Invalid, High_Card, One_Pair, Two_Pair, Three_Of_A_Kind, Straight, Flush, Full_House, Four_Of_A_Kind, Straight_Flush, Five_Of_A_Kind } private co...
Maintain the same structure and functionality when rewriting this code in C#.
fn main() { let hands = vec![ "๐Ÿ‚ก ๐Ÿ‚ฎ ๐Ÿ‚ญ ๐Ÿ‚ซ ๐Ÿ‚ช", "๐Ÿƒ ๐Ÿƒ‚ ๐Ÿ‚ข ๐Ÿ‚ฎ ๐Ÿƒ", "๐Ÿƒ ๐Ÿ‚ต ๐Ÿƒ‡ ๐Ÿ‚จ ๐Ÿƒ‰", "๐Ÿƒ ๐Ÿƒ‚ ๐Ÿ‚ฃ ๐Ÿ‚ค ๐Ÿ‚ฅ", "๐Ÿƒ ๐Ÿ‚ณ ๐Ÿƒ‚ ๐Ÿ‚ฃ ๐Ÿƒƒ", "๐Ÿƒ ๐Ÿ‚ท ๐Ÿƒ‚ ๐Ÿ‚ฃ ๐Ÿƒƒ", "๐Ÿƒ ๐Ÿ‚ท ๐Ÿƒ‡ ๐Ÿ‚ง ๐Ÿƒ—", "๐Ÿƒ ๐Ÿ‚ป ๐Ÿ‚ฝ ๐Ÿ‚พ ๐Ÿ‚ฑ", "๐Ÿƒ ๐Ÿƒ” ๐Ÿƒž ๐Ÿƒ… ๐Ÿ‚ช", "๐Ÿƒ ๐Ÿƒž ๐Ÿƒ— ๐Ÿƒ– ๐Ÿƒ”", "๐Ÿƒ ๐Ÿƒ‚ ๐ŸƒŸ ๐Ÿ‚ค ๐Ÿ‚ฅ", ...
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class PokerHandAnalyzer { private enum Hand { Invalid, High_Card, One_Pair, Two_Pair, Three_Of_A_Kind, Straight, Flush, Full_House, Four_Of_A_Kind, Straight_Flush, Five_Of_A_Kind } private co...
Convert this Rust block to C#, preserving its control flow and logic.
extern crate rand; use std::io::{stdin, stdout, Write}; use std::thread; use std::time::Duration; use rand::Rng; fn toss_coin<R: Rng>(rng: &mut R, print: bool) -> char { let c = if rng.gen() { 'H' } else { 'T' }; if print { print!("{}", c); stdout().flush().expect("Could not flush stdout"); ...
using static System.Console; using static System.Threading.Thread; using System; public static class PenneysGame { const int pause = 500; const int N = 3; static Random rng = new Random(); static int Toss() => rng.Next(2); static string AsString(this int sequence) { string s = ""; ...
Generate a C# translation of this Rust snippet without changing its computational steps.
struct Nonoblock { width: usize, config: Vec<usize>, spaces: Vec<usize>, } impl Nonoblock { pub fn new(width: usize, config: Vec<usize>) -> Nonoblock { Nonoblock { width: width, config: config, spaces: Vec::new(), } } pub fn solve(&mut self) -> Vec<Vec<i32>> { let mut output:...
using System; using System.Linq; using System.Text; public static class Nonoblock { public static void Main() { Positions(5, 2,1); Positions(5); Positions(10, 8); Positions(15, 2,3,2,3); Positions(5, 2,3); } public static void Positions(int cells, params int[] block...