Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <iostream>
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif
int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return... | require "lfs"
local out
if lfs.attributes('/dev/tape') then
out = '/dev/tape'
else
out = 'tape.file'
end
file = io.open(out, 'w')
file:write('Hello world')
io.close(file)
|
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
... | 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... |
Translate this program into Lua but keep the logic exactly as in C++. | #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
... | 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... |
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <functional>
template <typename F>
struct RecursiveFunc {
std::function<F(RecursiveFunc)> o;
};
template <typename A, typename B>
std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {
RecursiveFunc<std::function<B(A)>> r = {
std::function<std::function<B(... | 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
|
Produce a language-to-language conversion: from C++ to Lua, same semantics. | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false;
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
... | colors = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }
print("unsorted: " .. table.concat(colors," "))
known, notyn, nc, nq = {}, {n="y",y="n"}, 0, 0
table.sort(colors, function(a,b)
nc = nc + 1
if not known[a] then known[a]={[a]="n"} end
if not known[b] then known[b]={[b]="n"} end
if not ... |
Translate this program into Lua but keep the logic exactly as in C++. |
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
void distribute(int dist, vector<int> &List) {
if (dist > List.size() )
List.resize(dist);
for (int i=0; i < dist; i++)
List[i]++;
}
vector<int> beadSort(int *myints, int n) {
vector<int> list, list2, fifth ... |
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(... |
Write the same code in Lua as shown below in C++. |
#include <iostream>
int main() {
int Base = 10;
const int N = 2;
int c1 = 0;
int c2 = 0;
for (int k=1; k<pow((double)Base,N); k++){
c1++;
if (k%(Base-1) == (k*k)%(Base-1)){
c2++;
std::cout << k << " ";
}
}
std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ... | 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.... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? |
#include <iostream>
int main() {
int Base = 10;
const int N = 2;
int c1 = 0;
int c2 = 0;
for (int k=1; k<pow((double)Base,N); k++){
c1++;
if (k%(Base-1) == (k*k)%(Base-1)){
c2++;
std::cout << k << " ";
}
}
std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ... | 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.... |
Convert this C++ snippet to Lua and keep its semantics consistent. | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" <... | function runCode( code )
local acc, lc = 0
for i = 1, #code do
lc = code:sub( i, i ):upper()
if lc == "Q" then print( lc )
elseif lc == "H" then print( "Hello, World!" )
elseif lc == "+" then acc = acc + 1
elseif lc == "9" then
for j = 99, 1, -1 do
... |
Transform the following C++ implementation into Lua, maintaining the same output and logic. | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" <... | function runCode( code )
local acc, lc = 0
for i = 1, #code do
lc = code:sub( i, i ):upper()
if lc == "Q" then print( lc )
elseif lc == "H" then print( "Hello, World!" )
elseif lc == "+" then acc = acc + 1
elseif lc == "9" then
for j = 99, 1, -1 do
... |
Produce a functionally identical Lua code for the snippet given in C++. | #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;
... | function divisorCount(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = tot... |
Write the same algorithm in Lua as shown in this C++ implementation. | #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;
... | function divisorCount(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = tot... |
Port the following code from C++ to Lua with equivalent syntax and logic. | #include <iomanip>
#include <iostream>
#include <vector>
constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;
int mobiusFunction(int n) {
if (!MU.empty()) {
return MU[n];
}
MU.resize(MU_MAX + 1, 1);
int root = sqrt(MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1)... | function buildArray(size, value)
local tbl = {}
for i=1, size do
table.insert(tbl, value)
end
return tbl
end
MU_MAX = 1000000
sqroot = math.sqrt(MU_MAX)
mu = buildArray(MU_MAX, 1)
for i=2, sqroot do
if mu[i] == 1 then
for j=i, MU_MAX, i do
mu[j] = mu[j] * -i
... |
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
... | suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"}
stack = setmetatable({
__unm = function(z)
local ret = {}
for i = #z, 1, -1 do
ret[#ret + 1] = table.remove(z,math.random(i))
end
return setmetatable(ret, stack)
end,
__add = function(z, z2)
for ... |
Ensure the translated Lua code behaves exactly like the original C++ snippet. | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
contin... | local function phi(n)
assert(type(n) == 'number', 'n must be a number!')
local result, i = n, 2
while i <= n do
if n % i == 0 then
while n % i == 0 do n = n // i end
result = result - (result // i)
end
if i == 2 then i = 1 end
i = i + 2
end
if n > 1 then result = result - (res... |
Write the same code in Lua as shown below in C++. | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
contin... | local function phi(n)
assert(type(n) == 'number', 'n must be a number!')
local result, i = n, 2
while i <= n do
if n % i == 0 then
while n % i == 0 do n = n // i end
result = result - (result // i)
end
if i == 2 then i = 1 end
i = i + 2
end
if n > 1 then result = result - (res... |
Ensure the translated Lua code behaves exactly like the original C++ snippet. | #include <iostream>
#include <map>
#include <tuple>
#include <vector>
using namespace std;
pair<int, int> twoSum(vector<int> numbers, int sum) {
auto m = map<int, int>();
for (size_t i = 0; i < numbers.size(); ++i) {
auto key = sum - numbers[i];
if (m.find(key) != m.end()) {
return make_pair(m[key], i);
... | function twoSum (numbers, sum)
local i, j, s = 1, #numbers
while i < j do
s = numbers[i] + numbers[j]
if s == sum then
return {i, j}
elseif s < sum then
i = i + 1
else
j = j - 1
end
end
return {}
end
print(table.concat(twoSum({... |
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <iostream>
#include <map>
#include <tuple>
#include <vector>
using namespace std;
pair<int, int> twoSum(vector<int> numbers, int sum) {
auto m = map<int, int>();
for (size_t i = 0; i < numbers.size(); ++i) {
auto key = sum - numbers[i];
if (m.find(key) != m.end()) {
return make_pair(m[key], i);
... | function twoSum (numbers, sum)
local i, j, s = 1, #numbers
while i < j do
s = numbers[i] + numbers[j]
if s == sum then
return {i, j}
elseif s < sum then
i = i + 1
else
j = j - 1
end
end
return {}
end
print(table.concat(twoSum({... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
typedef uint32_t integer;
int count_digits(integer n) {
int digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
integer change_digit(integer n, int index, int new_digit) {
integer p = 1;
integer changed = 0;
... |
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.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 = {}, 10000000
for i = 2,S ... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? | #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;
... | function divisor_count(n)
local total = 1
while (n & 1) == 0 do
total = total + 1
n = n >> 1
end
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = math.floor(n / p)
end
total = ... |
Write the same code in Lua as shown below in C++. | #include <cstdio>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
for (int x : lst) w.push_back({x, x});
while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
for (int x : lst) if ((sum = get<1>(i) + x) == 13)
... | function prime_digits_sum_13(n)
local sum = 0
while n > 0 do
local r = n % 10
if r ~= 2 and r ~= 3 and r ~= 5 and r ~= 7 then
return false
end
n = math.floor(n / 10)
sum = sum + r
end
return sum == 13
end
local c = 0
for i=1,999999 do
if prime_dig... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <cstdio>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
for (int x : lst) w.push_back({x, x});
while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
for (int x : lst) if ((sum = get<1>(i) + x) == 13)
... | function prime_digits_sum_13(n)
local sum = 0
while n > 0 do
local r = n % 10
if r ~= 2 and r ~= 3 and r ~= 5 and r ~= 7 then
return false
end
n = math.floor(n / 10)
sum = sum + r
end
return sum == 13
end
local c = 0
for i=1,999999 do
if prime_dig... |
Write a version of this C++ function in Lua with identical behavior. | #include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
int main()
{
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumber... | function _deepcopy(o, tables)
if type(o) ~= 'table' then
return o
end
if tables[o] ~= nil then
return tables[o]
end
local new_o = {}
tables[o] = new_o
for k, v in next, o, nil do
local new_k = _deepcopy(k, tables)
local new_v = _deepcopy(v, tables)
new_o[new_k] = new_v
end
... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
int main()
{
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumber... | function _deepcopy(o, tables)
if type(o) ~= 'table' then
return o
end
if tables[o] ~= nil then
return tables[o]
end
local new_o = {}
tables[o] = new_o
for k, v in next, o, nil do
local new_k = _deepcopy(k, tables)
local new_v = _deepcopy(v, tables)
new_o[new_k] = new_v
end
... |
Write the same code in Lua as shown below in C++. | #include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_prime(const integer& n, int reps = 50) {
return mpz_probab_prime_p(n.get_mpz_t(), reps);
}
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
r... |
local function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
for f = 5, math.sqrt(n), 6 do
if n % f == 0 or n % (f+2) == 0 then return false end
end
return true
end
local function iscircularprime(p)
local n = math.floor(math.log10(p))... |
Convert this C++ block to Lua, preserving its control flow and logic. | #include <algorithm>
template<typename ForwardIterator>
void permutation_sort(ForwardIterator begin, ForwardIterator end)
{
while (std::next_permutation(begin, end))
{
}
}
|
function permute (list)
local function perm (list, n)
if n == 0 then coroutine.yield(list) end
for i = 1, n do
list[i], list[n] = list[n], list[i]
perm(list, n - 1)
list[i], list[n] = list[n], list[i]
end
end
return coroutine.wrap(function() perm(list, #list) end)
end
function inO... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? | #include <iostream>
#include <math.h>
unsigned long long root(unsigned long long base, unsigned int n) {
if (base < 2) return base;
if (n == 0) return 1;
unsigned int n1 = n - 1;
unsigned long long n2 = n;
unsigned long long n3 = n1;
unsigned long long c = 1;
auto d = (n3 + base) / n2;
auto e = (n3 * d + base... | function root(base, n)
if base < 2 then return base end
if n == 0 then return 1 end
local n1 = n - 1
local n2 = n
local n3 = n1
local c = 1
local d = math.floor((n3 + base) / n2)
local e = math.floor((n3 * d + base / math.pow(d, n1)) / n2)
while c ~= d and c ~= e do
c = d
... |
Transform the following C++ implementation into Lua, maintaining the same output and logic. | #include <iostream>
#include <math.h>
unsigned long long root(unsigned long long base, unsigned int n) {
if (base < 2) return base;
if (n == 0) return 1;
unsigned int n1 = n - 1;
unsigned long long n2 = n;
unsigned long long n3 = n1;
unsigned long long c = 1;
auto d = (n3 + base) / n2;
auto e = (n3 * d + base... | function root(base, n)
if base < 2 then return base end
if n == 0 then return 1 end
local n1 = n - 1
local n2 = n
local n3 = n1
local c = 1
local d = math.floor((n3 + base) / n2)
local e = math.floor((n3 * d + base / math.pow(d, n1)) / n2)
while c ~= d and c ~= e do
c = d
... |
Please provide an equivalent version of this C++ code in Lua. | int meaning_of_life();
| #!/usr/bin/env lua
function meaningoflife()
return 42
end
function main(arg)
print("Main: The meaning of life is " .. meaningoflife())
end
if type(package.loaded[(...)]) ~= "userdata" then
main(arg)
else
module(..., package.seeall)
end
|
Please provide an equivalent version of this C++ code in Lua. | int meaning_of_life();
| #!/usr/bin/env lua
function meaningoflife()
return 42
end
function main(arg)
print("Main: The meaning of life is " .. meaningoflife())
end
if type(package.loaded[(...)]) ~= "userdata" then
main(arg)
else
module(..., package.seeall)
end
|
Convert this C++ block to Lua, preserving its control flow and logic. | #include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
... | function isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
local p = 5
while p * p <= n do
if n % p == 0 then
return false
end
p = p + 2
if n % p == 0 th... |
Port the following code from C++ to Lua with equivalent syntax and logic. | #include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
... | function isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
local p = 5
while p * p <= n do
if n % p == 0 then
return false
end
p = p + 2
if n % p == 0 th... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class lastSunday
{
public:
lastSunday()
{
m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: ";
m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";... | function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
function dayOfWeek (y, m, d)
local t = os.time({year = y, month = m, day = d})
return os.date("%A", t)
end
function lastWeekdays (wday, year)
local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if... |
Write the same algorithm in Lua as shown in this C++ implementation. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class lastSunday
{
public:
lastSunday()
{
m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: ";
m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";... | function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
function dayOfWeek (y, m, d)
local t = os.time({year = y, month = m, day = d})
return os.date("%A", t)
end
function lastWeekdays (wday, year)
local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if... |
Port the following code from C++ to Lua with equivalent syntax and logic. | #include <iostream>
#include <vector>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
printf("Base %2d:", base);
for (int i = 0; i < count; i++) {
... | function turn(base, n)
local sum = 0
while n ~= 0 do
local re = n % base
n = math.floor(n / base)
sum = sum + re
end
return sum % base
end
function fairShare(base, count)
io.write(string.format("Base %2d:", base))
for i=1,count do
local t = turn(base, i - 1)
... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <functional>
#include <iostream>
#include <sstream>
#include <vector>
std::string to(int n, int b) {
static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::stringstream ss;
while (n > 0) {
auto rem = n % b;
n = n / b;
ss << BASE[rem];
}
auto fwd = ss.str(... | function to(n, b)
local BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n == 0 then
return "0"
end
local ss = ""
while n > 0 do
local idx = (n % b) + 1
n = math.floor(n / b)
ss = ss .. BASE:sub(idx, idx)
end
return string.reverse(ss)
end
function isEstheti... |
Change the following C++ code into Lua without altering its purpose. | #include <iostream>
bool ispr(unsigned int n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (unsigned int j = 3; j * j <= n; j += 2)
if (n % j == 0) return false; return true; }
int main() {
unsigned int c = 0, nc, pc = 9, i, a, b, l,
ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];
while (true... | local function is_prime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
for f = 5, n^0.5, 6 do
if n%f==0 or n%(f+2)==0 then return false end
end
return true
end
local function descending_primes()
local digits, candidates, primes = {9,8,7,6,5,4,3... |
Please provide an equivalent version of this C++ code in Lua. | #include <iostream>
#include <vector>
using namespace std;
vector<int> UpTo(int n, int offset = 0)
{
vector<int> retval(n);
for (int ii = 0; ii < n; ++ii)
retval[ii] = ii + offset;
return retval;
}
struct JohnsonTrotterState_
{
vector<int> values_;
vector<int> positions_;
vector<bool> directions_;
int sign... | _JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
setmetatable(n,{__index=_JT})
for i=1,dim do
n.values[i]=i
n.positions[i]=i
n.directions[i]=-1
end
return n
end
function _JT:largestMobile()
for i=#self.values,1,-1 do
local loc=self.positions[i]+self.directi... |
Translate this program into Lua but keep the logic exactly as in C++. | #include <iostream>
#include <vector>
using Sequence = std::vector<int>;
std::ostream& operator<<(std::ostream& os, const Sequence& v) {
os << "[ ";
for (const auto& e : v) {
std::cout << e << ", ";
}
os << "]";
return os;
}
int next_in_cycle(const Sequence& s, size_t i) {
return s[i % s.size()];
}
... | function next_in_cycle(c,length,index)
local pos = index % length
return c[pos]
end
function kolakoski(c,s,clen,slen)
local i = 0
local k = 0
while true do
s[i] = next_in_cycle(c,clen,k)
if s[k] > 1 then
for j=1,s[k]-1 do
i = i + 1
if i =... |
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version. | #include <vector>
#include <list>
#include <algorithm>
#include <iostream>
template <typename T>
struct Node {
T value;
Node* prev_node;
};
template <typename Container>
Container lis(const Container& values) {
using E = typename Container::value_type;
using NodePtr = Node<E>*;
using ConstNodePtr ... | function buildLIS(seq)
local piles = { { {table.remove(seq, 1), nil} } }
while #seq>0 do
local x=table.remove(seq, 1)
for j=1,#piles do
if piles[j][#piles[j]][1]>x then
table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])})
break
elseif ... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char** argv) {
const int min_length = 9;
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std... | wordlist, wordhash = {}, {}
for word in io.open("unixdict.txt", "r"):lines() do
if #word >= 9 then
wordlist[#wordlist+1] = word
wordhash[word] = #wordlist
end
end
for n = 1, #wordlist-8 do
local word = ""
for i = 0, 8 do
word = word .. wordlist[n+i]:sub(i+1,i+1)
end
if wordhash[word] then
... |
Port the provided C++ code into Lua while preserving the original functionality. | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
template <typename T>
void print(const std::vector<T> v) {
std::cout << "{ ";
for (const auto& e : v) {
std::cout << e << " ";
}
std::cout << "}";
}
template <typename T>
auto orderDisjointArrayItems(std::vector<T> M, std::vector... |
function split (str)
local t = {}
for word in str:gmatch("%S+") do table.insert(t, word) end
return t
end
function orderList (dataStr, orderStr)
local data, order = split(dataStr), split(orderStr)
for orderPos, orderWord in pairs(order) do
for dataPos, dataWord in pairs(data) do
... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/gmp.hpp>
using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;
class harmonic_generator {
public:
rational next() {
rational result = term_;
term_ += rational(1,... |
function harmonic (n)
if n < 1 or n ~= math.floor(n) then
error("Argument to harmonic function is not a natural number")
end
local Hn = 1
for i = 2, n do
Hn = Hn + (1/i)
end
return Hn
end
for x = 1, 20 do
print(x .. " :\t" .. harmonic(x))
end
local x, lastInt, Hx = 0, 1
... |
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <fstream>
#include <iostream>
#include <locale>
using namespace std;
int main(void)
{
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
ifstream in("input.txt");
wchar_t c;
while ((c = in.get()) != in.eof())
wcout<<c;
in.close();
return EXIT_... |
function is_ascii (str)
return string.match(str, "[\0-\x7F]")
end
function is_init (str)
return string.match(str, "[\xC2-\xF4]")
end
function is_cont (str)
return string.match(str, "[\x80-\xBF]")
end
function read_char (file)
local multibyte
for c in file:lines(1) do
if is_ascii(c) t... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject(... | Bitmap.render = function(self)
for y = 1, self.height do
print(table.concat(self.pixels[y], " "))
end
end
math.randomseed(os.time())
local W, H, MIDX = 15, 40, 7
local bitmap = Bitmap(W, H)
local AIR, PIN, BALL, FLOOR = ".", "▲", "☻", "■"
local nballs, balls = 60, {}
local frame, showEveryFrame = 1, false
b... |
Ensure the translated Lua code behaves exactly like the original C++ snippet. | #include <iostream>
int circlesort(int* arr, int lo, int hi, int swaps) {
if(lo == hi) {
return swaps;
}
int high = hi;
int low = lo;
int mid = (high - low) / 2;
while(lo < hi) {
if(arr[lo] > arr[hi]) {
int temp = arr[lo];
arr[lo] = arr[hi];
a... |
function innerCircle (t, lo, hi, swaps)
if lo == hi then return swaps end
local high, low, mid = hi, lo, math.floor((hi - lo) / 2)
while lo < hi do
if t[lo] > t[hi] then
t[lo], t[hi] = t[hi], t[lo]
swaps = swaps + 1
end
lo = lo + 1
hi = hi - 1
end
if lo == hi then
if t[lo] > t... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <array>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
class letterset {
public:
letterset() {
count_.fill(0);
}
explicit letterset(const std::string& str) {
count_.fill(0);
for (char c : str)... | LetterCounter = {
new = function(self, word)
local t = { word=word, letters={} }
for ch in word:gmatch(".") do t.letters[ch] = (t.letters[ch] or 0) + 1 end
return setmetatable(t, self)
end,
contains = function(self, other)
for k,v in pairs(other.letters) do
if (self.letters[k] or 0) < v then... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? | #include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace detail {
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(end... | local function wrapEachItem(items, prefix, suffix)
local itemsWrapped = {}
for i, item in ipairs(items) do
itemsWrapped[i] = prefix .. item .. suffix
end
return itemsWrapped
end
local function getAllItemCombinationsConcatenated(aItems, bItems)
local combinations = {}
for _, a in ipairs(aItems) do
for _, b... |
Please provide an equivalent version of this C++ code in Lua. | #include <iostream>
#include <cmath>
#include <tuple>
struct point { double x, y; };
bool operator==(const point& lhs, const point& rhs)
{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }
enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };
using result_t = std::tuple<result_categor... | function distance(p1, p2)
local dx = (p1.x-p2.x)
local dy = (p1.y-p2.y)
return math.sqrt(dx*dx + dy*dy)
end
function findCircles(p1, p2, radius)
local seperation = distance(p1, p2)
if seperation == 0.0 then
if radius == 0.0 then
print("No circles can be drawn through ("..p1.x.."... |
Transform the following C++ implementation into Lua, maintaining the same output and logic. | #include <iostream>
#include <cmath>
#include <tuple>
struct point { double x, y; };
bool operator==(const point& lhs, const point& rhs)
{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }
enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };
using result_t = std::tuple<result_categor... | function distance(p1, p2)
local dx = (p1.x-p2.x)
local dy = (p1.y-p2.y)
return math.sqrt(dx*dx + dy*dy)
end
function findCircles(p1, p2, radius)
local seperation = distance(p1, p2)
if seperation == 0.0 then
if radius == 0.0 then
print("No circles can be drawn through ("..p1.x.."... |
Write the same code in Lua as shown below in C++. | #include <array>
#include <iostream>
template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;
struct Cistercian {
public:
Cistercian() {
initN();
}
Cistercian(int v) {
initN();
draw(v);
}
Cistercian &operator=(int v) {
initN();
... | function initN()
local n = {}
for i=1,15 do
n[i] = {}
for j=1,11 do
n[i][j] = " "
end
n[i][6] = "x"
end
return n
end
function horiz(n, c1, c2, r)
for c=c1,c2 do
n[r+1][c+1] = "x"
end
end
function verti(n, r1, r2, c)
for r=r1,r2 do
... |
Write the same code in Lua as shown below in C++. | #include <array>
#include <iostream>
template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;
struct Cistercian {
public:
Cistercian() {
initN();
}
Cistercian(int v) {
initN();
draw(v);
}
Cistercian &operator=(int v) {
initN();
... | function initN()
local n = {}
for i=1,15 do
n[i] = {}
for j=1,11 do
n[i][j] = " "
end
n[i][6] = "x"
end
return n
end
function horiz(n, c1, c2, r)
for c=c1,c2 do
n[r+1][c+1] = "x"
end
end
function verti(n, r1, r2, c)
for r=r1,r2 do
... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? | #include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;
class poker
{
public:
poker() { face = "A23456789TJQK"; suit = "SHCD"; }
string analyze( string h )
{
memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand;
transform( h.begin(), h.end(), ... |
function valid (t)
if #t ~= 5 then return false end
for k, v in pairs(t) do
for key, card in pairs(t) do
if v.value == card.value and
v.suit == card.suit and
k ~= key
then
return false
end
end
end
retur... |
Maintain the same structure and functionality when rewriting this code in Lua. | #include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;
class poker
{
public:
poker() { face = "A23456789TJQK"; suit = "SHCD"; }
string analyze( string h )
{
memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand;
transform( h.begin(), h.end(), ... |
function valid (t)
if #t ~= 5 then return false end
for k, v in pairs(t) do
for key, card in pairs(t) do
if v.value == card.value and
v.suit == card.suit and
k ~= key
then
return false
end
end
end
retur... |
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <windows.h>
#include <string>
using namespace std;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, siz... | RIGHT, LEFT, UP, DOWN = 1, 2, 4, 8
function drawFractals( w )
love.graphics.setCanvas( canvas )
love.graphics.clear()
love.graphics.setColor( 255, 255, 255 )
local dir, facing, lineLen, px, py, c = RIGHT, UP, 1, 10, love.graphics.getHeight() - 20, 1
local x, y = 0, -lineLen
local pts = {}
ta... |
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <time.h>
#include <iostream>
#include <string>
using namespace std;
class penney
{
public:
penney()
{ pW = cW = 0; }
void gameLoop()
{
string a;
while( true )
{
playerChoice = computerChoice = "";
if( rand() % 2 )
{ computer(); player(); }
else
{ player(); comput... | function penny_game()
local player, computer = "", ""
function player_choose()
io.write( "Enter your sequence of three H and/or T: " )
local t = io.read():upper()
if #t > 3 then t = t:sub( 1, 3 )
elseif #t < 3 then return ""
end
for i = 1, 3 do
c = t:... |
Generate a Lua translation of this C++ snippet without changing its computational steps. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( ... |
function sierpinski (tri, order)
local new, p, t = {}
if order > 0 then
for i = 1, #tri do
p = i + 2
if p > #tri then p = p - #tri end
new[i] = (tri[i] + tri[p]) / 2
end
sierpinski({tri[1],tri[2],new[1],new[2],new[5],new[6]}, order-1)
sierpins... |
Translate the given C++ code snippet into Lua without altering its behavior. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( ... |
function sierpinski (tri, order)
local new, p, t = {}
if order > 0 then
for i = 1, #tri do
p = i + 2
if p > #tri then p = p - #tri end
new[i] = (tri[i] + tri[p]) / 2
end
sierpinski({tri[1],tri[2],new[1],new[2],new[5],new[6]}, order-1)
sierpins... |
Ensure the translated Lua code behaves exactly like the original C++ snippet. | #include <iomanip>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>
typedef std::pair<int, std::vector<int> > puzzle;
class nonoblock {
public:
void solve( std::vector<puzzle>& p ) {
for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) {
... | local examples = {
{5, {2, 1}},
{5, {}},
{10, {8}},
{15, {2, 3, 2, 3}},
{5, {2, 3}},
}
function deep (blocks, iBlock, freedom, str)
if iBlock == #blocks then
for takenFreedom = 0, freedom do
print (str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. string.rep("0", freedom - takenFreed... |
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <iomanip>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>
typedef std::pair<int, std::vector<int> > puzzle;
class nonoblock {
public:
void solve( std::vector<puzzle>& p ) {
for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) {
... | local examples = {
{5, {2, 1}},
{5, {}},
{10, {8}},
{15, {2, 3, 2, 3}},
{5, {2, 3}},
}
function deep (blocks, iBlock, freedom, str)
if iBlock == #blocks then
for takenFreedom = 0, freedom do
print (str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. string.rep("0", freedom - takenFreed... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <iostream>
struct Interval {
int start, end;
bool print;
};
int main() {
Interval intervals[] = {
{2, 1000, true},
{1000, 4000, true},
{2, 10000, false},
{2, 100000, false},
{2, 1000000, false},
{2, 10000000, false},
{2, 100000000, false},
... | function makeInterval(s,e,p)
return {start=s, end_=e, print_=p}
end
function main()
local intervals = {
makeInterval( 2, 1000, true),
makeInterval(1000, 4000, true),
makeInterval( 2, 10000, false),
makeInterval( 2, 1000000, false),
makeInterval(... |
Convert this C++ snippet to Lua and keep its semantics consistent. | #include <iostream>
struct Interval {
int start, end;
bool print;
};
int main() {
Interval intervals[] = {
{2, 1000, true},
{1000, 4000, true},
{2, 10000, false},
{2, 100000, false},
{2, 1000000, false},
{2, 10000000, false},
{2, 100000000, false},
... | function makeInterval(s,e,p)
return {start=s, end_=e, print_=p}
end
function main()
local intervals = {
makeInterval( 2, 1000, true),
makeInterval(1000, 4000, true),
makeInterval( 2, 10000, false),
makeInterval( 2, 1000000, false),
makeInterval(... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #include <iostream>
bool valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) {
if (nuts % n != 1) {
return false;
}
}
return nuts != 0 && (nuts % n == 0);
}
int main() {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x)) {
... | function valid(n,nuts)
local k = n
local i = 0
while k ~= 0 do
if (nuts % n) ~= 1 then
return false
end
k = k - 1
nuts = nuts - 1 - math.floor(nuts / n)
end
return nuts ~= 0 and (nuts % n == 0)
end
for n=2, 9 do
local x = 0
while not valid(n, x) d... |
Port the following code from C++ to Lua with equivalent syntax and logic. | #include <iostream>
bool valid(int n, int nuts) {
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) {
if (nuts % n != 1) {
return false;
}
}
return nuts != 0 && (nuts % n == 0);
}
int main() {
int x = 0;
for (int n = 2; n < 10; n++) {
while (!valid(n, x)) {
... | function valid(n,nuts)
local k = n
local i = 0
while k ~= 0 do
if (nuts % n) ~= 1 then
return false
end
k = k - 1
nuts = nuts - 1 - math.floor(nuts / n)
end
return nuts ~= 0 and (nuts % n == 0)
end
for n=2, 9 do
local x = 0
while not valid(n, x) d... |
Convert this C++ block to Lua, preserving its control flow and logic. | #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER... | c = string.char
midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96)
midi = midi .. "MTrk" .. c(0,0,0,8*8+4)
for _,note in ipairs{60,62,64,65,67,69,71,72} do
midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0)
end
midi = midi .. c(0, 0xFF, 0x2F, 0)
file = io.open("scale.mid", "wb")
file:write(midi)
file:close()
mid... |
Port the following code from C++ to Lua with equivalent syntax and logic. | #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER... | c = string.char
midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96)
midi = midi .. "MTrk" .. c(0,0,0,8*8+4)
for _,note in ipairs{60,62,64,65,67,69,71,72} do
midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0)
end
midi = midi .. c(0, 0xFF, 0x2F, 0)
file = io.open("scale.mid", "wb")
file:write(midi)
file:close()
mid... |
Generate a Lua translation of this C++ snippet without changing its computational steps. | #include <windows.h>
#include <sstream>
#include <ctime>
const float PI = 3.1415926536f, TWO_PI = 2.f * PI;
class vector2
{
public:
vector2( float a = 0, float b = 0 ) { set( a, b ); }
void set( float a, float b ) { x = a; y = b; }
void rotate( float r ) {
float _x = x, _y = y,
s = s... | function love.load ()
love.window.setTitle("Polyspiral")
incr = 0
end
function love.update (dt)
incr = (incr + 0.05) % 360
x1 = love.graphics.getWidth() / 2
y1 = love.graphics.getHeight() / 2
length = 5
angle = incr
end
function love.draw ()
for i = 1, 150 do
x2 = x1 + math.cos... |
Can you help me rewrite this code in Lua instead of C++, keeping it the same logically? | #include <windows.h>
#include <sstream>
#include <ctime>
const float PI = 3.1415926536f, TWO_PI = 2.f * PI;
class vector2
{
public:
vector2( float a = 0, float b = 0 ) { set( a, b ); }
void set( float a, float b ) { x = a; y = b; }
void rotate( float r ) {
float _x = x, _y = y,
s = s... | function love.load ()
love.window.setTitle("Polyspiral")
incr = 0
end
function love.update (dt)
incr = (incr + 0.05) % 360
x1 = love.graphics.getWidth() / 2
y1 = love.graphics.getHeight() / 2
length = 5
angle = incr
end
function love.draw ()
for i = 1, 150 do
x2 = x1 + math.cos... |
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMem... | function love.load( )
love.math.setRandomSeed( os.time( ) )
keys = { }
number_cells = 50
voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )
end
function hypot( x, y )
return math.sqrt( x*x + y*y )
end
function generateVoronoi( width, height, num_cells )
... |
Transform the following C++ implementation into Lua, maintaining the same output and logic. | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMem... | function love.load( )
love.math.setRandomSeed( os.time( ) )
keys = { }
number_cells = 50
voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )
end
function hypot( x, y )
return math.sqrt( x*x + y*y )
end
function generateVoronoi( width, height, num_cells )
... |
Generate an equivalent Lua version of this C++ code. | #include <functional>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp>
template<typename T>
T normalize(T a, double b) { return std::fmod(a, b); }
inline double d2d(double a) { return normalize<double>(a, 360); }
inline double g2g(doub... | range = { degrees=360, gradians=400, mils=6400, radians=2.0*math.pi }
function convert(value, fromunit, tounit)
return math.fmod(value * range[tounit] / range[fromunit], range[tounit])
end
testvalues = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }
testunits = { "degrees", "gradians", "mils"... |
Produce a language-to-language conversion: from C++ to Lua, same semantics. | #include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>
#include <libxml/xpath.h>
#ifndef LIBXML_XPATH_ENABLED
# e... | require 'lxp'
data = [[<inventory title="OmniCorp Store #45x10^3">
<section name="health">
<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>
<item upc="445322344" stock="18">
<name>Levitatio... |
Port the provided C++ code into Lua while preserving the original functionality. | #include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
class StraddlingCheckerboard
{
map<char, string> table;
char first[10], second[10], third[10];
int rowU, rowV;
public:
StraddlingCheckerboard(const string &alphabet, int u, int v)
{
rowU = min(u, v);
rowV... | local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" }
local dicE, dicD, s1, s2 = {}, {}, 0, 0
function dec( txt )
local i, numb, s, t, c = 1, false
while( i < #txt ) do
c = txt:sub( i, i )
if not numb then
if tonumber( c ) == s1 then
i = i + 1; s = string.format( ... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #include <iostream>
#include <fstream>
#include <string>
#include <tuple>
#include <vector>
#include <stdexcept>
#include <boost/regex.hpp>
struct Claim {
Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() {
}
void add_pro(const std::string... |
local http = require("socket.http")
function count (pattern, wordList)
local total = 0
for word in wordList:gmatch("%S+") do
if word:match(pattern) then total = total + 1 end
end
return total
end
function plaus (case, opposite, words)
if count(case, words) > 2 * count(opposite, words) t... |
Please provide an equivalent version of this C++ code in Lua. | #include <iostream>
#include <fstream>
#include <string>
#include <tuple>
#include <vector>
#include <stdexcept>
#include <boost/regex.hpp>
struct Claim {
Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() {
}
void add_pro(const std::string... |
local http = require("socket.http")
function count (pattern, wordList)
local total = 0
for word in wordList:gmatch("%S+") do
if word:match(pattern) then total = total + 1 end
end
return total
end
function plaus (case, opposite, words)
if count(case, words) > 2 * count(opposite, words) t... |
Translate this program into Lua but keep the logic exactly as in C++. | #include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include "xtensor-io/ximage.hpp"
xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim)
{
xt::xarray<int>::shape_type shape = { x_dim, y_dim };
xt::xarray<int> grid(shape);
grid(x_dim/2, y_dim/2) = 64000;
r... | local sandpile = {
init = function(self, dim, val)
self.cell, self.dim = {}, dim
for r = 1, dim do
self.cell[r] = {}
for c = 1, dim do
self.cell[r][c] = 0
end
end
self.cell[math.floor(dim/2)+1][math.floor(dim/2)+1] = val
end,
iter = function(self)
local dim, cel, more... |
Please provide an equivalent version of this C++ code in Lua. | #include <iostream>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include "xtensor-io/ximage.hpp"
xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim)
{
xt::xarray<int>::shape_type shape = { x_dim, y_dim };
xt::xarray<int> grid(shape);
grid(x_dim/2, y_dim/2) = 64000;
r... | local sandpile = {
init = function(self, dim, val)
self.cell, self.dim = {}, dim
for r = 1, dim do
self.cell[r] = {}
for c = 1, dim do
self.cell[r][c] = 0
end
end
self.cell[math.floor(dim/2)+1][math.floor(dim/2)+1] = val
end,
iter = function(self)
local dim, cel, more... |
Change the following C++ code into Lua without altering its purpose. | #include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
using integer = mpz_class;
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
return out.str();
}
integer next_highest(const integer& n) {
std::string str(to_string(n));
if (!std::next_permuta... | unpack = unpack or table.unpack
function nexthighestint(n)
local digits, index = {}, {[0]={},{},{},{},{},{},{},{},{},{}}
for d in tostring(n):gmatch("%d") do digits[#digits+1]=tonumber(d) end
for i,d in ipairs(digits) do index[d][#index[d]+1]=i end
local function findswap(i,d)
for D=d+1,9 do
for I... |
Write the same algorithm in Lua as shown in this C++ implementation. | #include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
using integer = mpz_class;
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
return out.str();
}
integer next_highest(const integer& n) {
std::string str(to_string(n));
if (!std::next_permuta... | unpack = unpack or table.unpack
function nexthighestint(n)
local digits, index = {}, {[0]={},{},{},{},{},{},{},{},{},{}}
for d in tostring(n):gmatch("%d") do digits[#digits+1]=tonumber(d) end
for i,d in ipairs(digits) do index[d][#index[d]+1]=i end
local function findswap(i,d)
for D=d+1,9 do
for I... |
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <iostream>
#include <string>
#include <cctype>
#include <cstdint>
typedef std::uint64_t integer;
const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen"... |
local oneslist = { [0]="", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
local teenlist = { [0]="ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }
local tenslist = { [0]="", "", "twenty", "thirty", "forty", "fifty", "sixty", "sevent... |
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <iomanip>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
constexpr double degrees(double deg) {
const double tau = 2.0 * M_PI;
return deg * tau / 360.0;
}
const double part_ratio = 2.0 * cos(degrees(72));
const double side_ratio = 1.0 / (part_ratio + 2.0);
struct Point {
doubl... | Bitmap.chaosgame = function(self, n, r, niters)
local w, h, vertices = self.width, self.height, {}
for i = 1, n do
vertices[i] = {
x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n),
y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n)
}
end
local x, y = w/2, h/2
for i = 1, niters do
... |
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <string>
#include <time.h>
using namespace std;
namespace
{
void placeRandomly(char* p, char c)
{
int loc = rand() % 8;
if (!p[loc])
p[loc] = c;
else
placeRandomly(p, c);
}
int placeFirst(char* p, char c, int loc = 0)
{
while (p[loc]) ++loc;
p[loc] = ... |
function randomInsert (t, str, left, right)
local pos
repeat pos = math.random(left, right) until not t[pos]
t[pos] = str
return pos
end
function chess960 ()
local t, b1, b2 = {}
local kingPos = randomInsert(t, "K", 2, 7)
randomInsert(t, "R", 1, kingPos - 1)
randomInsert(t, "R", kingP... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <iostream>
#include <utility>
#include <vector>
using Point = std::pair<double, double>;
constexpr auto eps = 1e-14;
std::ostream &operator<<(std::ostream &os, const Point &p) {
auto x = p.first;
if (x == 0.0) {
x = 0.0;
}
auto y = p.second;
if (y == 0.0) {
y = 0.0;
}
... | EPS = 1e-14
function pts(p)
local x, y = p.x, p.y
if x == 0 then
x = 0
end
if y == 0 then
y = 0
end
return "(" .. x .. ", " .. y .. ")"
end
function lts(pl)
local str = "["
for i,p in pairs(pl) do
if i > 1 then
str = str .. ", "
end
s... |
Produce a functionally identical Lua code for the snippet given in C++. | #include <iostream>
using namespace std;
string redact(const string &source, const string &word, bool partial, bool insensitive, bool overkill) {
string temp = source;
auto different = [insensitive](char s, char w) {
if (insensitive) {
return toupper(s) != toupper(w);
} else {
... | function redact(text, targ, opts)
local part, case, ovrk = opts:find("p")~=nil, opts:find("s")~=nil, opts:find("o")~=nil
local oknp = ovrk or not part
local patt = oknp and "([%w%-]+)" or "(%w+)"
local ci = case and function(s) return s end or function(s) return s:lower() end
local matches = function(s,w) ret... |
Change the following C++ code into Lua without altering its purpose. | class animal {
public:
virtual void bark()
{
throw "implement me: do not know how to bark";
}
};
class elephant : public animal
{
};
int main()
{
elephant e;
e.bark();
}
| local object={print=print}
setmetatable(object,{__index=function(t,k)return function() print("You called the method",k)end end})
object.print("Hi")
object.hello()
|
Change the following C++ code into Lua without altering its purpose. | #include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
std::map<std::string, double> atomicMass = {
{"H", 1.008},
{"He", 4.002602},
{"Li", 6.94},
{"Be", 9.0121831},
{"B", 10.81},
{"C", 12.011},
{"N", 14.007},
{"O", 15.999},
{"F... | atomicMass = {
["H"] = 1.008,
["He"] = 4.002602,
["Li"] = 6.94,
["Be"] = 9.0121831,
["B"] = 10.81,
["C"] = 12.011,
["N"] = 14.007,
["O"] = 15.999,
["F"] = 18.998403163,
["Ne"] = 20.1797,
["Na"] = 22.98976928,
["Mg"] = 24.305,
["Al"] ... |
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_no... | require"lpeg"
P, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V
expression = P{"expr";
ws = P" "^0,
number = C(R"09"^1) * V"ws",
lp = "(" * V"ws",
rp = ")" * V"ws",
sym = C(S"+-*/") * V"ws",
more = (V"sym" * V"expr")^0,
expr = V"number" * V"more" + V"lp" * lpeg.Ct(V"expr" * V"more") * V"rp" * V"more"}
functio... |
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_no... | require"lpeg"
P, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V
expression = P{"expr";
ws = P" "^0,
number = C(R"09"^1) * V"ws",
lp = "(" * V"ws",
rp = ")" * V"ws",
sym = C(S"+-*/") * V"ws",
more = (V"sym" * V"expr")^0,
expr = V"number" * V"more" + V"lp" * lpeg.Ct(V"expr" * V"more") * V"rp" * V"more"}
functio... |
Keep all operations the same but rewrite the snippet in Lua. | #include <iostream>
#include <map>
#include <random>
std::default_random_engine generator;
std::uniform_int_distribution<int> dice(1, 6);
int rollDice() {
return dice(generator);
}
const bool sixesThrowAgain = true;
const std::map<int, int> snl{
{4, 14},
{9, 31},
{17, 7},
{20, 38},
{28, 84},
... | local sixesThrowAgain = true
function rollDice()
return math.random(6)
end
function nextSquare(square)
if square == 4 then
return 14
elseif square == 9 then
return 31
elseif square == 17 then
return 7
elseif square == 20 then
return 38
elseif square == 28 then
... |
Generate an equivalent Lua version of this C++ code. | #include <iostream>
#include <map>
#include <random>
std::default_random_engine generator;
std::uniform_int_distribution<int> dice(1, 6);
int rollDice() {
return dice(generator);
}
const bool sixesThrowAgain = true;
const std::map<int, int> snl{
{4, 14},
{9, 31},
{17, 7},
{20, 38},
{28, 84},
... | local sixesThrowAgain = true
function rollDice()
return math.random(6)
end
function nextSquare(square)
if square == 4 then
return 14
elseif square == 9 then
return 31
elseif square == 17 then
return 7
elseif square == 20 then
return 38
elseif square == 28 then
... |
Write a version of this C++ function in Lua with identical behavior. | #include <iostream>
struct fraction {
fraction(int n, int d) : numerator(n), denominator(d) {}
int numerator;
int denominator;
};
std::ostream& operator<<(std::ostream& out, const fraction& f) {
out << f.numerator << '/' << f.denominator;
return out;
}
class farey_sequence {
public:
explicit ... |
function farey (n)
local a, b, c, d, k = 0, 1, 1, n
local farTab = {{a, b}}
while c <= n do
k = math.floor((n + b) / d)
a, b, c, d = c, d, k * c - a, k * d - b
table.insert(farTab, {a, b})
end
return farTab
end
for i = 1, 11 do
io.write(i .. ": ")
for _, frac in pa... |
Translate the given C++ code snippet into Lua without altering its behavior. | #include <iostream>
struct fraction {
fraction(int n, int d) : numerator(n), denominator(d) {}
int numerator;
int denominator;
};
std::ostream& operator<<(std::ostream& out, const fraction& f) {
out << f.numerator << '/' << f.denominator;
return out;
}
class farey_sequence {
public:
explicit ... |
function farey (n)
local a, b, c, d, k = 0, 1, 1, n
local farTab = {{a, b}}
while c <= n do
k = math.floor((n + b) / d)
a, b, c, d = c, d, k * c - a, k * d - b
table.insert(farTab, {a, b})
end
return farTab
end
for i = 1, 11 do
io.write(i .. ": ")
for _, frac in pa... |
Produce a language-to-language conversion: from C++ to Lua, same semantics. | #include <iostream>
#include <math.h>
struct PolarPoint;
struct CartesianPoint
{
double x;
double y;
operator PolarPoint();
};
struct PolarPoint
{
double rho;
double theta;
operator CartesianPoint();
};
CartesianPoint::operator PolarPoint()
{
return PolarPoint
... |
type(123 .. "123")
type(123 + "123")
type(123 + "foo")
function noop () end
local a = noop()
print(a)
local x, y, z = noop()
print(x, y, z)
print(not not nil, not not false, not not 1, not not "foo", not not { })
|
Preserve the algorithm and functionality while converting the code from C++ to Lua. | #include <iostream>
#include <math.h>
struct PolarPoint;
struct CartesianPoint
{
double x;
double y;
operator PolarPoint();
};
struct PolarPoint
{
double rho;
double theta;
operator CartesianPoint();
};
CartesianPoint::operator PolarPoint()
{
return PolarPoint
... |
type(123 .. "123")
type(123 + "123")
type(123 + "foo")
function noop () end
local a = noop()
print(a)
local x, y, z = noop()
print(x, y, z)
print(not not nil, not not false, not not 1, not not "foo", not not { })
|
Convert the following code from C++ to Lua, ensuring the logic remains intact. | #include <iostream>
bool isPrime(uint64_t n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
uint64_t test = 5;
while (test * test < n) {
if (n % test == 0) return false;
test += 2;
if (n % test == 0) return false;
test += 4;... |
function isPrime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
local i, p = 0
repeat
i = i + 1
p = 2 ^ i - 1
if isPrime(p) then
print("2 ^ " .. i .. "... |
Translate this program into Lua but keep the logic exactly as in C++. | #include <iostream>
bool isPrime(uint64_t n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
uint64_t test = 5;
while (test * test < n) {
if (n % test == 0) return false;
test += 2;
if (n % test == 0) return false;
test += 4;... |
function isPrime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
local i, p = 0
repeat
i = i + 1
p = 2 ^ i - 1
if isPrime(p) then
print("2 ^ " .. i .. "... |
Keep all operations the same but rewrite the snippet in Lua. | #include <array>
#include <iostream>
#include <vector>
#include <boost/circular_buffer.hpp>
#include "prime_sieve.hpp"
int main() {
using std::cout;
using std::vector;
using boost::circular_buffer;
using group_buffer = circular_buffer<vector<int>>;
const int max = 1000035;
const int max_group_... | local N = 1000035
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end
table.lastn = function(t,n)... |
Write a version of this C++ function in Lua with identical behavior. | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <vector>
template <typename T>
size_t indexOf(const std::vector<T> &v, const T &k) {
auto it = std::find(v.cbegin(), v.cend(), k);
if (it != v.cend()) {
return it - v.cbegin();
}
return -1;
}... | sums, taxis, limit = {}, {}, 1200
for i = 1, limit do
for j = 1, i-1 do
sum = i^3 + j^3
sums[sum] = sums[sum] or {}
table.insert(sums[sum], i.."^3 + "..j.."^3")
end
end
for k,v in pairs(sums) do
if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end
end
table.sort(taxis... |
Rewrite the snippet below in Lua so it works the same as the original C++ code. | #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... |
function primeList (n)
local function isPrime (x)
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
local pTable, j = {2, 3}
for i = 5, n, 2 do
if isPrime(i) then
table.insert(pTable, i)
end
j = i
end
repeat j = j + 2 until isPrime(j)
... |
Translate the given C++ code snippet into Lua without altering its behavior. | #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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.