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 Python to Elixir.
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 ...
defmodule Longest_increasing_subsequence do def lis(l) do (for ss <- combos(l), ss == Enum.sort(ss), do: ss) |> Enum.max_by(fn ss -> length(ss) end) end defp combos(l) do Enum.reduce(1..length(l), [[]], fn k, acc -> acc ++ (combos(k, l)) end) end defp combos(1, l), do: (for x <- l, do: [x]) ...
Write a version of this Python function in Elixir with identical behavior.
from __future__ import print_function def order_disjoint_list_items(data, items): itemindices = [] for item in set(items): itemcount = items.count(item) lastindex = [-1] for i in range(itemcount): lastindex.append(data.index(item, lastindex[-1] + 1)) it...
defmodule Order do def disjoint(m,n) do IO.write " Enum.chunk(n,2) |> Enum.reduce({m,0}, fn [x,y],{m,from} -> md = Enum.drop(m, from) if x > y and x in md and y in md do if Enum.find_index(md,&(&1==x)) > Enum.find_index(md,&(&1==y)) do new_from = max(Enum.find_ind...
Write the same code in Elixir as shown below in Python.
python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(string1, string2, separator): return separator.join([string1, '', string2]) >>> f('Rosetta', 'Code', ':') 'Rosetta::Code' >>>
iex(1)> f = fn str1,str2,sep -> [str1,"",str2] |> Enum.join(sep) end iex(2)> g = fn str1,str2,sep -> str1 <> sep <> sep <> str2 end iex(3)> defmodule JoinStrings do ...(3)> def f(str1,str2,sep), do: [str1,"",str2] |> Enum.join(sep) ...(3)> def g(str1,str2,sep), do: str1 <> sep <> sep <> str2 ...(3)> end
Transform the following Python implementation into Elixir, maintaining the same output and logic.
>>> exec 10
iex(1)> Code.eval_string("x + 4 * Enum.sum([1,2,3,4])", [x: 17]) {57, [x: 17]} iex(2)> Code.eval_string("c = a + b", [a: 1, b: 2]) {3, [a: 1, b: 2, c: 3]} iex(3)> Code.eval_string("a = a + b", [a: 1, b: 2]) {3, [a: 3, b: 2]}
Rewrite this program in Elixir while keeping its functionality equivalent to the Python version.
>>> exec 10
iex(1)> Code.eval_string("x + 4 * Enum.sum([1,2,3,4])", [x: 17]) {57, [x: 17]} iex(2)> Code.eval_string("c = a + b", [a: 1, b: 2]) {3, [a: 1, b: 2, c: 3]} iex(3)> Code.eval_string("a = a + b", [a: 1, b: 2]) {3, [a: 3, b: 2]}
Ensure the translated Elixir code behaves exactly like the original Python snippet.
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c...
defmodule Brace_expansion do def getitem(s), do: getitem(String.codepoints(s), 0, [""]) defp getitem([], _, out), do: {out,[]} defp getitem([c|_]=s, depth, out) when depth>0 and (c == "," or c == "}"), do: {out,s} defp getitem([c|t], depth, out) do x = getgroup(t, depth+1, [], false) if (c == "{") an...
Produce a functionally identical Elixir code for the snippet given in Python.
from collections import namedtuple from math import sqrt Pt = namedtuple('Pt', 'x, y') Circle = Cir = namedtuple('Circle', 'x, y, r') def circles_from_p1p2r(p1, p2, r): 'Following explanation at http://mathforum.org/library/drmath/view/53027.html' if r == 0.0: raise ValueError('radius of zero') (x...
defmodule RC do def circle(p, p, r) when r>0.0 do raise ArgumentError, message: "Infinite number of circles, points coincide." end def circle(p, p, r) when r==0.0 do {px, py} = p [{px, py, r}] end def circle({p1x,p1y}, {p2x,p2y}, r) do {dx, dy} = {p2x-p1x, p2y-p1y} q = :math.sqrt(dx*dx + d...
Port the provided Python code into Elixir while preserving the original functionality.
from collections import namedtuple from math import sqrt Pt = namedtuple('Pt', 'x, y') Circle = Cir = namedtuple('Circle', 'x, y, r') def circles_from_p1p2r(p1, p2, r): 'Following explanation at http://mathforum.org/library/drmath/view/53027.html' if r == 0.0: raise ValueError('radius of zero') (x...
defmodule RC do def circle(p, p, r) when r>0.0 do raise ArgumentError, message: "Infinite number of circles, points coincide." end def circle(p, p, r) when r==0.0 do {px, py} = p [{px, py, r}] end def circle({p1x,p1y}, {p2x,p2y}, r) do {dx, dy} = {p2x-p1x, p2y-p1y} q = :math.sqrt(dx*dx + d...
Generate a Elixir translation of this Python snippet without changing its computational steps.
:- initialization(main). faces([a,k,q,j,10,9,8,7,6,5,4,3,2]). face(F) :- faces(Fs), member(F,Fs). suit(S) :- member(S, ['♥','♦','♣','♠']). best_hand(Cards,H) :- straight_flush(Cards,C) -> H = straight-flush(C) ; many_kind(Cards,F,4) -> H = four-of-a-kind(F) ; full_house(Cards,F1,F2) -> H = full-house(F1...
defmodule Card do @faces ~w(2 3 4 5 6 7 8 9 10 j q k a) @suits ~w(♥ ♦ ♣ ♠) @ordinal @faces |> Enum.with_index |> Map.new defstruct ~w[face suit ordinal]a def new(str) do {face, suit} = String.split_at(str, -1) if face in @faces and suit in @suits do ordinal = ...
Convert this Python block to Elixir, preserving its control flow and logic.
:- initialization(main). faces([a,k,q,j,10,9,8,7,6,5,4,3,2]). face(F) :- faces(Fs), member(F,Fs). suit(S) :- member(S, ['♥','♦','♣','♠']). best_hand(Cards,H) :- straight_flush(Cards,C) -> H = straight-flush(C) ; many_kind(Cards,F,4) -> H = four-of-a-kind(F) ; full_house(Cards,F1,F2) -> H = full-house(F1...
defmodule Card do @faces ~w(2 3 4 5 6 7 8 9 10 j q k a) @suits ~w(♥ ♦ ♣ ♠) @ordinal @faces |> Enum.with_index |> Map.new defstruct ~w[face suit ordinal]a def new(str) do {face, suit} = String.split_at(str, -1) if face in @faces and suit in @suits do ordinal = ...
Write the same algorithm in Elixir as shown in this Python implementation.
from functools import wraps from turtle import * def memoize(obj): cache = obj.cache = {} @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer @memoize def f...
defmodule Fibonacci do def fibonacci_word, do: Stream.unfold({"1","0"}, fn{a,b} -> {a, {b, b<>a}} end) def word_fractal(n) do word = fibonacci_word |> Enum.at(n) walk(to_char_list(word), 1, 0, 0, 0, -1, %{{0,0}=>"S"}) |> print end defp walk([], _, _, _, _, _, map), do: map defp walk([h|t], n...
Translate this program into Elixir but keep the logic exactly as in Python.
from __future__ import print_function import random from time import sleep first = random.choice([True, False]) you = '' if first: me = ''.join(random.sample('HT'*3, 3)) print('I choose first and will win on first seeing {} in the list of tosses'.format(me)) while len(you) != 3 or any(ch not in 'HT' for c...
defmodule Penney do @toss [:Heads, :Tails] def game(score \\ {0,0}) def game({iwin, ywin}=score) do IO.puts "Penney game score I : [i, you] = @toss coin = Enum.random(@toss) IO.puts " {myC, yC} = setup(coin) seq = for _ <- 1..3, do: Enum.random(@toss) IO.write Enum.join(seq, " ") ...
Generate an equivalent Elixir version of this Python code.
def nonoblocks(blocks, cells): if not blocks or blocks[0] == 0: yield [(0, 0)] else: assert sum(blocks) + len(blocks)-1 <= cells, \ 'Those blocks will not fit in those cells' blength, brest = blocks[0], blocks[1:] minspace4rest = sum(1+b for b in brest) ...
defmodule Nonoblock do def solve(cell, blocks) do width = Enum.sum(blocks) + length(blocks) - 1 if cell < width do raise "Those blocks will not fit in those cells" else nblocks(cell, blocks, "") end end defp nblocks(cell, _, position) when cell<=0, do: display(String.slice(posit...
Port the following code from Python to Elixir with equivalent syntax and logic.
def nonoblocks(blocks, cells): if not blocks or blocks[0] == 0: yield [(0, 0)] else: assert sum(blocks) + len(blocks)-1 <= cells, \ 'Those blocks will not fit in those cells' blength, brest = blocks[0], blocks[1:] minspace4rest = sum(1+b for b in brest) ...
defmodule Nonoblock do def solve(cell, blocks) do width = Enum.sum(blocks) + length(blocks) - 1 if cell < width do raise "Those blocks will not fit in those cells" else nblocks(cell, blocks, "") end end defp nblocks(cell, _, position) when cell<=0, do: display(String.slice(posit...
Generate a Elixir translation of this Python snippet without changing its computational steps.
def monkey_coconuts(sailors=5): "Parameterised the number of sailors using an inner loop including the last mornings case" nuts = sailors while True: n0, wakes = nuts, [] for sailor in range(sailors + 1): portion, remainder = divmod(n0, sailors) wakes.append((n0, ...
defmodule RC do def valid?(sailor, nuts), do: valid?(sailor, nuts, sailor) def valid?(sailor, nuts, 0), do: nuts > 0 and rem(nuts,sailor) == 0 def valid?(sailor, nuts, _) when rem(nuts,sailor)!=1, do: false def valid?(sailor, nuts, i) do valid?(sailor, nuts - div(nuts,sailor) - 1, i-1) end end Enum.ea...
Translate the given Python code snippet into Elixir without altering its behavior.
def monkey_coconuts(sailors=5): "Parameterised the number of sailors using an inner loop including the last mornings case" nuts = sailors while True: n0, wakes = nuts, [] for sailor in range(sailors + 1): portion, remainder = divmod(n0, sailors) wakes.append((n0, ...
defmodule RC do def valid?(sailor, nuts), do: valid?(sailor, nuts, sailor) def valid?(sailor, nuts, 0), do: nuts > 0 and rem(nuts,sailor) == 0 def valid?(sailor, nuts, _) when rem(nuts,sailor)!=1, do: false def valid?(sailor, nuts, i) do valid?(sailor, nuts - div(nuts,sailor) - 1, i-1) end end Enum.ea...
Write the same code in Elixir as shown below in Python.
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print s...
IO.puts 'Arguments:' IO.inspect OptionParser.parse(System.argv())
Change the following Python code into Elixir without altering its purpose.
from optparse import OptionParser [...] parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print s...
IO.puts 'Arguments:' IO.inspect OptionParser.parse(System.argv())
Convert the following code from Python to Elixir, ensuring the logic remains intact.
board = [] given = [] start = None def setup(s): global board, given, start lines = s.splitlines() ncols = len(lines[0].split()) nrows = len(lines) board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)] for r, row in enumerate(lines): for c, cell in enumerate(row.split()): ...
defmodule HLPsolver do defmodule Cell do defstruct value: -1, used: false, adj: [] end def solve(str, adjacent, print_out\\true) do board = setup(str) if print_out, do: print(board, "Problem:") {start, _} = Enum.find(board, fn {_,cell} -> cell.value==1 end) board = set_adj(board, adjacent...
Produce a functionally identical Elixir code for the snippet given in Python.
board = [] given = [] start = None def setup(s): global board, given, start lines = s.splitlines() ncols = len(lines[0].split()) nrows = len(lines) board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)] for r, row in enumerate(lines): for c, cell in enumerate(row.split()): ...
defmodule HLPsolver do defmodule Cell do defstruct value: -1, used: false, adj: [] end def solve(str, adjacent, print_out\\true) do board = setup(str) if print_out, do: print(board, "Problem:") {start, _} = Enum.find(board, fn {_,cell} -> cell.value==1 end) board = set_adj(board, adjacent...
Port the provided Python code into Elixir while preserving the original functionality.
def merge_list(a, b): out = [] while len(a) and len(b): if a[0] < b[0]: out.append(a.pop(0)) else: out.append(b.pop(0)) out += a out += b return out def strand(a): i, s = 0, [a.pop(0)] while i < len(a): if a[i] > s[-1]: s.append(a.pop(i)) else: i += 1 return s def strand_sort(a): out = st...
defmodule Sort do def strand_sort(args), do: strand_sort(args, []) defp strand_sort([], result), do: result defp strand_sort(a, result) do {_, sublist, b} = Enum.reduce(a, {hd(a),[],[]}, fn val,{v,l1,l2} -> if v <= val, do: {val, [val | l1], l2}, e...
Can you help me rewrite this code in Elixir instead of Python, keeping it the same logically?
def mc_rank(iterable, start=1): lastresult, fifo = None, [] for n, item in enumerate(iterable, start-1): if item[0] == lastresult: fifo += [item] else: while fifo: yield n, fifo.pop(0) lastresult, fifo = item[0], fifo + [item] while fi...
defmodule Ranking do def methods(data) do IO.puts "stand.\tmod.\tdense\tord.\tfract." Enum.group_by(data, fn {score,_name} -> score end) |> Enum.map(fn {score,pairs} -> names = Enum.map(pairs, fn {_,name} -> name end) |> Enum.reverse {score, names} end) |> Enum.sort_by(fn {sco...
Please provide an equivalent version of this Python code in Elixir.
import urllib.request import re PLAUSIBILITY_RATIO = 2 def plausibility_check(comment, x, y): print('\n Checking plausibility of: %s' % comment) if x > PLAUSIBILITY_RATIO * y: print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times' % (x, y, x / y)) else: ...
defmodule RC do def task(path) do plausibility_ratio = 2 rules = [ {"I before E when not preceded by C:", "ie", "ei"}, {"E before I when preceded by C:", "cei", "cie"} ] regex = ~r/ie|ei|cie|cei/ counter = File.read!(path) |> countup(regex) Enum.all?(rules, fn {str, x, y} -> nx...
Translate the given Python code snippet into Elixir without altering its behavior.
import urllib.request import re PLAUSIBILITY_RATIO = 2 def plausibility_check(comment, x, y): print('\n Checking plausibility of: %s' % comment) if x > PLAUSIBILITY_RATIO * y: print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times' % (x, y, x / y)) else: ...
defmodule RC do def task(path) do plausibility_ratio = 2 rules = [ {"I before E when not preceded by C:", "ie", "ei"}, {"E before I when preceded by C:", "cei", "cie"} ] regex = ~r/ie|ei|cie|cei/ counter = File.read!(path) |> countup(regex) Enum.all?(rules, fn {str, x, y} -> nx...
Transform the following Python implementation into Elixir, maintaining the same output and logic.
beforeTxt = smallrc01 = rc01 = def intarray(binstring): return [[1 if ch == '1' else 0 for ch in line] for line in binstring.strip().split()] def chararray(intmatrix): return '\n'.join(''.join(str(p) for p in row) for row in intmatrix) def toTxt(intmatrix): Return 8-neighb...
defmodule ZhangSuen do @neighbours [{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}] def thinning(str, black \\ ? s0 = for {line, i} <- (String.split(str, "\n") |> Enum.with_index), {c, j} <- (to_char_list(line) |> Enum.with_index), into: Map.new, do: {{i,j}...
Produce a functionally identical Elixir code for the snippet given in Python.
>>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = {''.join(p).upper() for p in permutations(pieces) if p.index('B') % 2 != p.index('b') % 2 and ( p.index('r') < p.index('K') < p.index('R') or p.index('R') < p.index('K') <...
defmodule Chess960 do @pieces ~w(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖) @regexes [~r/♗(..)*♗/, ~r/♖.*♔.*♖/] def shuffle do row = Enum.shuffle(@pieces) |> Enum.join if Enum.all?(@regexes, &Regex.match?(&1, row)), do: row, else: shuffle end end Enum.each(1..5, fn _ -> IO.puts Chess960.shuffle end)
Convert the following code from Python to Elixir, ensuring the logic remains intact.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': n = 600851475143 j = 3 while not isPrime(n): if n % j == 0: n /= j j += 2 print(n);
defmodule Factor do def wheel235(), do: Stream.concat( [2, 3, 5], Stream.scan(Stream.cycle([6, 4, 2, 4, 2, 4, 6, 2]), 1, &+/2) ) def gpf(n), do: gpf n, wheel235() defp gpf(n, divs) do [d] = Enum.take divs, 1 cond do d*d > n -> n rem(n, d) === 0 -> gp...
Convert this Python snippet to Elixir and keep its semantics consistent.
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighb...
adjacent = [{-3, 0}, {0, -3}, {0, 3}, {3, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}] board = """ . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . """ HLPsolver.solve(board, adjacent)
Rewrite this program in Elixir while keeping its functionality equivalent to the Python version.
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighb...
adjacent = [{-3, 0}, {0, -3}, {0, 3}, {3, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}] board = """ . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . """ HLPsolver.solve(board, adjacent)
Port the provided Python code into Elixir while preserving the original functionality.
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: ...
adjacent = [{-1, 0}, {0, -1}, {0, 1}, {1, 0}] board1 = """ 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 """ HLPsolver...
Translate the given Python code snippet into Elixir without altering its behavior.
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: ...
adjacent = [{-1, 0}, {0, -1}, {0, 1}, {1, 0}] board1 = """ 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 """ HLPsolver...
Produce a language-to-language conversion: from Python to Elixir, same semantics.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
defmodule RC do def backup_file(filename) do backup = filename <> ".backup" case File.rename(filename, backup) do :ok -> :ok {:error, reason} -> raise "rename error: end File.cp!(backup, filename) end end hd(System.argv) |> RC.backup_file
Please provide an equivalent version of this Python code in Elixir.
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
defmodule RC do def backup_file(filename) do backup = filename <> ".backup" case File.rename(filename, backup) do :ok -> :ok {:error, reason} -> raise "rename error: end File.cp!(backup, filename) end end hd(System.argv) |> RC.backup_file
Produce a functionally identical Elixir code for the snippet given in Python.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new =...
defmodule Proper do def divisors(1), do: [] def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort defp divisors(k,_n,q) when k>q, do: [] defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q) defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)] defp divisors(k,n,q) ...
Translate the given Python code snippet into Elixir without altering its behavior.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new =...
defmodule Proper do def divisors(1), do: [] def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort defp divisors(k,_n,q) when k>q, do: [] defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q) defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)] defp divisors(k,n,q) ...
Rewrite the snippet below in Elixir so it works the same as the original Python code.
from collections import defaultdict from itertools import product from pprint import pprint as pp cube2n = {x**3:x for x in range(1, 1201)} sum2cubes = defaultdict(set) for c1, c2 in product(cube2n, cube2n): if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2])) taxied = sorted((k, v) for k,v in sum2cubes.it...
defmodule Taxicab do def numbers(n \\ 1200) do (for i <- 1..n, j <- i..n, do: {i,j}) |> Enum.group_by(fn {i,j} -> i*i*i + j*j*j end) |> Enum.filter(fn {_,v} -> length(v)>1 end) |> Enum.sort end end nums = Taxicab.numbers |> Enum.with_index Enum.each(nums, fn {x,i} -> if i in 0..24 or i in 1999..2...
Port the provided Python code into Elixir while preserving the original functionality.
from itertools import islice def lfact(): yield 0 fact, summ, n = 1, 0, 1 while 1: fact, summ, n = fact*n, summ + fact, n + 1 yield summ print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())]) print('20 through 110 (inclusive) by tens:') for lf in islice(lfact(), 20, 111, 10)...
defmodule LeftFactorial do def calc(0), do: 0 def calc(n) do {result, _factorial} = Enum.reduce(1..n, {0, 1}, fn i,{res, fact} -> {res + fact, fact * i} end) result end end Enum.each(0..10, fn i -> IO.puts "! end) Enum.each(Enum.take_every(20..110, 10), fn i -> IO.puts "! end) Enum.each(Enu...
Change the programming language of this snippet from Python to Elixir without modifying what it does.
from itertools import islice def lfact(): yield 0 fact, summ, n = 1, 0, 1 while 1: fact, summ, n = fact*n, summ + fact, n + 1 yield summ print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())]) print('20 through 110 (inclusive) by tens:') for lf in islice(lfact(), 20, 111, 10)...
defmodule LeftFactorial do def calc(0), do: 0 def calc(n) do {result, _factorial} = Enum.reduce(1..n, {0, 1}, fn i,{res, fact} -> {res + fact, fact * i} end) result end end Enum.each(0..10, fn i -> IO.puts "! end) Enum.each(Enum.take_every(20..110, 10), fn i -> IO.puts "! end) Enum.each(Enu...
Translate this program into Elixir but keep the logic exactly as in Python.
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 ...
defmodule Magic_square do def doubly_even(n) when rem(n,4)!=0, do: raise ArgumentError, "must be even, but not divisible by 4." def doubly_even(n) do n2 = n * n Enum.zip(1..n2, make_pattern(n)) |> Enum.map(fn {i,p} -> if p, do: i, else: n2 - i + 1 end) |> Enum.chunk(n) |> to_string(n) |> IO....
Write the same code in Elixir as shown below in Python.
class DigitSumer : def __init__(self): sumdigit = lambda n : sum( map( int,str( n ))) self.t = [sumdigit( i ) for i in xrange( 10000 )] def __call__ ( self,n ): r = 0 while n >= 10000 : n,q = divmod( n,10000 ) r += self.t[q] return r + self.t[n] ...
defmodule SelfNums do def digAndSum(number) when is_number(number) do Integer.digits(number) |> Enum.reduce( 0, fn(num, acc) -> num + acc end ) |> (fn(x) -> x + number end).() end def selfFilter(list, firstNth) do numRange = Enum.to_list 1..firstNth numRange -- list end end defmodule Se...
Translate the given Python code snippet into Elixir without altering its behavior.
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_...
defmodule Puzzle do def sum_and_product do s1 = for x <- 2..49, y <- x+1..99, x+y<100, do: {x,y} s2 = Enum.filter(s1, fn p -> Enum.all?(sumEq(s1,p), fn q -> length(mulEq(s1,q)) != 1 end) end) s3 = Enum.filter(s2, fn p -> only1?(mulEq(s1,p), s2) end) Enum.filter(s3, fn p -> only1?(sumEq(s1,p)...
Generate an equivalent Elixir version of this Python code.
"Generate a short Superpermutation of n characters A... as a string using various algorithms." from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase...
defmodule Superpermutation do def minimisation(1), do: [1] def minimisation(n) do Enum.chunk(minimisation(n-1), n-1, 1) |> Enum.reduce({[],nil}, fn sub,{acc,last} -> if Enum.uniq(sub) == sub do i = if acc==[], do: 0, else: Enum.find_index(sub, &(&1==last)) + 1 {acc ++ (Enum.drop(sub,i)...
Ensure the translated Elixir code behaves exactly like the original Python snippet.
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5...
defmodule Test do def integer?(n) when n == trunc(n), do: true def integer?(_), do: false end Enum.each([2, 2.0, 2.5, 2.000000000000001, 1.23e300, 1.0e-300, "123", '123', :"123"], fn n -> IO.puts " end)
Convert this Python snippet to Elixir and keep its semantics consistent.
range17 = range(17) a = [['0'] * 17 for i in range17] idx = [0] * 4 def find_group(mark, min_n, max_n, depth=1): if (depth == 4): prefix = "" if (mark == '1') else "un" print("Fail, found totally {}connected group:".format(prefix)) for i in range(4): print(idx[i]) retur...
defmodule Ramsey do def main(n\\17) do vertices = Enum.to_list(0 .. n-1) g = create_graph(n,vertices) edges = for v1 <- :digraph.vertices(g), v2 <- :digraph.out_neighbours(g, v1), do: {v1,v2} print_graph(vertices,edges) case ramsey_check(vertices,edges) do true -> "Satisfies Ramsey...
Produce a language-to-language conversion: from Python to Elixir, same semantics.
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "...
defmodule Hash do def join(table1, index1, table2, index2) do h = Enum.group_by(table1, fn s -> elem(s, index1) end) Enum.flat_map(table2, fn r -> Enum.map(h[elem(r, index2)], fn s -> {s, r} end) end) end end table1 = [{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18,...
Write a version of this Python function in Elixir with identical behavior.
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ ...
defmodule RC do def perm_rep(list), do: perm_rep(list, length(list)) def perm_rep([], _), do: [[]] def perm_rep(_, 0), do: [[]] def perm_rep(list, i) do for x <- list, y <- perm_rep(list, i-1), do: [x|y] end end list = [1, 2, 3] Enum.each(1..3, fn n -> IO.inspect RC.perm_rep(list,n) end)
Convert this Python block to Elixir, preserving its control flow and logic.
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ ...
defmodule RC do def perm_rep(list), do: perm_rep(list, length(list)) def perm_rep([], _), do: [[]] def perm_rep(_, 0), do: [[]] def perm_rep(list, i) do for x <- list, y <- perm_rep(list, i-1), do: [x|y] end end list = [1, 2, 3] Enum.each(1..3, fn n -> IO.inspect RC.perm_rep(list,n) end)
Please provide an equivalent version of this Python code in Elixir.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from ...
defmodule Game24 do @expressions [ ["((", "", ")", "", ")", ""], ["(", "(", "", "", "))", ""], ["(", "", ")", "(", "", ")"], ["", "((", "", "", ")", ")"], ["", "(", "", "(", "", "))"] ] def solve(digits) do dig_perm = permute(digits) |> Enum...
Convert the following code from Python to Elixir, ensuring the logic remains intact.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from ...
defmodule Game24 do @expressions [ ["((", "", ")", "", ")", ""], ["(", "(", "", "", "))", ""], ["(", "", ")", "(", "", ")"], ["", "((", "", "", ")", ")"], ["", "(", "", "(", "", "))"] ] def solve(digits) do dig_perm = permute(digits) |> Enum...
Translate this program into Elixir but keep the logic exactly as in Python.
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i =' % (N, k), perm(N, k, exact), end=', '...
defmodule Combinations_permutations do def perm(n, k), do: product(n - k + 1 .. n) def comb(n, k), do: div( perm(n, k), product(1 .. k) ) defp product(a..b) when a>b, do: 1 defp product(list), do: Enum.reduce(list, 1, fn n, acc -> n * acc end) def test do IO.puts "\nA sample of permutations from ...
Write the same code in Elixir as shown below in Python.
from pyprimes import nprimes from functools import reduce primelist = list(nprimes(1000001)) def primorial(n): return reduce(int.__mul__, primelist[:n], 1) if __name__ == '__main__': print('First ten primorals:', [primorial(n) for n in range(10)]) for e in range(7): n = 10**e print('...
defmodule SieveofEratosthenes do def init(lim) do find_primes(2,lim,(2..lim)) end def find_primes(count,lim,nums) when (count * count) > lim do nums end def find_primes(count,lim,nums) when (count * count) <= lim do find_primes(count+1,lim,Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count))) ...
Rewrite the snippet below in Elixir so it works the same as the original Python code.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x ...
import Integer defmodule Rectangle do def cut_it(h, w) when is_odd(h) and is_odd(w), do: 0 def cut_it(h, w) when is_odd(h), do: cut_it(w, h) def cut_it(_, 1), do: 1 def cut_it(h, 2), do: h def cut_it(2, w), do: w def cut_it(h, w) do grid = List.duplicate(false, (h + 1) * (w + 1)) t = div(h, 2) * (...
Maintain the same structure and functionality when rewriting this code in Elixir.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x ...
import Integer defmodule Rectangle do def cut_it(h, w) when is_odd(h) and is_odd(w), do: 0 def cut_it(h, w) when is_odd(h), do: cut_it(w, h) def cut_it(_, 1), do: 1 def cut_it(h, 2), do: h def cut_it(2, w), do: w def cut_it(h, w) do grid = List.duplicate(false, (h + 1) * (w + 1)) t = div(h, 2) * (...
Please provide an equivalent version of this Python code in Elixir.
from itertools import product, combinations, izip scoring = [0, 1, 3] histo = [[0] * 10 for _ in xrange(4)] for results in product(range(3), repeat=6): s = [0] * 4 for r, g in izip(results, combinations(range(4), 2)): s[g[0]] += scoring[r] s[g[1]] += scoring[2 - r] for h, v in izip(histo,...
defmodule World_Cup do def group_stage do results = [[3,0],[1,1],[0,3]] teams = [0,1,2,3] allresults = combos(2,teams) |> combinations(results) allpoints = for list <- allresults, do: (for {l1,l2} <- list, do: Enum.zip(l1,l2)) |> List.flatten totalpoints = for list <- allpoints, do: (for t <- team...
Write a version of this Python function in Elixir with identical behavior.
def isPrime(n): if n < 2: return False if n % 2 == 0: return n == 2 if n % 3 == 0: return n == 3 d = 5 while d * d <= n: if n % d == 0: return False d += 2 if n % d == 0: return False d += 4 return True def genera...
defmodule Prime do def conspiracy(m) do IO.puts " Enum.map(prime(m), &rem(&1, 10)) |> Enum.chunk(2,1) |> Enum.reduce(Map.new, fn [a,b],acc -> Map.update(acc, {a,b}, 1, &(&1+1)) end) |> Enum.sort |> Enum.each(fn {{a,b},v} -> sv = to_string(v) |> String.rjust(10) sf = Float.to_...
Translate this program into Elixir but keep the logic exactly as in Python.
from __future__ import division import matplotlib.pyplot as plt import random mean, stddev, size = 50, 4, 100000 data = [random.gauss(mean, stddev) for c in range(size)] mn = sum(data) / size sd = (sum(x*x for x in data) / size - (sum(data) / size) ** 2) ** 0.5 print("Sample mean = %g; Stddev = %g; max = %g;...
defmodule Statistics do def normal_distribution(n, w\\5) do {sum, sum2, hist} = generate(n, w) mean = sum / n stddev = :math.sqrt(sum2 / n - mean*mean) IO.puts "size: IO.puts "mean: IO.puts "stddev: {min, max} = Map.to_list(hist) |> Enum.filter_map(fn {_k,v} ->...
Write the same algorithm in Elixir as shown in this Python implementation.
import math from sys import stdout LOG_10 = 2.302585092994 def build_oms(s): if s % 2 == 0: s += 1 q = [[0 for j in range(s)] for i in range(s)] p = 1 i = s // 2 j = 0 while p <= (s * s): q[i][j] = p ti = i + 1 if ti >= s: ti = 0 tj = j - 1 if ...
defmodule Magic_square do @lux %{ L: [4, 1, 2, 3], U: [1, 4, 2, 3], X: [1, 4, 3, 2] } def singly_even(n) when rem(n-2,4)!=0, do: raise ArgumentError, "must be even, but not divisible by 4." def singly_even(2), do: raise ArgumentError, "2x2 magic square not possible." def singly_even(n) do n2 = div(n, 2)...
Keep all operations the same but rewrite the snippet in Elixir.
def _notcell(c): return '0' if c == '1' else '1' def eca_infinite(cells, rule): lencells = len(cells) rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} c = cells while True: yield c c = _notcell(c[0])*2 + c + _notcell(c...
defmodule Elementary_cellular_automaton do def infinite(cell, rule, times) do each(cell, rule_pattern(rule), times) end defp each(_, _, 0), do: :ok defp each(cells, rules, times) do IO.write String.duplicate(" ", times) IO.puts String.replace(cells, "0", ".") |> String.replace("1", " c = not_...
Write a version of this Python function in Elixir with identical behavior.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char i...
defmodule RC do def dec2bin(dec, precision\\16) do [int, df] = case String.trim(dec) |> String.split(".") do [int] -> [int, nil] [int, df] -> [int, df] end {sign, int} = if String.first(int)=="-", do: String.split_at(int, 1), else: {"", int} bin = sign <> (String.to_integer(int) |> Integer...
Generate a Elixir translation of this Python snippet without changing its computational steps.
hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16)) bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16)) def float_dec2bin(d): neg = False if d < 0: d = -d neg = True hx = float(d).hex() p = hx.index('p') bn = ''.join(hex2bin.get(char, char) for char i...
defmodule RC do def dec2bin(dec, precision\\16) do [int, df] = case String.trim(dec) |> String.split(".") do [int] -> [int, nil] [int, df] -> [int, df] end {sign, int} = if String.first(int)=="-", do: String.split_at(int, 1), else: {"", int} bin = sign <> (String.to_integer(int) |> Integer...
Translate the given Python code snippet into Elixir without altering its behavior.
from itertools import imap, imap, groupby, chain, imap from operator import itemgetter from sys import argv from array import array def concat_map(func, it): return list(chain.from_iterable(imap(func, it))) def minima(poly): return (min(pt[0] for pt in poly), min(pt[1] for pt in poly)) def translate_to_...
defmodule Polyominoes do defp translate2origin(poly) do minx = Enum.map(poly, &elem(&1,0)) |> Enum.min miny = Enum.map(poly, &elem(&1,1)) |> Enum.min Enum.map(poly, fn {x,y} -> {x - minx, y - miny} end) |> Enum.sort end defp rotate90({x, y}), do: {y, -x} defp reflect({x, y}), do: {-x, y} ...
Transform the following Python implementation into Elixir, maintaining the same output and logic.
from itertools import groupby from unicodedata import decomposition, name from pprint import pprint as pp commonleaders = ['the'] replacements = {u'ß': 'ss', u'ſ': 's', u'ʒ': 's', } hexdigits = set('0123456789abcdef') decdigits = set('0123456789') def splitch...
defmodule Natural do def sorting(texts) do Enum.sort_by(texts, fn text -> compare_value(text) end) end defp compare_value(text) do text |> String.downcase |> String.replace(~r/\A(a |an |the )/, "") |> String.split |> Enum.map(fn word -> Regex.scan(~r/\d+|\D+/, word) |>...
Generate a Elixir translation of this Python snippet without changing its computational steps.
def DrawBoard(board): peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for n in xrange(1,16): peg[n] = '.' if n in board: peg[n] = "%X" % n print " %s" % peg[1] print " %s %s" % (peg[2],peg[3]) print " %s %s %s" % (peg[4],peg[5],peg[6]) print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10])...
defmodule IQ_Puzzle do def task(i \\ 0, n \\ 5) do fmt = Enum.map_join(1..n, fn i -> String.duplicate(" ", n-i) <> String.duplicate("~w ", i) <> "~n" end) pegs = Tuple.duplicate(1, div(n*(n+1),2)) |> put_elem(i, 0) rest = tuple_size(pegs) - 1 next = next_list(n) :io.format fm...
Write a version of this Python function in Elixir with identical behavior.
from itertools import islice def posd(): "diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..." count, odd = 1, 3 while True: yield count yield odd count, odd = count + 1, odd + 2 def pos_gen(): "position numbers. 1 3 2 5 7 4 9 ..." val = 1 diff = posd...
use Bitwise, skip_operators: true defmodule Partition do def init(), do: :ets.new :pN, [:set, :named_table, :private] def gpentagonals(), do: Stream.unfold {1, 0}, &next/1 defp next({m, n}) do a = case rem m, 2 do 0 -> div m, 2 1 -> m end {n, {m + 1, n + ...
Convert the following code from Python to Elixir, ensuring the logic remains intact.
import datetime import re import urllib.request import sys def get(url): with urllib.request.urlopen(url) as response: html = response.read().decode('utf-8') if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html): return None return html def main(): template = 'http://...
defmodule Mentions do def get(url) do {:ok, {{_, 200, _}, _, body}} = url |> String.to_charlist() |> :httpc.request() data = List.to_string(body) if Regex.match?(~r|<!Doctype HTML.*<Title>URL Not Found</Title>|s, data) do {:error, "log file not found"} else {:ok, data} ...
Convert this Python block to Elixir, preserving its control flow and logic.
from __future__ import print_function import os import hashlib import datetime def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"): knownFiles = {} for root, dirs, files in os.walk(pth): for fina in files: fullFina = os.path.join(root, fina) isSymLink = os.path.isli...
defmodule Files do def find_duplicate_files(dir) do IO.puts "\nDirectory : File.cd!(dir, fn -> Enum.filter(File.ls!, fn fname -> File.regular?(fname) end) |> Enum.group_by(fn file -> File.stat!(file).size end) |> Enum.filter(fn {_, files} -> length(files)>1 end) |> Enum.each(fn {size,...
Keep all operations the same but rewrite the snippet in Lua.
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x...
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...
Maintain the same structure and functionality when rewriting this code in Lua.
#include <array> #include <cstdint> #include <iostream> class XorShiftStar { private: const uint64_t MAGIC = 0x2545F4914F6CDD1D; uint64_t state; public: void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x...
function create() local g = { magic = 0x2545F4914F6CDD1D, state = 0, seed = function(self, num) self.state = num end, next_int = function(self) local x = self.state x = x ~ (x >> 12) x = x ~ (x << 25) x = x ~ (x >> 2...
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version.
#include <iostream> typedef unsigned long long bigint; using namespace std; class sdn { public: bool check( bigint n ) { int cc = digitsCount( n ); return compare( n, cc ); } void displayAll( bigint s ) { for( bigint y = 1; y < s; y++ ) if( check( y ) ) cout << y << " is a Self-...
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...
Generate a Lua translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <string> #include <vector> const std::vector<std::pair<std::string, std::string>> conditions = { {"Printer prints", "NNNNYYYY"}, {"A red light is flashing", "YYNNYYNN"}, {"Printer is recognized by computer", "NYNYNYNY"} }; const std::vector<std::pair<std::string, std::string>>...
function promptYN(q) local ans = '?' repeat io.write(q..'? ') ans = string.upper(io.read()) until ans == 'Y' or ans == 'N' return ans == 'Y' end function getCharAt(s,i) return string.sub(s,i,i) end conditions = { {"Printer prints", "NNNNYYYY"}, {"A red light is flashing", "...
Generate a Lua translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> int main() { int numberOfLines; std::cin >> numberOfLines; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::vector<std::string> lines(numberOfLines); for(int i = 0; i < numberOfLines; ++i) { std::getline(s...
function show (t) for _, line in pairs(t) do print(line) end end local lineTable, numLines = {}, io.read() for i = 1, numLines do table.insert(lineTable, io.read()) end show(lineTable)
Write a version of this C++ function in Lua with identical behavior.
#include <iostream> #define _USE_MATH_DEFINES #include <math.h> double arcLength(double radius, double angle1, double angle2) { return (360.0 - abs(angle2 - angle1)) * M_PI * radius / 180.0; } int main() { auto al = arcLength(10.0, 10.0, 120.0); std::cout << "arc length: " << al << '\n'; return 0; }
function arcLength(radius, angle1, angle2) return (360.0 - math.abs(angle2 - angle1)) * math.pi * radius / 180.0 end function main() print("arc length: " .. arcLength(10.0, 10.0, 120.0)) end main()
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <fstream> int main() { std::string word; std::ifstream file("unixdict.txt"); if (!file) { std::cerr << "Cannot open unixdict.txt" << std::endl; return -1; } while (file >> word) { if (word.length() > 11 && word.find("the") != std::string::npos)...
for word in io.open("unixdict.txt", "r"):lines() do if #word > 11 and word:find("the") then print(word) end end
Port the following code from C++ to Lua with equivalent syntax and logic.
#include <iostream> int main() { using namespace std; cout << "Hello, World!" << endl; return 0; }
io.write("Hello world, from ",_VERSION,"!\n")
Rewrite the snippet below in Lua so it works the same as the original C++ code.
#include <iostream> int main() { using namespace std; cout << "Hello, World!" << endl; return 0; }
io.write("Hello world, from ",_VERSION,"!\n")
Write a version of this C++ function in Lua with identical behavior.
#include <algorithm> #include <iostream> template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; delete ri...
AVL={balance=0} AVL.__mt={__index = AVL} function AVL:new(list) local o={} setmetatable(o, AVL.__mt) for _,v in ipairs(list or {}) do o=o:insert(v) end return o end function AVL:rebalance() local rotated=false if self.balance>1 then if self.right.balance<0 then self.right, self.right....
Produce a language-to-language conversion: from C++ to Lua, same semantics.
#include <algorithm> #include <iostream> template <class T> class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; delete ri...
AVL={balance=0} AVL.__mt={__index = AVL} function AVL:new(list) local o={} setmetatable(o, AVL.__mt) for _,v in ipairs(list or {}) do o=o:insert(v) end return o end function AVL:rebalance() local rotated=false if self.balance>1 then if self.right.balance<0 then self.right, self.right....
Produce a language-to-language conversion: from C++ to Lua, same semantics.
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either op...
print([[ This is a long paragraph of text it is the simplest while using it with lua, however it will have the same line breaks and spacing as you set in this block. ]]) print([=[by using equals signs, ]] may be embedded.]=]) local msg = [[this is a message that spans multiple lines and will have the next lines ...
Produce a language-to-language conversion: from C++ to Lua, same semantics.
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either op...
print([[ This is a long paragraph of text it is the simplest while using it with lua, however it will have the same line breaks and spacing as you set in this block. ]]) print([=[by using equals signs, ]] may be embedded.]=]) local msg = [[this is a message that spans multiple lines and will have the next lines ...
Write the same code in Lua as shown below in C++.
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostrea...
sandpile.__index = sandpile sandpile.new = function(self, vals) local inst = setmetatable({},sandpile) inst.cell, inst.dim = {}, #vals for r = 1, inst.dim do inst.cell[r] = {} for c = 1, inst.dim do inst.cell[r][c] = vals[r][c] end end return inst end sandpile.add = function(self, other) l...
Change the programming language of this snippet from C++ to Lua without modifying what it does.
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostrea...
sandpile.__index = sandpile sandpile.new = function(self, vals) local inst = setmetatable({},sandpile) inst.cell, inst.dim = {}, #vals for r = 1, inst.dim do inst.cell[r] = {} for c = 1, inst.dim do inst.cell[r][c] = vals[r][c] end end return inst end sandpile.add = function(self, other) l...
Convert the following code from C++ to Lua, ensuring the logic remains intact.
class fifteenSolver{ const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2}; int n{},_n{}, N0[100]{},N3[100]{},N4[100]{}; unsigned long N2[100]{}; const bool fY(){ if (N4[n]<_n) return fN(); if (N2[n]==0x123456789abcdef0) {std::cout<<"Solution found in "<<n<<" moves ...
#!/usr/bin/lua local SOLUTION_LIMIT, MAX_F_VALUE = 100,100 local NR, NC, RCSIZE = 4,4,4*4 local Up, Down, Right, Left = 'u','d','r','l' local G_cols = {} local G_rows = {} local C_cols = {} local C_rows = {} local Goal = {} local Tiles = {} local Solution = {} local desc = {} desc[0] = 0 local function...
Rewrite this program in Lua while keeping its functionality equivalent to the C++ version.
int i; void* address_of_i = &i;
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))
Convert this C++ block to Lua, preserving its control flow and logic.
#include <time.h> #include <iostream> #include <string> #include <iomanip> #include <cstdlib> typedef unsigned int uint; using namespace std; enum movDir { UP, DOWN, LEFT, RIGHT }; class tile { public: tile() : val( 0 ), blocked( false ) {} uint val; bool blocked; }; class g2048 { public: g2048() : d...
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 ...
Convert this C++ snippet to Lua and keep its semantics consistent.
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector> typedef std::vector<char> vecChar; class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST"; if( code_len < 4 ) code_l...
math.randomseed( os.time() ) local black, white, none, code = "X", "O", "-" local colors, codeLen, maxGuess, rept, alpha, opt = 6, 4, 10, false, "ABCDEFGHIJKLMNOPQRST", "" local guesses, results function createCode() code = "" local dic, a = "" for i = 1, colors do dic = dic .. alpha:sub( i, i ) ...
Rewrite the snippet below in Lua so it works the same as the original C++ code.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> void reverse(std::istream& in, std::ostream& out) { constexpr size_t record_length = 80; char record[record_length]; while (in.read(record, record_length)) { std::reverse(std::begin(record), std::end(record)); ou...
local sample = [[ Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN]] local txtfile = io....
Convert this C++ snippet to Lua and keep its semantics consistent.
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <string> #include <utility> #include <vector> using word_list = std::vector<std::pair<std::string, std::string>>; void print_words(std::ostream& out, const word_list& words) { int n = 1; for (const auto& pair ...
minOddWordLength = 5 minWordLength = minOddWordLength*2-1 dict = {} for word in io.lines('unixdict.txt') do local n = #word if n >= minOddWordLength then dict[word] = n end end for word, len in pairs(dict) do if len >= minWordLength then local odd = "" for o, _ in word:gmatch("(.)(.?)") do ...
Write a version of this C++ function in Lua with identical behavior.
while (true) std::cout << "SPAM\n";
while true do print("SPAM") end repeat print("SPAM") until false
Port the provided C++ code into Lua while preserving the original functionality.
T* foo = new(arena) T;
pool = {} pool.a = 1 pool.b = "hello" pool.c = true pool.d = { 1,2,3 } pool = nil
Translate the given C++ code snippet into Lua without altering its behavior.
T* foo = new(arena) T;
pool = {} pool.a = 1 pool.b = "hello" pool.c = true pool.d = { 1,2,3 } pool = nil
Generate an equivalent Lua version of this C++ code.
#include <iostream> #include <cstdint> #include <vector> #include "prime_sieve.hpp" using integer = uint32_t; using vector = std::vector<integer>; void print_vector(const vector& vec) { if (!vec.empty()) { auto i = vec.begin(); std::cout << '(' << *i; for (++i; i != vec.end(); ++i) ...
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 a version of this C++ function in Lua with identical behavior.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
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...
Maintain the same structure and functionality when rewriting this code in Lua.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
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...
Write a version of this C++ function in Lua with identical behavior.
#include <iostream> #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) { os << ", " << *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 this program into Lua but keep the logic exactly as in C++.
#include <iostream> #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) { os << ", " << *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 a version of this C++ function in Lua with identical behavior.
#include <ctime> #include <string> #include <iostream> #include <algorithm> class cycle{ public: template <class T> void cy( T* a, int len ) { int i, j; show( "original: ", a, len ); std::srand( unsigned( time( 0 ) ) ); for( int i = len - 1; i > 0; i-- ) { do { ...
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 the snippet below in Lua so it works the same as the original C++ code.
#include <time.h> #include <iostream> #include <vector> using namespace std; class cSort { public: void doIt( vector<unsigned> s ) { sq = s; display(); c_sort(); cout << "writes: " << wr << endl; display(); } private: void display() { copy( sq.begin(), sq.end(), ostream_iterator<unsigned>( std...
function printa(a) io.write("[") for i,v in ipairs(a) do if i > 1 then io.write(", ") end io.write(v) end io.write("]") end function cycle_sort(a) local writes = 0 local cycle_start = 0 while cycle_start < #a - 1 do local val = a[cycle_start + 1]...
Convert the following code from C++ to Lua, ensuring the logic remains intact.
#include <time.h> #include <iostream> #include <vector> using namespace std; class cSort { public: void doIt( vector<unsigned> s ) { sq = s; display(); c_sort(); cout << "writes: " << wr << endl; display(); } private: void display() { copy( sq.begin(), sq.end(), ostream_iterator<unsigned>( std...
function printa(a) io.write("[") for i,v in ipairs(a) do if i > 1 then io.write(", ") end io.write(v) end io.write("]") end function cycle_sort(a) local writes = 0 local cycle_start = 0 while cycle_start < #a - 1 do local val = a[cycle_start + 1]...
Ensure the translated Lua code behaves exactly like the original C++ snippet.
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
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...
Port the following code from C++ to Lua with equivalent syntax and logic.
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
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...