Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Ensure the translated Lua code behaves exactly like the original C++ snippet. | #include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;
#if 1
typedef unsigned long usingle;
typedef unsigned long long udouble;
const int word_len = 32;
#else
typedef unsigned short usingle;
typedef unsigned long udouble;
const int word_len = 16;
#endif
... |
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... |
Keep all operations the same but rewrite the snippet in Lua. | #include <iostream>
#include <cstdint>
using integer = uint32_t;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 + next_prime_digit_number(n/10) * 10;
... |
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... |
Generate an equivalent Lua version of this C++ code. | #include <windows.h>
#include <math.h>
#include <string>
const int BMP_SIZE = 240, MY_TIMER = 987654;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
... | _ = 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 * ... |
Convert this C++ block to Lua, preserving its control flow and logic. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
bool square_free(integer n) {
if (n % 4 == 0)
return false;
for (integer p = 3; p * p <= n; p += 2) {
integer count = 0;
for (; n % p == 0; n /= p) {
if (++count > 1)
return f... | 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
... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <iostream>
#include <vector>
constexpr int N = 2200;
constexpr int N2 = 2 * N * N;
int main() {
using namespace std;
vector<bool> found(N + 1);
vector<bool> aabb(N2 + 1);
int s = 3;
for (int a = 1; a < N; ++a) {
int aa = a * a;
for (int b = 1; b < N; ++b) {
... |
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))
... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <algorithm>
#include <iostream>
#include <map>
#include <vector>
std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {
for (auto &p : v) {
auto sum = p.first + p.second;
auto prod = p.first * p.second;
os << '[' << p.first << ", " << p.second << "] S=" <... | 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... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? | #include <complex>
#include <math.h>
#include <iostream>
template<class Type>
struct Precision
{
public:
static Type GetEps()
{
return eps;
}
static void SetEps(Type e)
{
eps = e;
}
private:
static Type eps;
};
template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);
template<class DigT... | 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 C++. | #include <algorithm>
#include <chrono>
#include <iostream>
#include <vector>
int ulam(int n) {
std::vector<int> ulams{1, 2};
std::vector<int> sieve{1, 1};
for (int u = 2; ulams.size() < n; ) {
sieve.resize(u + ulams[ulams.size() - 2], 0);
for (int i = 0; i < ulams.size() - 1; ++i)
... | 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 ... |
Port the following code from C++ to Lua with equivalent syntax and logic. | #include <iostream>
template <typename T>
auto typeString(const T&) {
return typeid(T).name();
}
class C {};
struct S {};
int main() {
std::cout << typeString(1) << '\n';
std::cout << typeString(1L) << '\n';
std::cout << typeString(1.0f) << '\n';
std::cout << typeString(1.0) << '\n';
std::cou... | 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(", ")
... |
Write the same code in Lua as shown below in C++. | #include <algorithm>
#include <iostream>
#include <iterator>
#include <locale>
#include <vector>
#include "prime_sieve.hpp"
const int limit1 = 1000000;
const int limit2 = 10000000;
class prime_info {
public:
explicit prime_info(int max) : max_print(max) {}
void add_prime(int prime);
void print(std::ostrea... |
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>#... |
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {
{"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};
tab_t tab2 {
{"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"... | 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... |
Generate an equivalent Lua version of this C++ code. | #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::... | 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... |
Write a version of this C++ function in Lua with identical behavior. | #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::... | 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... |
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <list>
int main ()
{
std::list<int> numbers {1, 5, 7, 0, 3, 2};
numbers.insert(numbers.begin(), 9);
numbers.insert(numbers.end(), 4);
auto it = std::next(numbers.begin(), numbers.size() / 2);
numbers.insert(it, 6);
for(const auto& i: numbers)
std::cout <... |
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 the snippet below in Lua so it works the same as the original C++ code. | #include <cassert>
#include <functional>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
enum RangeType {
CLOSED,
BOTH_OPEN,
LEFT_OPEN,
RIGHT_OPEN
};
class RealSet {
private:
double low, high;
double interval = 0.00001;
std::function<bool(double)> predicate;
public:
R... | 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
... |
Write the same algorithm in Lua as shown in this C++ implementation. | #include <cassert>
#include <functional>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
enum RangeType {
CLOSED,
BOTH_OPEN,
LEFT_OPEN,
RIGHT_OPEN
};
class RealSet {
private:
double low, high;
double interval = 0.00001;
std::function<bool(double)> predicate;
public:
R... | 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
... |
Generate a Lua translation of this C++ snippet without changing its computational steps. | #include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
double ByVaccaSeries(int numTerms)
{
double gamma = 0;
size_t next = 4;
for(double numerator = 1; numerator < numTerms; ++numerator)
{
double delta = 0;
for(size_t denominato... | function computeGamma (iterations, decimalPlaces)
local Hn = 1
for i = 2, iterations do
Hn = Hn + (1/i)
end
local gamma = tostring(Hn - math.log(iterations))
return tonumber(gamma:sub(1, decimalPlaces + 2))
end
print(computeGamma(10^8, 8))
|
Change the programming language of this snippet from C++ to Lua without modifying what it does. | #include <iostream>
#include <sstream>
#include <vector>
uint64_t ipow(uint64_t base, uint64_t exp) {
uint64_t result = 1;
while (exp) {
if (exp & 1) {
result *= base;
}
exp >>= 1;
base *= base;
}
return result;
}
int main() {
using namespace std;
v... | 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 C++ code. | #include <iostream>
#include <sstream>
#include <vector>
uint64_t ipow(uint64_t base, uint64_t exp) {
uint64_t result = 1;
while (exp) {
if (exp & 1) {
result *= base;
}
exp >>= 1;
base *= base;
}
return result;
}
int main() {
using namespace std;
v... | 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
|
Transform the following C++ implementation into Lua, maintaining the same output and logic. | #include <iostream>
#include <cmath>
#include <optional>
#include <vector>
using namespace std;
template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
if(!monad.has_value())
{
return optional<remove_reference_t<decltype(*f(*monad))>>();
}
return f(*monad)... |
local NONE = {}
local function unit(x) return { x } end
local Some = unit
local function isNone(mb) return #mb == 0 end
local function isSome(mb) return #mb == 1 end
local function isMaybe(mb) return isNone(mb) or isSome(mb) end
local function get(mb) return mb[1] end
function maybeToStr(mb)
return isNone(mb... |
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
struct Textonym_Checker {
private:
int total;
int elements;
int textonyms;
int max_found;
std::vector<std::string> max_strings;
std::unordered_map<std::string, std::vector<std::string>> values;
int get_mappin... |
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... |
Translate this program into Lua but keep the logic exactly as in C++. | #include <iostream>
auto Zero = [](auto){ return [](auto x){ return x; }; };
auto True = [](auto a){ return [=](auto){ return a; }; };
auto False = [](auto){ return [](auto b){ return b; }; };
auto Successor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(f)(f(x));
};
... | 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 the following code from C++ to Lua, ensuring the logic remains intact. | #include <iostream>
auto Zero = [](auto){ return [](auto x){ return x; }; };
auto True = [](auto a){ return [=](auto){ return a; }; };
auto False = [](auto){ return [](auto b){ return b; }; };
auto Successor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(f)(f(x));
};
... | 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 C++ to Lua with equivalent syntax and logic. | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
this->i++;
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv;
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n... | for n in pairs(_G) do print(n) end
|
Generate a Lua translation of this C++ snippet without changing its computational steps. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>
class ipv4_cidr {
public:
ipv4_cidr() {}
ipv4_cidr(std::uint32_t address, unsigned int mask_length)
: address_(address), mask_length_(mask_length) {}
std::uint32_t address() const {
return address_;
}
unsi... | 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
|
Generate a Lua translation of this C++ snippet without changing its computational steps. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>
class ipv4_cidr {
public:
ipv4_cidr() {}
ipv4_cidr(std::uint32_t address, unsigned int mask_length)
: address_(address), mask_length_(mask_length) {}
std::uint32_t address() const {
return address_;
}
unsi... | 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
|
Port the provided C++ code into Lua while preserving the original functionality. | #include <iostream>
#include <iomanip>
#include <cmath>
namespace Rosetta {
template <int N>
class GaussLegendreQuadrature {
public:
enum {eDEGREE = N};
template <typename Function>
double integrate(double a, double b, Function f) {
double p = (b - a) / 2... | 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... |
Write the same code in Lua as shown below in C++. | #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {... | 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,... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {... | 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. | #include <iostream>
#include <vector>
#include <chrono>
#include <climits>
#include <cmath>
using namespace std;
vector <long long> primes{ 3, 5 };
int main()
{
cout.imbue(locale(""));
const int cutOff = 200, bigUn = 100000,
chunks = 50, little = bigUn / chunks;
const char tn[] = " cuban prime";
... | 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 + ... |
Change the programming language of this snippet from C++ to Lua without modifying what it does. | #include <windows.h>
#include <ctime>
#include <string>
#include <iostream>
const int BMP_SIZE = 600;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
... | 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 ... |
Generate a Lua translation of this C++ snippet without changing its computational steps. | #include <windows.h>
#include <ctime>
#include <string>
#include <iostream>
const int BMP_SIZE = 600;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
... | 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 ... |
Convert this C++ block to Lua, preserving its control flow and logic. | #include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>
#include <sstream>
std::array<std::string, 6> games{ "12", "13", "14", "23", "24", "34" };
std::string results = "000000";
int fromBase3(std::string num) {
int out = 0;
for (auto c : num) {
int d = c - '0';
out = 3 * ... | 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... |
Maintain the same structure and functionality when rewriting this code in Lua. | #include <ciso646>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
using std::vector;
using std::string;
#include <exception>
#include <stdexcept>
template <typename...Args> std::runtime_error error( Args...args )
{
return st... |
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 C++ to Lua, ensuring the logic remains intact. | #include <list>
#include <algorithm>
#include <iostream>
class point {
public:
point( int a = 0, int b = 0 ) { x = a; y = b; }
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
class map {
public:
... |
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... |
Generate an equivalent Lua version of this C++ code. | #include <list>
#include <algorithm>
#include <iostream>
class point {
public:
point( int a = 0, int b = 0 ) { x = a; y = b; }
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
class map {
public:
... |
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... |
Please provide an equivalent version of this C++ code in Lua. | #include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
enum CipherMode {ENCRYPT, DECRYPT};
uint32_t randRsl[256];
uint32_t randCnt;
uint32_t mm[256];
uint32_t aa = 0, bb = 0, cc = 0;
void isaac()
{
++cc;
bb += cc;
for (uint32_t i = 0; i < 256; ++i)
{
uin... | #!/usr/bin/env lua
local randRsl = {};
local randCnt = 0;
local mm = {};
local aa,bb,cc = 0,0,0;
local cap = 0x100000000;
local ENCRYPT = 1;
local DECRYPT = 2;
function isaac()
cc = ( cc + 1 ) % cap;
bb = ( bb + cc ) % cap;
for i = 0,255 do
local x = mm[i];
local y;
local imod ... |
Please provide an equivalent version of this C++ code in Lua. | #include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
enum CipherMode {ENCRYPT, DECRYPT};
uint32_t randRsl[256];
uint32_t randCnt;
uint32_t mm[256];
uint32_t aa = 0, bb = 0, cc = 0;
void isaac()
{
++cc;
bb += cc;
for (uint32_t i = 0; i < 256; ++i)
{
uin... | #!/usr/bin/env lua
local randRsl = {};
local randCnt = 0;
local mm = {};
local aa,bb,cc = 0,0,0;
local cap = 0x100000000;
local ENCRYPT = 1;
local DECRYPT = 2;
function isaac()
cc = ( cc + 1 ) % cap;
bb = ( bb + cc ) % cap;
for i = 0,255 do
local x = mm[i];
local y;
local imod ... |
Change the following C++ code into Lua without altering its purpose. | #include <cassert>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
using big_int = mpz_class;
bool is_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25);
}
template <typename integer>
class n_smooth_generator {
public:
explicit n_smooth_gen... | 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... |
Write the same algorithm in Lua as shown in this C++ implementation. | #include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
#define PI 3.14159265359
class Vector
{
public:
Vector(double ix, double iy, char mode)
{
if(mode=='a')
{
x=ix*cos(iy);
y=ix*sin(iy);
}
else
{
x=ix;
... | 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... |
Write the same algorithm in Lua as shown in this C++ implementation. | #include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <utility>
#include <vector>
using namespace std;
static const double PI = acos(-1.0);
double affine_remap(const pair<double, double>& from, double x, const pair<double, double>& to)
{
return to.first + (x - from.first) * (to.second -... | 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)
... |
Translate the given C++ code snippet into Lua without altering its behavior. | #include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <utility>
#include <vector>
using namespace std;
static const double PI = acos(-1.0);
double affine_remap(const pair<double, double>& from, double x, const pair<double, double>& to)
{
return to.first + (x - from.first) * (to.second -... | 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)
... |
Ensure the translated Lua code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <iostream>
#include <vector>
const int STX = 0x02;
const int ETX = 0x03;
void rotate(std::string &a) {
char t = a[a.length() - 1];
for (int i = a.length() - 1; i > 0; i--) {
a[i] = a[i - 1];
}
a[0] = t;
}
std::string bwt(const std::string &s) {
for (char c : ... | 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 ... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <algorithm>
#include <iostream>
#include <vector>
const int STX = 0x02;
const int ETX = 0x03;
void rotate(std::string &a) {
char t = a[a.length() - 1];
for (int i = a.length() - 1; i > 0; i--) {
a[i] = a[i - 1];
}
a[0] = t;
}
std::string bwt(const std::string &s) {
for (char c : ... | 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 ... |
Convert this C++ block to Lua, preserving its control flow and logic. | #include <time.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <deque>
class riffle
{
public:
void shuffle( std::deque<int>* v, int tm )
{
std::deque<int> tmp;
bool fl;
size_t len;
std::deque<int>::iterator it;
copyTo( v, &tmp );
for( int t = 0; t < tm; t++ )
{
std:... |
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 = "... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <time.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <deque>
class riffle
{
public:
void shuffle( std::deque<int>* v, int tm )
{
std::deque<int> tmp;
bool fl;
size_t len;
std::deque<int>::iterator it;
copyTo( v, &tmp );
for( int t = 0; t < tm; t++ )
{
std:... |
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 = "... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? | #include <exception>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
class Frac {
public:
Frac() : num(0), denom(1) {}
Frac(int n, int d) {
if (d == 0) {
throw std::runtime_error("d must not be zero");
}
int sign_of_d = d < 0 ? -1 : 1;
int g = std::gcd(n,... | 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
... |
Change the following C++ code into Lua without altering its purpose. | #include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
class Frac {
public:
Frac(long n, long d) {
if (d == 0) {
throw new std::runtime_error("d must not be zero");
}
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g =... | 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
... |
Change the following C++ code into Lua without altering its purpose. | #include <vector>
#include <iostream>
#include <cmath>
#include <utility>
#include <map>
#include <iomanip>
bool isPrime( int i ) {
int stop = std::sqrt( static_cast<double>( i ) ) ;
for ( int d = 2 ; d <= stop ; d++ )
if ( i % d == 0 )
return false ;
return true ;
}
class Compare {
public :
Compa... |
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... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #include <iostream>
#include <vector>
std::vector<long> TREE_LIST;
std::vector<int> OFFSET;
void init() {
for (size_t i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.push_back(1);
} else {
OFFSET.push_back(0);
}
}
}
void append(long t) {
TREE_LIST.push_back(1 | ... | 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
... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <random>
#include <map>
#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>
int main( ) {
std::random_device myseed ;
std::mt19937 engine ( myseed( ) ) ;
std::normal_distribution<> normDistri ( 2 , 3 ) ;
std::map<int , int> normalFreq ;
int sum = 0 ;
double mean = 0.0 ... | 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... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #include <iostream>
#include <numeric>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
... | 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... |
Produce a language-to-language conversion: from C++ to Lua, same semantics. | #include <iostream>
#include <vector>
__int128 imax(__int128 a, __int128 b) {
if (a > b) {
return a;
}
return b;
}
__int128 ipow(__int128 b, __int128 n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return b;
}
__int128 res = b;
while (n > 1) {
res *= b... | 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 ... |
Translate this program into Lua but keep the logic exactly as in C++. | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs = { 1 };
std::vector<int> divs2;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int j = n / i;
divs.push_back(i);
if (i !... | 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... |
Maintain the same structure and functionality when rewriting this code in Lua. | #include <array>
#include <bitset>
#include <iostream>
using namespace std;
struct FieldDetails {string_view Name; int NumBits;};
template <const char *T> consteval auto ParseDiagram()
{
constexpr string_view rawArt(T);
constexpr auto firstBar = rawArt.find("|");
constexpr auto lastBar = rawArt.... | 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 this C++ block to Lua, preserving its control flow and logic. | #include <iostream>
#include <tuple>
#include <vector>
std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);
std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {
if (pos > minLen || seq[0] > n) return { minLen, 0 };
else if (seq[0] == n) return ... | 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
... |
Generate an equivalent Lua version of this C++ code. | #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
whil... | 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 ... |
Ensure the translated Lua code behaves exactly like the original C++ snippet. | #include <ctime>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
class markov {
public:
void create( std::string& file, unsigned int keyLen, unsigned int words ) {
std::ifstream f( file.c_str(), std::ios_base::in );
fileBuffer = std::str... | 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 ... |
Write a version of this C++ function in Lua with identical behavior. | #include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
struct string_comparator {
using is_transparent = void;
bool operator()(const std::string& lhs, const std::string& rhs) const {
return lhs < rhs;
}
bool operato... |
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
... |
Please provide an equivalent version of this C++ code in Lua. |
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <=... | 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 C++ snippet. | #include <cstdint>
#include <iostream>
#include <vector>
#include <primesieve.hpp>
void print_diffs(const std::vector<uint64_t>& vec) {
for (size_t i = 0, n = vec.size(); i != n; ++i) {
if (i != 0)
std::cout << " (" << vec[i] - vec[i - 1] << ") ";
std::cout << vec[i];
}
std::cou... | function findcps(primelist, fcmp)
local currlist = {primelist[1]}
local longlist, prevdiff = currlist, 0
for i = 2, #primelist do
local diff = primelist[i] - primelist[i-1]
if fcmp(diff, prevdiff) then
currlist[#currlist+1] = primelist[i]
if #currlist > #longlist then
longlist = currli... |
Generate a Lua translation of this C++ snippet without changing its computational steps. | #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= ... | function is_1_or_has_eight_divisors (n)
if n == 1 then return true end
local divCount, sqr = 2, math.sqrt(n)
for d = 2, sqr do
if n % d == 0 then
divCount = d == sqr and divCount + 1 or divCount + 2
end
if divCount > 8 then return false end
end
return divCount == ... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <cmath>
#include <cstdint>
#include <iostream>
#include <functional>
uint64_t factorial(int n) {
uint64_t result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int inverse_factorial(uint64_t f) {
int p = 1;
int i = 1;
if (f == 1) {
return 0;... |
function factorial(n)
local result = 1
local i = 1
while i <= n do
result = result * i
i = i + 1
end
return result
end
function inverse_factorial(f)
local p = 1
local i = 1
if f == 1 then
return 0
end
while p < f do
p = p * i
i = i + 1... |
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (au... | 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 C++. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (au... | 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 VB. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbrevia... | #!/usr/bin/lua
local list1 = [[
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst
COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate
Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp
FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN
LOAD Locate CLocate LOWe... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbrevia... | #!/usr/bin/lua
local list1 = [[
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst
COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate
Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp
FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN
LOAD Locate CLocate LOWe... |
Please provide an equivalent version of this VB code in Lua. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <=... | function truncate (filename, length)
local inFile = io.open(filename, 'r')
if not inFile then
error("Specified filename does not exist")
end
local wholeFile = inFile:read("*all")
inFile:close()
if length >= wholeFile:len() then
error("Provided length is not less than current file... |
Maintain the same structure and functionality when rewriting this code in Lua. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <=... | function truncate (filename, length)
local inFile = io.open(filename, 'r')
if not inFile then
error("Specified filename does not exist")
end
local wholeFile = inFile:read("*all")
inFile:close()
if length >= wholeFile:len() then
error("Provided length is not less than current file... |
Write the same code in Lua as shown below in VB. | Sub arrShellSort(ByVal arrData As Variant)
Dim lngHold, lngGap As Long
Dim lngCount, lngMin, lngMax As Long
Dim varItem As Variant
lngMin = LBound(arrData)
lngMax = UBound(arrData)
lngGap = lngMin
Do While (lngGap < lngMax)
lngGap = 3 * lngGap + 1
Loop
Do While (lngGap > 1)
lngGap = lngGap ... | function shellsort( a )
local inc = math.ceil( #a / 2 )
while inc > 0 do
for i = inc, #a do
local tmp = a[i]
local j = i
while j > inc and a[j-inc] > tmp do
a[j] = a[j-inc]
j = j - inc
end
a[j] = tmp
end
... |
Can you help me rewrite this code in Lua instead of VB, keeping it the same logically? | Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
E... | function fileLine (lineNum, fileName)
local count = 0
for line in io.lines(fileName) do
count = count + 1
if count == lineNum then return line end
end
error(fileName .. " has fewer than " .. lineNum .. " lines.")
end
print(fileLine(7, "test.txt"))
|
Translate the given VB code snippet into Lua without altering its behavior. | Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
E... | function fileLine (lineNum, fileName)
local count = 0
for line in io.lines(fileName) do
count = count + 1
if count == lineNum then return line end
end
error(fileName .. " has fewer than " .. lineNum .. " lines.")
end
print(fileLine(7, "test.txt"))
|
Generate a Lua translation of this VB snippet without changing its computational steps. | Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
| function encodeChar(chr)
return string.format("%%%X",string.byte(chr))
end
function encodeString(str)
local output, t = string.gsub(str,"[^%w]",encodeChar)
return output
end
print(encodeString("http://foo bar/"))
|
Convert this VB block to Lua, preserving its control flow and logic. | Dim URL As String = "http://foo bar/"
URL = EncodeURLComponent(URL)
Print(URL)
| function encodeChar(chr)
return string.format("%%%X",string.byte(chr))
end
function encodeString(str)
local output, t = string.gsub(str,"[^%w]",encodeChar)
return output
end
print(encodeString("http://foo bar/"))
|
Produce a language-to-language conversion: from VB to Lua, same semantics. | Private Sub optional_parameters(theRange As String, _
Optional ordering As Integer = 0, _
Optional column As Integer = 1, _
Optional reverse As Integer = 1)
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add _
Key:=Range(theRange).Columns(column), _
SortOn:... | function showTable(tbl)
if type(tbl)=='table' then
local result = {}
for _, val in pairs(tbl) do
table.insert(result, showTable(val))
end
return '{' .. table.concat(result, ', ') .. '}'
else
return (tostring(tbl))
end
end
function sortTable(op)
local tbl = op.table or {}
local column = op.column or 1... |
Port the following code from VB to Lua with equivalent syntax and logic. | dim s(10)
print "Enter 11 numbers."
for i = 0 to 10
print i +1;
input " => "; s(i)
next i
print
for i = 10 to 0 step -1
print "f("; s(i); ") = ";
r = f(s(i))
if r > 400 then
print "-=< overflow >=-"
else
print r
end if
next i
end
function f(n)
f = sqr(abs(n)) + 5 * n * n * n
end function
| function f (x) return math.abs(x)^0.5 + 5*x^3 end
function reverse (t)
local rev = {}
for i, v in ipairs(t) do rev[#t - (i-1)] = v end
return rev
end
local sequence, result = {}
print("Enter 11 numbers...")
for n = 1, 11 do
io.write(n .. ": ")
sequence[n] = io.read()
end
for _, x in ipairs(reverse... |
Produce a functionally identical Lua code for the snippet given in VB. | for j = asc("a") to asc("z")
print chr(j);
next j
print
for j= asc("A") to Asc("Z")
print chr(j);
next j
end
| function ASCIIstring (pattern)
local matchString, ch = ""
for charNum = 0, 255 do
ch = string.char(charNum)
if string.match(ch, pattern) then
matchString = matchString .. ch
end
end
return matchString
end
print(ASCIIstring("%l"))
print(ASCIIstring("%u"))
|
Port the provided VB code into Lua while preserving the original functionality. | Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & R... | function reverse()
local ch = io.read(1)
if ch:find("%w") then
local rc = reverse()
io.write(ch)
return rc
end
return ch
end
function forward()
ch = io.read(1)
io.write(ch)
if ch == "." then return false end
if not ch:find("%w") then
ch = reverse()
if ch then io.write(ch) end
if... |
Change the programming language of this snippet from VB to Lua without modifying what it does. | option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public pr... | local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
function Bitmap:render()
for y = 1, self.height do
print(table.concat(self.pixels[y]))
end
end
function Bitmap:drawKochPath(path, x, y, angle, speed, color)
local rules = {
["+"] = function() angle = angle + pi/3 end,
["-"] = functi... |
Change the programming language of this snippet from VB to Lua without modifying what it does. | Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(j)... | function Is_self_describing( n )
local s = tostring( n )
local t = {}
for i = 0, 9 do t[i] = 0 end
for i = 1, s:len() do
local idx = tonumber( s:sub(i,i) )
t[idx] = t[idx] + 1
end
for i = 1, s:len() do
if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end
end
ret... |
Can you help me rewrite this code in Lua instead of VB, keeping it the same logically? | Sub Main_Contain()
Dim ListeWords() As String, Book As String, i As Long, out() As String, count As Integer
Book = Read_File("C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt")
ListeWords = Split(Book, vbNewLine)
For i = LBound(ListeWords) To UBound(ListeWords)
If Len(ListeWords(i)) > 11 Th... | for word in io.open("unixdict.txt", "r"):lines() do
if #word > 11 and word:find("the") then
print(word)
end
end
|
Transform the following VB implementation into Lua, maintaining the same output and logic. | Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
TheAddress = varptr(MyVar)
MEMSET(TheAddress, 102, SizeOf(byte))
showmessage "MyVar = " + str$(MyVar)
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))
showmessage "SecVar = " + str$(SecVar)
| t = {}
print(t)
f = function() end
print(f)
c = coroutine.create(function() end)
print(c)
u = io.open("/dev/null","w")
print(u)
print(_G, _ENV)
print(string.format("%p %p %p", print, string, string.format))
|
Maintain the same structure and functionality when rewriting this code in Lua. | Friend Class Tile
Public Sub New()
Me.Value = 0
Me.IsBlocked = False
End Sub
Public Property Value As Integer
Public Property IsBlocked As Boolean
End Class
Friend Enum MoveDirection
Up
Down
Left
Right
End Enum
Friend Class G2048
Public Sub New()
... |
local unpack = unpack or table.unpack
game = {
cell = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
best = 0,
draw = function(self)
local t = self.cell
print("+
for r=0,12,4 do
print(string.format("|%4d|%4d|%4d|%4d|\n+
end
end,
incr = function(self)
local t,open = self.cell,{}
for i=1,16 ... |
Generate an equivalent Lua version of this VB code. | Do
Debug.Print "SPAM"
Loop
| while true do
print("SPAM")
end
repeat
print("SPAM")
until false
|
Port the following code from VB to Lua with equivalent syntax and logic. | Function Multiply(a As Integer, b As Integer) As Integer
Return a * b
End Function
| function multiply( a, b )
return a * b
end
|
Translate the given VB code snippet into Lua without altering its behavior. | Imports System.Text
Module Module1
Function Sieve(limit As Integer) As Integer()
Dim primes As New List(Of Integer) From {2}
Dim c(limit + 1) As Boolean REM composite = true
REM no need to process even numbers > 2
Dim p = 3
While True
Dim p2 = p * p
... | function findspds(primelist, diffs)
local results = {}
for i = 1, #primelist-#diffs do
result = {primelist[i]}
for j = 1, #diffs do
if primelist[i+j] - primelist[i+j-1] == diffs[j] then
result[j+1] = primelist[i+j]
else
result = nil
break
end
end
results[#re... |
Write the same algorithm in Lua as shown in this VB implementation. |
s=7*8*9
m=9876432
for i=(m\s)*s to 1 step -s
if instr(i,"5")=0 and instr(i,"0")=0 then
b=false: j=1
while j<=len(i)-1 and not b
if instr(j+1,i,mid(i,j,1))<>0 then b=true
j=j+1
wend
if not b then
j=1
while j<=len(i) and not b
if (i mod mid(i,j,1))<>0 then b=true
j=... | function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
end... |
Convert this VB block to Lua, preserving its control flow and logic. |
s=7*8*9
m=9876432
for i=(m\s)*s to 1 step -s
if instr(i,"5")=0 and instr(i,"0")=0 then
b=false: j=1
while j<=len(i)-1 and not b
if instr(j+1,i,mid(i,j,1))<>0 then b=true
j=j+1
wend
if not b then
j=1
while j<=len(i) and not b
if (i mod mid(i,j,1))<>0 then b=true
j=... | function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
end... |
Preserve the algorithm and functionality while converting the code from VB to Lua. | Module Module1
Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
Dim length = a.GetLength(0) - 1
Dim result(length - 1, length - 1) As Double
For i = 1 To length
For j = 1 To length
If i < x AndAlso j < y Then
result(i - ... |
_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.direct... |
Translate the given VB code snippet into Lua without altering its behavior. | Module Module1
Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
Dim length = a.GetLength(0) - 1
Dim result(length - 1, length - 1) As Double
For i = 1 To length
For j = 1 To length
If i < x AndAlso j < y Then
result(i - ... |
_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.direct... |
Write the same code in Lua as shown below in VB. | Private Sub Sattolo(Optional ByRef a As Variant)
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
For i = UBound(a) To lbound(a)+1 Step -1
j = Int((UBound(a) - 1 - LBound(a) + 1) * Rnd + LBound(a))
t = a(i)
a(i) = a(j)
a(j) = t
Next i
En... | function sattolo (items)
local j
for i = #items, 2, -1 do
j = math.random(i - 1)
items[i], items[j] = items[j], items[i]
end
end
math.randomseed(os.time())
local testCases = {
{},
{10},
{10, 20},
{10, 20, 30},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}
}
for _, arr... |
Translate this program into Lua but keep the logic exactly as in VB. | Private Sub Sattolo(Optional ByRef a As Variant)
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
For i = UBound(a) To lbound(a)+1 Step -1
j = Int((UBound(a) - 1 - LBound(a) + 1) * Rnd + LBound(a))
t = a(i)
a(i) = a(j)
a(j) = t
Next i
En... | function sattolo (items)
local j
for i = #items, 2, -1 do
j = math.random(i - 1)
items[i], items[j] = items[j], items[i]
end
end
math.randomseed(os.time())
local testCases = {
{},
{10},
{10, 20},
{10, 20, 30},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}
}
for _, arr... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE ADDRE... |
local sql = require("ljsqlite3")
local conn = sql.open("address.sqlite")
conn:exec[[
CREATE TABLE IF NOT EXISTS address(
id INTEGER PRIMARY KEY AUTOINCREMENT,
street TEXT NOT NULL,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL)
]]
conn:close()
|
Port the following code from VB to Lua with equivalent syntax and logic. | Module Module1
Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean
Dim f As Integer = n Mod b : n \= b : While n > 0
If n Mod b <> f Then Return False Else n \= b
End While : Return True
End Function
Function isBrazilian(ByVal n As Integer) As Boolean
... | function sameDigits(n,b)
local f = n % b
n = math.floor(n / b)
while n > 0 do
if n % b ~= f then
return false
end
n = math.floor(n / b)
end
return true
end
function isBrazilian(n)
if n < 7 then
return false
end
if (n % 2 == 0) and (n >= 8) the... |
Rewrite this program in Lua while keeping its functionality equivalent to the VB version. | Module Module1
Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean
Dim f As Integer = n Mod b : n \= b : While n > 0
If n Mod b <> f Then Return False Else n \= b
End While : Return True
End Function
Function isBrazilian(ByVal n As Integer) As Boolean
... | function sameDigits(n,b)
local f = n % b
n = math.floor(n / b)
while n > 0 do
if n % b ~= f then
return false
end
n = math.floor(n / b)
end
return true
end
function isBrazilian(n)
if n < 7 then
return false
end
if (n % 2 == 0) and (n >= 8) the... |
Translate the given VB code snippet into Lua without altering its behavior. |
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".... | local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1
while n<=15 or not foundDup or #used1000<1001 do
local nxt = a[n - 1] - n
if nxt<1 or used[nxt] ~= nil then
nxt = nxt + 2 * n
end
local alreadyUsed = used[nxt] ~= nil
table.insert(a, nxt... |
Generate an equivalent Lua version of this VB code. |
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".... | local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1
while n<=15 or not foundDup or #used1000<1001 do
local nxt = a[n - 1] - n
if nxt<1 or used[nxt] ~= nil then
nxt = nxt + 2 * n
end
local alreadyUsed = used[nxt] ~= nil
table.insert(a, nxt... |
Convert this VB block to Lua, preserving its control flow and logic. | Private Function call_fn(f As String, n As Long) As Long
call_fn = Application.Run(f, f, n)
End Function
Private Function Y(f As String) As String
Y = f
End Function
Private Function fac(self As String, n As Long) As Long
If n > 1 Then
fac = n * call_fn(self, n - 1)
Else
fac = 1
... | Y = function (f)
return function(...)
return (function(x) return x(x) end)(function(x) return f(function(y) return x(x)(y) end) end)(...)
end
end
|
Change the following VB code into Lua without altering its purpose. | Option Base 1
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
Re... |
function show (msg, t)
io.write(msg .. ":\t")
for _, v in pairs(t) do io.write(v .. " ") end
print()
end
function randList (length, lo, hi)
local t = {}
for i = 1, length do table.insert(t, math.random(lo, hi)) end
return t
end
function tally (list)
local tal = {}
for k, v in pairs(... |
Change the programming language of this snippet from VB to Lua without modifying what it does. | Module Module1
Sub Print(ls As List(Of Integer))
Dim iter = ls.GetEnumerator
Console.Write("[")
If iter.MoveNext Then
Console.Write(iter.Current)
End If
While iter.MoveNext
Console.Write(", ")
Console.Write(iter.Current)
End While
... | local N = 2
local base = 10
local c1 = 0
local c2 = 0
for k = 1, math.pow(base, N) - 1 do
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
io.write(k .. ' ')
end
end
print()
print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.