conf = {}

fp = io.open( "conf.txt", "r" )

for line in fp:lines() do
    line = line:match( "%s*(.+)" )
    if line and line:sub( 1, 1 ) ~= "#" and line:sub( 1, 1 ) ~= ";" then
 	option = line:match( "%S+" ):lower()
	value  = line:match( "%S*%s*(.*)" )

	if not value then
 	    conf[option] = true
	else
	    if not value:find( "," ) then
		conf[option] = value
	    else
		value = value .. ","
		conf[option] = {}
		for entry in value:gmatch( "%s*(.-)," ) do
		    conf[option][#conf[option]+1] = entry
		end
	    end
	end

    end
end

fp:close()

print( "fullname = ", conf["fullname"] )
print( "favouritefruit = ", conf["favouritefruit"] )
if conf["needspeeling"] then print( "needspeeling = true" ) else print( "needspeeling = false" ) end
if conf["seedsremoved"] then print( "seedsremoved = true" ) else print( "seedsremoved = false" ) end
if conf["otherfamily"] then
    print "otherfamily:"
    for _, entry in pairs( conf["otherfamily"] ) do
	print( "", entry )
    end
end

read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.


implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using the given latitude and longitude coordinates. The code uses either the authalic radius (6371.0 km) or the average great-circle radius (6372.8 km) for calculations, with the latter being recommended. The results may vary based on the radius used. The code also takes into account the recommendations by the International Union of Geodesy and Geophysics to use the mean earth radius (6371 km) for real applications.


Library: LuaSocket
local http = require("socket.http")
local url = require("socket.url")
local page = http.request('http://www.google.com/m/search?q=' .. url.escape("lua"))
print(page)

Print the content of a specified URL to the console using HTTP request.


function luhn(n)
  n=string.reverse(n)
  print(n)
  local s1=0
  --sum odd digits
  for i=1,n:len(),2 do
    s1=s1+n:sub(i,i)
  end
  --evens
  local s2=0
  for i=2,n:len(),2 do
    local doubled=n:sub(i,i)*2
    doubled=string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end)
    s2=s2+doubled
  end
  print(s1)
  print(s2)
  local total=s1+s2
  if total%10==0 then
    return true
  end
  return false
end

-- Note that this function takes strings, not numbers.
-- 16-digit numbers tend to be problematic
-- when looking at individual digits.
print(luhn'49927398716')
print(luhn'49927398717')
print(luhn'1234567812345678')
print(luhn'1234567812345670')

The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


function josephus(n, k, m)
    local positions={}
    for i=1,n do
        table.insert(positions, i-1)
    end
    local i,j=1,1
    local s='Execution order: '
    while #positions>m do
        if j==k then
            s=s .. positions[i] .. ', '
            table.remove(positions, i)
            i=i-1
        end
        i=i+1
        j=j+1
        if i>#positions then i=1 end
        if j>k then j=1 end
    end
    print(s:sub(1,#s-2) .. '.')
    local s='Survivors: '
    for _,v in pairs(positions) do s=s .. v .. ', ' end
    print(s:sub(1,#s-2) .. '.')
end
josephus(41,3, 1)

The code calculates the final survivor in the Josephus problem, given any number of prisoners (n) and a step count (k). It also provides a way to determine the position of any prisoner in the killing sequence. The code can handle scenarios where multiple survivors (m) are allowed. It follows the execution procedure described in the problem, with complexity O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die. The prisoners can be numbered from either 0 to n-1 or 1 to n.


function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end

string.rep(s,n)

The code repeats a given string a specified number of times. It also includes a more efficient method for repeating a single character. Additionally, it demonstrates the use of native string library functions for these tasks.


test = "My name is Lua."
pattern = ".*name is (%a*).*"

if test:match(pattern) then
    print("Name found.")
end

sub, num_matches = test:gsub(pattern, "Hello, %1!")
print(sub)

use Lua's string manipulation methods to match and substitute parts of a string using patterns similar to regular expressions, with the percent sign (%) used to start a character class or a reference for a match in a substitution.


local x = io.read()
local y = io.read()

print ("Sum: "       , (x + y))
print ("Difference: ", (x - y))
print ("Product: "   , (x * y))
print ("Quotient: "  , (x / y)) -- Does not truncate
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Exponent: "  , (x ^ y))

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


function countSubstring(s1, s2)
    return select(2, s1:gsub(s2, ""))
end

print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))

3
2

function countSubstring(s1, s2)
    local count = 0
    for eachMatch in s1:gmatch(s2) do
        count = count + 1
    end
    return count
end

print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))

3
2

"Implement a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function does not count overlapping substrings and matches from left-to-right or right-to-left for the highest number of non-overlapping matches."


function move(n, src, dst, via)
    if n > 0 then
        move(n - 1, src, via, dst)
        print(src, 'to', dst)
        move(n - 1, via, dst, src)
    end
end

move(4, 1, 2, 3)

function move(n, src, via, dst)
    if n > 0 then
        move(n - 1, src, dst, via)
        print('Disk ',n,' from ' ,src, 'to', dst)
        move(n - 1, via, src, dst)

    end
end

move(4, 1, 2, 3)

#!/usr/bin/env luajit
local function printf(fmt, ...) io.write(string.format(fmt, ...)) end
local runs=0
local function move(tower, from, to)
	if #tower[from]==0
		or (#tower[to]>0
		and tower[from][#tower[from]]>tower[to][#tower[to]]) then
			to,from=from,to
	end
	if #tower[from]>0 then
		tower[to][#tower[to]+1]=tower[from][#tower[from]]
		tower[from][#tower[from]]=nil

		io.write(tower[to][#tower[to]],":",from, "→", to, " ")
	end
end

local function hanoi(n)
	local src,dst,via={},{},{}
	local tower={src,dst,via}
	for i=1,n do src[i]=n-i+1 end
	local one,nxt,lst
	if n%2==1 then -- odd
		one,nxt,lst=1,2,3
	else
		one,nxt,lst=1,3,2
	end
	--repeat
	::loop::
		move(tower, one, nxt)
		if #dst==n then return end
		move(tower, one, lst)
		one,nxt,lst=nxt,lst,one
	goto loop
	--until false
end

local num=arg[1] and tonumber(arg[1]) or 4

hanoi(num)

Implement a recursive solution to solve the Towers of Hanoi problem.


function Binomial( n, k )
    if k > n then return nil end
    if k > n/2 then k = n - k end       --   (n k) = (n n-k)

    numer, denom = 1, 1
    for i = 1, k do
        numer = numer * ( n - i + 1 )
        denom = denom * i
    end
    return numer / denom
end

local Binomial = setmetatable({},{
 __call = function(self,n,k)
   local hash = (n<<32) | (k & 0xffffffff)
   local ans = self[hash]
   if not ans then
    if n<0 or k>n then
      return 0 -- not save
    elseif n<=1 or k==0 or k==n then
      ans = 1
    else
      if 2*k > n then
        ans = self(n, n - k)
      else
        local lhs = self(n-1,k)
        local rhs = self(n-1,k-1)
        local sum = lhs + rhs
        if sum<0 or not math.tointeger(sum)then
          -- switch to double
          ans = lhs/1.0 + rhs/1.0 -- approximate
        else
          ans = sum
        end
      end
    end
    rawset(self,hash,ans)
   end
   return ans
 end
})
print( Binomial(100,50)) -- 1.0089134454556e+029

"Calculates any binomial coefficient using a given formula. It specifically outputs the binomial coefficient of 5 and 3, which is 10. The code also handles tasks related to combinations and permutations, both with and without replacement. It utilizes additive recursion with memoization by hashing 2 input integers and supports bit-wise operations assuming a 64-bit integer implementation."


function shellsort( a )
    local inc = math.ceil( #a / 2 )
    while inc > 0 do
        for i = inc, #a do
            local tmp = a[i]
            local j = i
            while j > inc and a[j-inc] > tmp do
                a[j] = a[j-inc]
                j = j - inc
            end
            a[j] = tmp
        end
        inc = math.floor( 0.5 + inc / 2.2 )
    end

    return a
end

a = { -12, 3, 0, 4, 7, 4, 8, -5, 9 }
a = shellsort( a )

for _, i in pairs(a) do
    print(i)
end

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


function ConvertToGrayscaleImage( bitmap )
    local size_x, size_y = #bitmap, #bitmap[1]
    local gray_im = {}

    for i = 1, size_x do
        gray_im[i] = {}
        for j = 1, size_y do
            gray_im[i][j] = math.floor( 0.2126*bitmap[i][j][1] + 0.7152*bitmap[i][j][2] + 0.0722*bitmap[i][j][3] )
        end
    end

    return gray_im
end

function ConvertToColorImage( gray_im )
    local size_x, size_y = #gray_im, #gray_im[1]
    local bitmap = Allocate_Bitmap( size_x, size_y )         -- this function is defined at http://rosettacode.org/wiki/Basic_bitmap_storage#Lua

    for i = 1, size_x do
        for j = 1, size_y do
            bitmap[i][j] = { gray_im[i][j], gray_im[i][j], gray_im[i][j] }
        end
    end

    return bitmap
end

extend the data storage type to support grayscale images, define operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance, and ensure no rounding errors or distorted results occur when storing calculated luminance as an unsigned integer.


Works with: LÖVE
function love.load()
	text = "Hello World! "
	length = string.len(text)

	update_time = 0.3
	timer = 0
	right_direction = true

	local width, height = love.graphics.getDimensions( )

	local size = 100
	local font = love.graphics.setNewFont( size )
	local twidth = font:getWidth( text )
	local theight = font:getHeight( )
	x = width/2 - twidth/2
	y = height/2-theight/2

end

function love.update(dt)
	timer = timer + dt
	if timer > update_time then
		timer = timer - update_time
		if right_direction then
			text = string.sub(text, 2, length) .. string.sub(text, 1, 1)
		else
			text = string.sub(text, length, length) .. string.sub(text, 1, length-1)
		end
	end
end

function love.draw()
	love.graphics.print (text, x, y)
end

function love.keypressed(key, scancode, isrepeat)
	if false then
	elseif key == "escape" then
		love.event.quit()
	end
end

function love.mousepressed( x, y, button, istouch, presses )
	right_direction = not right_direction
end

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


i=0
repeat
  i=i+1
  print(i)
until i%6 == 0

Initializes a value at 0, then enters a loop where it increments the value by 1 and prints it each iteration. The loop continues until the value modulo 6 equals 0. The loop is guaranteed to run at least once. Note: Lua does not support do-while loops.


Works with: Lua version 5.0+

str = "Hello world"
length = #str

str = "Hello world"
length = string.len(str)

str = "Hello world"
length = #str

str = "Hello world"
length = string.len(str)

utf8.len("møøse")
utf8.len("𝔘𝔫𝔦𝔠𝔬𝔡𝔢")
utf8.len("J̲o̲s̲é̲")

determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. The codes also handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. Additionally, the codes can provide the string length in graphemes if the language supports it. For Lua language, the codes consider a character as the size of one byte, so there is no difference between byte length and character length.


print (string.sub("knights",2))    -- remove the first character
print (string.sub("knights",1,-2))    -- remove the last character
print (string.sub("knights",2,-2))    -- remove the first and last characters

The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.


nw = require("nw")
win = nw:app():window(320, 240)
win:show()
win:maximize()
cw, ch = win:client_size()
print(cw .. " x " .. ch)

"Determines the maximum height and width of a window that can fit on the screen's physical display area without scrolling, considering window decorations, menubars, multiple monitors, and tiling window managers."


--9x9 sudoku solver in lua
--based on a branch and bound solution
--fields are not tried in plain order
--but in a way to detect dead ends earlier
concat=table.concat
insert=table.insert
constraints = { }   --contains a table with 3 constraints for every field
-- a contraint "cons" is a table containing all fields which must not have the same value
-- a field "f" is an integer from 1 to 81
columns = { }       --contains all column-constraints   variable "c"
rows = { }          --contains all row-constraints      variable "r"
blocks = { }        --contains all block-constraints    variable "b"

--initialize all constraints
for f = 1, 81 do
  constraints[f] = { }
end
all_constraints = { } --union of colums, rows and blocks
for i = 1, 9 do
  columns[i] = {
    unknown = 9, --number of fields not yet solved
    unknowns = { } --fields not yet solved
  }
  insert(all_constraints, columns[i])
  rows[i] = {
    unknown = 9, -- see l.15
    unknowns = { } -- see l.16
  }
  insert(all_constraints, rows[i])
  blocks[i] = {
    unknown = 9, --see l.15
    unknowns = { } --see l.16
  }
  insert(all_constraints, blocks[i])
end
constraints_by_unknown = { } --contraints sorted by their number of unknown fields
for i = 0, 9 do
  constraints_by_unknown[i] = {
    count = 0 --how many contraints are in here
  }
end
for r = 1, 9 do
  for c = 1, 9 do
    local f = (r - 1) * 9 + c
    insert(rows[r], f)
    insert(constraints[f], rows[r])
    insert(columns[c], f)
    insert(constraints[f], columns[c])
  end
end
for i = 1, 3 do
  for j = 1, 3 do
    local r = (i - 1) * 3 + j
    for k = 1, 3 do
      for l = 1, 3 do
        local c = (k - 1) * 3 + l
        local f = (r - 1) * 9 + c
        local b = (i - 1) * 3 + k
        insert(blocks[b], f)
        insert(constraints[f], blocks[b])
      end
    end
  end
end
working = { } --save the read values in here
function read() --read the values from stdin
  local f = 1
  local l = io.read("*a")
  for d in l:gmatch("(%d)") do
    local n = tonumber(d)
    if n > 0 then
      working[f] = n
      for _,cons in pairs(constraints[f]) do
        cons.unknown = cons.unknown - 1
      end
    else
      for _,cons in pairs(constraints[f]) do
        cons.unknowns[f] = f
      end
    end
    f = f + 1
  end
  assert((f == 82), "Wrong number of digits")
end
read()
function printer(t) --helper function for printing a 1-81 table
  local pattern = {1,2,3,false,4,5,6,false,7,8,9} --place seperators for better readability
  for _,r in pairs(pattern) do
    if r then
      local function p(c)
        return c and t[(r - 1) * 9 + c] or "|"
      end
      local line={}
      for k,v in pairs(pattern) do
        line[k]=p(v)
      end
      print(concat(line))
    else
      print("---+---+---")
    end
  end
end
order = { } --when to try a field
for _,cons in pairs(all_constraints) do --put all constraints in the corresponding constraints_by_unknown set
  local level = constraints_by_unknown[cons.unknown]
  level[cons] = cons
  level.count = level.count + 1
end
function first(t) --helper function to get a value from a set
  for k, v in pairs(t) do
    if k == v then
      return k
    end
  end
end
function establish_order() -- determine the sequence in which the fields are to be tried
  local solved = constraints_by_unknown[0].count
  while solved < 27 do --there 27 constraints
  --contraints with no unknown fields are considered "solved"
  --keep in mind the actual solving happens in function branch
    local i = 1
    while constraints_by_unknown[i].count == 0 do
      i = i + 1
      -- find a unsolved contraint with the least number of unsolved fields
    end
    local cons = first(constraints_by_unknown[i])
    local f = first(cons.unknowns)
    -- take one of its unknown fields and append it to "order"
    insert(order, f)
    for _,c in pairs(constraints[f]) do
    --each constraint "c" of "f" is moved up one "level"
    --delete "f" from the constraints unknown fields
    --decrease unknown of "c"
      c.unknowns[f] = nil
      local level = constraints_by_unknown[c.unknown]
      level[c] = nil
      level.count = level.count - 1
      c.unknown = c.unknown - 1
      level = constraints_by_unknown[c.unknown]
      level[c] = c
      level.count = level.count + 1
      constraints_by_unknown[c.unknown][c] = c
    end
    solved = constraints_by_unknown[0].count
  end
end
establish_order()
max = #order --how many fields are to be solved
function bound(f,i)
  for _,c in pairs(constraints[f]) do
    for _,x in pairs(c) do
      if i == working[x] then
        return false --i is already used in fs column/row/block
      end
    end
  end
  return true
end
function branch(n)
  local f = order[n] --recursively iterate over fields in order
  if n > max then
    return working --all fields solved without collision
  else
    for i = 1, 9 do --check all values
      if bound(f, i) then --if there is no collision
        working[f] = i
        local res = branch(n + 1) --try next field
        if res then
          return res --all fields solved without collision
        else
          working[f] = nil --this lead to a dead end
        end
      else
        working[f] = nil --reset field because of a collision
      end
    end
    return false --this is a dead end
  end
end
x = branch(1)
if x then
  return printer(x)
end

003 000 000
400 080 036
008 000 100

040 060 073
000 900 000
000 002 005

004 070 068
600 000 000
700 600 500

implement a Sudoku solver that takes a partially filled 9x9 grid as input and displays the solved Sudoku in a human-readable format. The speed of the code is approximately half as fast as optimized C.


function table.shuffle(t)
  for n = #t, 1, -1 do
    local k = math.random(n)
    t[n], t[k] = t[k], t[n]
  end

  return t
end

math.randomseed( os.time() )
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
table.shuffle(a)
for i,v in ipairs(a) do print(i,v) end

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


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 isLeapYear(year) then monthLength[2] = 29 end
    for month = 1, 12 do
        day = monthLength[month]
        while dayOfWeek(year, month, day) ~= wday do day = day - 1 end
        print(year .. "-" .. month .. "-" .. day)
    end
end

lastWeekdays("Friday", tonumber(arg[1]))

>lua lastFridays.lua 2012
2012-1-27
2012-2-24
2012-3-30
2012-4-27
2012-5-25
2012-6-29
2012-7-27
2012-8-31
2012-9-28
2012-10-26
2012-11-30
2012-12-28

>

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


"Display the string 'Goodbye, World!' without appending a newline at the end."


local function encrypt(text, key)
	return text:gsub("%a", function(t)
			local base = (t:lower() == t and string.byte('a') or string.byte('A'))

			local r = t:byte() - base
			r = r + key
			r = r%26 -- works correctly even if r is negative
			r = r + base
			return string.char(r)
		end)
end

local function decrypt(text, key)
	return encrypt(text, -key)
end

caesar = {
	encrypt = encrypt,
	decrypt = decrypt,
}

-- test
do
	local text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
	local encrypted = caesar.encrypt(text, 7)
	local decrypted = caesar.decrypt(encrypted, 7)
	print("Original text:  ", text)
	print("Encrypted text: ", encrypted)
	print("Decrypted text: ", decrypted)
end

local memo = {}

local function make_table(k)
    local t = {}
    local a, A = ('a'):byte(), ('A'):byte()

    for i = 0,25 do
        local  c = a + i
        local  C = A + i
        local rc = a + (i+k) % 26
        local RC = A + (i+k) % 26
        t[c], t[C] = rc, RC
    end

    return t
end

local function caesar(str, k, decode)
    k = (decode and -k or k) % 26

    local t = memo[k]
    if not t then
        t = make_table(k)
        memo[k] = t
    end

    local res_t = { str:byte(1,-1) }
    for i,c in ipairs(res_t) do
        res_t[i] = t[c] or c
    end
    return string.char(unpack(res_t))
end

implement both encoding and decoding functionalities of a Caesar cipher. The cipher uses a key between 1 and 25 to rotate the letters of the alphabet, replacing each letter with the next 1st to 25th letter in the alphabet. It also includes the ability to wrap from Z to A. The codes also highlight the cipher's lack of security due to its vulnerability to frequency analysis or brute force attacks. The Caesar cipher is shown to be identical to the Vigenère cipher with a key length of 1 and to the Rot-13 cipher with a key of 13.


function gcd( m, n )
    while n ~= 0 do
        local q = m
        m = n
        n = q % n
    end
    return m
end

function lcm( m, n )
    return ( m ~= 0 and n ~= 0 ) and m * n / gcd( m, n ) or 0
end

print( lcm(12,18) )

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


function checkDigit (cusip)
  if #cusip ~= 8 then return false end

  local sum, c, v, p = 0
  for i = 1, 8 do
    c = cusip:sub(i, i)
    if c:match("%d") then
      v = tonumber(c)
    elseif c:match("%a") then
      p = string.byte(c) - 55
      v = p + 9
    elseif c == "*" then
      v = 36
    elseif c == "@" then
      v = 37
    elseif c == "#" then
      v = 38
    end
    if i % 2 == 0 then
      v = v * 2
    end

    sum = sum + math.floor(v / 10) + v % 10
  end

  return tostring((10 - (sum % 10)) % 10)
end

local testCases = {
  "037833100",
  "17275R102",
  "38259P508",
  "594918104",
  "68389X106",
  "68389X105"
}
for _, CUSIP in pairs(testCases) do
  io.write(CUSIP .. ": ")
  if checkDigit(CUSIP:sub(1, 8)) == CUSIP:sub(9, 9) then
    print("VALID")
  else
    print("INVALID")
  end
end

The code validates the last digit (check digit) of a CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. It uses an algorithm that calculates the check digit based on the first eight characters of the CUSIP, considering both numeric and alphabetic characters, as well as special characters "*", "@", and "#". The function returns the calculated check digit for verification.


ffi = require("ffi")
print("size of int (in bytes):  " .. ffi.sizeof(ffi.new("int")))
print("size of pointer (in bytes):  " .. ffi.sizeof(ffi.new("int*")))
print((ffi.abi("le") and "little" or "big") .. " endian")

uses ffi to print the word size and endianness of the host machine in a scripting environment where Lua is used, as pure/native Lua cannot perform this task. The support for this operation is expected to be provided by the host or an external library.


t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
for key, value in pairs(t) do
  print(value, key)
end

0	sunday
fooday	7
2	tuesday
3	wednesday
5	friday
4	thursday
6	saturday
1	monday

l={'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', not_a_number='fooday', [0]='today', [-1]='yesterday' }
for key, value in ipairs(l) do
  print(key, value)
end

1	monday
2	tuesday
3	wednesday
4	thursday
5	friday
6	saturday
7	sunday

utilize a "for each" loop or another type of loop to iterate through a collection in order and print each element. In Lua, two built-in iterators, pairs() and ipairs(), are used for this task. Pairs() iterates over all entries in a table without a specific order, while ipairs() iterates over table entries with positive integer keys in order, ignoring non-numeric and non-positive integer keys.


function string:split (sep)
    local sep, fields = sep or ":", {}
    local pattern = string.format("([^%s]+)", sep)
    self:gsub(pattern, function(c) fields[#fields+1] = c end)
    return fields
end

local str = "Hello,How,Are,You,Today"
print(table.concat(str:split(","), "."))

"Tokenizes a string by separating it into an array using commas as delimiters, then displays the words to the user separated by a period, including a trailing period."


function gcd(a,b)
	if b ~= 0 then
		return gcd(b, a % b)
	else
		return math.abs(a)
	end
end

function demo(a,b)
	print("GCD of " .. a .. " and " .. b .. " is " .. gcd(a, b))
end

demo(100, 5)
demo(5, 100)
demo(7, 23)

GCD of 100 and 5 is 5
GCD of 5 and 100 is 5
GCD of 7 and 23 is 1

function gcd(a,b)
    while b~=0 do
        a,b=b,a%b
    end
    return math.abs(a)
end

implement a faster iterative solution of Euclid to find the greatest common divisor (GCD), also known as greatest common factor (gcf) and greatest common measure, of two integers. The code is related to the task of finding the least common multiple.


Works with: Lua version 5.3
Library: LuaSocket
local socket = require("socket")

local function has_value(tab, value)
    for i, v in ipairs(tab) do
        if v == value then return i end
    end
    return false
end

local function checkOn(client)
   local line, err = client:receive()
	if line then
		client:send(line .. "\n")
	end
	if err and err ~= "timeout" then
		print(tostring(client) .. " " .. err)
		client:close()
		return true  -- end this connection
   end
	return false  -- do not end this connection
end

local server = assert(socket.bind("*",12321))
server:settimeout(0)  -- make non-blocking
local connections = { }  -- a list of the client connections
while true do
	local newClient = server:accept()
	if newClient then
		newClient:settimeout(0)  -- make non-blocking
		table.insert(connections, newClient)
	end
	local readList = socket.select({server, table.unpack(connections)})
	for _, conn in ipairs(readList) do
		if conn ~= server and checkOn(conn) then
			table.remove(connections, has_value(connections, conn))
		end
	end
end

local socket=require("socket")

function checkOn (client)
    local line, err = client:receive()
    if line then
        print(tostring(client) .. " said " .. line)
        client:send(line .. "\n")
    end
    if err and err ~= "timeout" then
        print(tostring(client) .. " " .. err)
        client:close()
        return true  -- end this connection
    end
    return false    -- do not end this connection
end

local delay = 0.004  -- anything less than this uses up my CPU
local connections = {}  -- an array of connections
local newClient
local server = assert(socket.bind("*", 12321))
server:settimeout(delay)
while true do
    repeat
        newClient = server:accept()
        for idx, client in ipairs(connections) do
            if checkOn(client) then table.remove(connections, idx) end
        end
    until newClient
    newClient:settimeout(delay)
    print(tostring(newClient) .. " connected")
    table.insert(connections, newClient)
end

Works with: Luvit
local http = require("http")

http.createServer(function(req, res)
	print(("Connection from %s"):format(req.socket:address().ip))

	local chunks = {}
	local function dumpChunks()
		for i=1,#chunks do
			res:write(table.remove(chunks, 1))
		end
	end

	req:on("data", function(data)
		for line, nl in data:gmatch("([^\n]+)(\n?)") do
			if nl == "\n" then
				dumpChunks()
				res:write(line)
				res:write("\n")
			else
				table.insert(chunks, line)
			end
		end
	end)

	req:on("end", function()
		dumpChunks()
		res:finish()
	end)
end):listen(12321, "127.0.0.1")

print("Server running at http://127.0.0.1:12321/")

"Implement an echo server that runs on TCP port 12321, accepts and handles multiple simultaneous connections from localhost only, echoes back complete lines received from clients, and logs connection information. The server uses a table of client socket objects with tiny delays to prevent CPU overuse, and continues to respond to other clients even if one client sends a partial line or stops reading responses."


if tonumber(a) ~= nil then
   --it's a number
end;

The code defines a boolean function that checks if a given string can be interpreted as a numeric value, including floating point, negative numbers, and numbers in different formats like hexadecimal or scientific notation.


Works with: Lua version 5.1 - 5.3
Library: lua-http
local request = require('http.request')
local headers, stream = request.new_from_uri("https://sourceforge.net/"):go()
local body = stream:get_body_as_string()
local status = headers:get(':status')
io.write(string.format('Status: %d\nBody: %s\n', status, body)

send a GET request to the URL "https://www.w3.org/" without authentication, print the obtained resource to the console, and check the host certificate for validity. The code does not support redirects and uses lua-http library.


subjectPolygon = {
  {50, 150}, {200, 50}, {350, 150}, {350, 300},
  {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}
}

clipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}

function inside(p, cp1, cp2)
  return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
end

function intersection(cp1, cp2, s, e)
  local dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y
  local dpx, dpy = s.x-e.x, s.y-e.y
  local n1 = cp1.x*cp2.y - cp1.y*cp2.x
  local n2 = s.x*e.y - s.y*e.x
  local n3 = 1 / (dcx*dpy - dcy*dpx)
  local x = (n1*dpx - n2*dcx) * n3
  local y = (n1*dpy - n2*dcy) * n3
  return {x=x, y=y}
end

function clip(subjectPolygon, clipPolygon)
  local outputList = subjectPolygon
  local cp1 = clipPolygon[#clipPolygon]
  for _, cp2 in ipairs(clipPolygon) do  -- WP clipEdge is cp1,cp2 here
    local inputList = outputList
    outputList = {}
    local s = inputList[#inputList]
    for _, e in ipairs(inputList) do
      if inside(e, cp1, cp2) then
        if not inside(s, cp1, cp2) then
          outputList[#outputList+1] = intersection(cp1, cp2, s, e)
        end
        outputList[#outputList+1] = e
      elseif inside(s, cp1, cp2) then
        outputList[#outputList+1] = intersection(cp1, cp2, s, e)
      end
      s = e
    end
    cp1 = cp2
  end
  return outputList
end

function main()
  local function mkpoints(t)
    for i, p in ipairs(t) do
      p.x, p.y = p[1], p[2]
    end
  end
  mkpoints(subjectPolygon)
  mkpoints(clipPolygon)

  local outputList = clip(subjectPolygon, clipPolygon)

  for _, p in ipairs(outputList) do
    print(('{%f, %f},'):format(p.x, p.y))
  end
end

main()

Implement the Sutherland-Hodgman clipping algorithm to find the intersection of a given polygon and a rectangle. The code takes a polygon defined by a sequence of points and clips it by a rectangle. It then prints the sequence of points that define the resulting clipped polygon. Additionally, it displays all three polygons on a graphical surface, each in a different color, and fills the resulting polygon.


print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


> -- A STRING THAT CAN BE IMPLICITLY CONVERTED TO A NUMBER
> s = "1234"
> s+1 -- implicitly convert to number, add 1, remain a number
1235
> type(s+1)
number
> (s+1)..'' -- implicitly convert to number, add 1, implicitly convert back to string
1235
> type((s+1)..'')
string
> tostring(s+1) -- implicitly convert to number, add 1, explicitly convert back to string
1235
> type(tostring(s+1))
string
> -- A STRING THAT CANNOT BE IMPLICITLY CONVERTED TO A NUMBER
> s = "hello"
> s+1
stdin:1: attempt to add a 'string' with a 'number'
stack traceback:
        [C]: in metamethod 'add'
        stdin:1: in main chunk
        [C]: in ?
> -- ONE-LINER EXPLICIT VERSION
> tostring(tonumber("1234")+1)
1235

increment a numerical string using Lua's implicit type conversion feature.


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 _, array in pairs(testCases) do
    sattolo(array)
    print("[" .. table.concat(array, ", ") .. "]")
end

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


function median (numlist)
    if type(numlist) ~= 'table' then return numlist end
    table.sort(numlist)
    if #numlist %2 == 0 then return (numlist[#numlist/2] + numlist[#numlist/2+1]) / 2 end
    return numlist[math.ceil(#numlist/2)]
end

print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))
print(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2}))

The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.


for i = 1, 100 do
	if i % 15 == 0 then
		print("FizzBuzz")
	elseif i % 3 == 0 then
		print("Fizz")
	elseif i % 5 == 0 then
		print("Buzz")
	else
		print(i)
	end
end
for i = 1, 100 do
	output = ""
	if i % 3 == 0 then
		output = output.."Fizz"
	end
	if i % 5 == 0 then
		output = output.."Buzz"
	end
	if(output == "") then
		output = i
	end
	print(output)
end
word = {"Fizz", "Buzz", "FizzBuzz"}

for i = 1, 100 do
        print(word[(i % 3 == 0 and 1 or 0) + (i % 5 == 0 and 2 or 0)] or i)
end
local t = {
        [0]  = "FizzBuzz",
        [3]  = "Fizz",
        [5]  = "Buzz",
        [6]  = "Fizz",
        [9]  = "Fizz",
        [10] = "Buzz",
        [12] = "Fizz"
}

for i = 1, 100 do
        print(t[i%15] or i)
end

local mt = {
	__newindex = (function (t, k, v)
		if type(k) ~= "number" then	rawset(t, k, v)
		elseif 0 == (k % 15) then	rawset(t, k, "fizzbuzz")
		elseif 0 == (k % 5) then	rawset(t, k, "fizz")
		elseif 0 == (k % 3) then	rawset(t, k, "buzz")
		else 						rawset(t, k, k) end
		return t[k]
end)
}

local fizzbuzz = {}
setmetatable(fizzbuzz, mt)

for i=1,100 do fizzbuzz[i] = i end
for i=1,100 do print(fizzbuzz[i]) end
#!/usr/bin/env luajit
local to=arg[1] or tonumber(arg[1]) or 100
local CF,CB=3,5
local cf,cb=CF,CB
for i=1,to do
	cf,cb=cf-1,cb-1
	if cf~=0 and cb~=0 then
		io.write(i)
	else
		if cf==0 then
			cf=CF
			io.write("Fizz")
		end
		if cb==0 then
			cb=CB
			io.write("Buzz")
		end
	end
	io.write(", ")
end

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


local maxIterations = 250
local minX, maxX, minY, maxY = -2.5, 2.5, -2.5, 2.5
local miX, mxX, miY, mxY
function remap( x, t1, t2, s1, s2 )
    local f = ( x - t1 ) / ( t2 - t1 )
    local g = f * ( s2 - s1 ) + s1
    return g;
end
function drawMandelbrot()
    local pts, a, as, za, b, bs, zb, cnt, clr = {}
    for j = 0, hei - 1 do
        for i = 0, wid - 1 do
            a = remap( i, 0, wid, minX, maxX )
            b = remap( j, 0, hei, minY, maxY )
            cnt = 0; za = a; zb = b
            while( cnt < maxIterations ) do
                as = a * a - b * b; bs = 2 * a * b
                a = za + as; b = zb + bs
                if math.abs( a ) + math.abs( b ) > 16 then break end
                cnt = cnt + 1
            end
            if cnt == maxIterations then clr = 0
            else clr = remap( cnt, 0, maxIterations, 0, 255 )
            end
            pts[1] = { i, j, clr, clr, 0, 255 }
            love.graphics.points( pts )
        end
    end
end
function startFractal()
    love.graphics.setCanvas( canvas ); love.graphics.clear()
    love.graphics.setColor( 255, 255, 255 )
    drawMandelbrot(); love.graphics.setCanvas()
end
function love.load()
    wid, hei = love.graphics.getWidth(), love.graphics.getHeight()
    canvas = love.graphics.newCanvas( wid, hei )
    startFractal()
end
function love.mousepressed( x, y, button, istouch )
    if button ==  1 then
        startDrag = true; miX = x; miY = y
    else
        minX = -2.5; maxX = 2.5; minY = minX; maxY = maxX
        startFractal()
        startDrag = false
    end
end
function love.mousereleased( x, y, button, istouch )
    if startDrag then
        local l
        if x > miX then mxX = x
        else l = x; mxX = miX; miX = l
        end
        if y > miY then mxY = y
        else l = y; mxY = miY; miY = l
        end
        miX = remap( miX, 0, wid, minX, maxX )
        mxX = remap( mxX, 0, wid, minX, maxX )
        miY = remap( miY, 0, hei, minY, maxY )
        mxY = remap( mxY, 0, hei, minY, maxY )
        minX = miX; maxX = mxX; minY = miY; maxY = mxY
        startFractal()
    end
end
function love.draw()
    love.graphics.draw( canvas )
end
-- Mandelbrot set in Lua 6/15/2020 db
local charmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "@" }
for y = -1.3, 1.3, 0.1 do
  for x = -2.1, 1.1, 0.04 do
    local zi, zr, i = 0, 0, 0
    while i < 100 do
      if (zi*zi+zr*zr >= 4) then break end
      zr, zi, i = zr*zr-zi*zi+x, 2*zr*zi+y, i+1
    end
    io.write(charmap[i%10])
  end
  print()
end

generate and draw the Mandelbrot set using various algorithms and functions. It requires the LÖVE 2D Engine for execution. The code also allows for zooming in and out using mouse interactions. It produces an 80x25 ASCII Mandelbrot set with a limited iteration count to fit within two lines of 80 columns.


function sumf(a, ...) return a and a + sumf(...) or 0 end
function sumt(t) return sumf(unpack(t)) end
function prodf(a, ...) return a and a * prodf(...) or 1 end
function prodt(t) return prodf(unpack(t)) end

print(sumt{1, 2, 3, 4, 5})
print(prodt{1, 2, 3, 4, 5})

function table.sum(arr, length)
      --same as if <> then <> else <>
      return length == 1 and arr[1] or arr[length] + table.sum(arr, length -1)
end

function table.product(arr, length)
      return length == 1 and arr[1] or arr[length] * table.product(arr, length -1)
end

t = {1,2,3}
print(table.sum(t,#t))
print(table.product(t,3))

Calculate the sum and product of all integers in an array.


function isLeapYear(year)
  return year%4==0 and (year%100~=0 or year%400==0)
end

"Determines if a specified year is a leap year in the Gregorian calendar."


implement the MD5 Message Digest Algorithm directly without using built-in or external hashing libraries. The implementation produces a correct message digest for an input string. The code also handles bit manipulation, unsigned integers, and works with little-endian data. It also pays attention to details such as boundary conditions, padding, endianness, and data layout. The code includes verification strings and hashes from RFC 1321 for testing.


print( "Fire", "Police", "Sanitation" )
sol = 0
for f = 1, 7 do
    for p = 1, 7 do
        for s = 1, 7 do
            if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then
                print( f, p, s ); sol = sol + 1
            end
        end
    end
end
print( string.format( "\n%d solutions found", sol ) )

all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.


a = "string"
b = a
print(a == b) -->true
print(b) -->string

distinguish between copying a string's content and creating an additional reference to an existing string in Lua, considering that Lua strings are immutable.


function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end

local m,n
function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions take an integer as input and return the corresponding sequence value. If the input is 0, the Female function returns 1 and the Male function returns 0. For any other positive integer, the Female function returns the input minus the Male function's output for the previous Female function's output. Similarly, the Male function returns the input minus the Female function's output for the previous Male function's output. The functions are locally scoped and forward declared.


math.randomseed(os.time())
local a = {1,2,3}
print(a[math.random(1,#a)])

demonstrate how to select a random element from a list.


function decodeChar(hex)
	return string.char(tonumber(hex,16))
end

function decodeString(str)
	local output, t = string.gsub(str,"%%(%x%x)",decodeChar)
	return output
end

-- will print "http://foo bar/"
print(decodeString("http%3A%2F%2Ffoo%20bar%2F"))

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


function binarySearch (list,value)
    local low = 1
    local high = #list
    while low <= high do
        local mid = math.floor((low+high)/2)
        if list[mid] > value then high = mid - 1
        elseif list[mid] < value then low = mid + 1
        else return mid
        end
    end
    return false
end

function binarySearch (list, value)
    local function search(low, high)
        if low > high then return false end
        local mid = math.floor((low+high)/2)
        if list[mid] > value then return search(low,mid-1) end
        if list[mid] < value then return search(mid+1,high) end
        return mid
    end
    return search(1,#list)
end

The code implements a binary search algorithm, which finds a specific value in a sorted integer array. The algorithm divides the range of values into halves until the desired value is found. It includes both recursive and iterative implementations, and it handles cases where there are multiple equal values. The code also identifies the leftmost and rightmost insertion points for the given value. Additionally, it includes a fix for potential overflow bugs.


print( "Program name:", arg[0] )

print "Arguments:"
for i = 1, #arg do
    print( i," ", arg[i] )
end

"Code retrieves and prints command-line arguments given to the program using the global table arg in Lua scripting language, without using argc and argv conventions. It also parses these arguments intelligently."


function degToRad( d )
    return d * 0.01745329251
end

function love.load()
    g = love.graphics
    rodLen, gravity, velocity, acceleration = 260, 3, 0, 0
    halfWid, damp = g.getWidth() / 2, .989
    posX, posY, angle = halfWid
    TWO_PI, angle = math.pi * 2, degToRad( 90 )
end

function love.update( dt )
    acceleration = -gravity / rodLen * math.sin( angle )
    angle = angle + velocity; if angle > TWO_PI then angle = 0 end
    velocity = velocity + acceleration
    velocity = velocity * damp
    posX = halfWid + math.sin( angle ) * rodLen
    posY = math.cos( angle ) * rodLen
end

function love.draw()
    g.setColor( 250, 0, 250 )
    g.circle( "fill", halfWid, 0, 8 )
    g.line( halfWid, 4, posX, posY )
    g.setColor( 250, 100, 20 )
    g.circle( "fill", posX, posY, 20 )
end

Creates and animates a simple physical model of a gravity pendulum using the LÖVE 2D Engine.


local json = require("json")

local json_data = [=[[
    42,
    3.14159,
    [ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ],
    { "H": 1, "He": 2, "X": null, "Li": 3 },
    null,
    true,
    false
]]=]

print("Original JSON: " .. json_data)
local data = json.decode(json_data)
json.util.printValue(data, 'Lua')
print("JSON re-encoded: " .. json.encode(data))

local data = {
    42,
    3.14159,
    {
        2, 4, 8, 16, 32, 64,
        "apples",
        "bananas",
        "cherries"
    },
    {
        H = 1,
        He = 2,
        X = json.util.null(),
        Li = 3
    },
    json.util.null(),
    true,
    false
}

print("JSON from new Lua data: " .. json.encode(data))

The code loads a JSON string into a data structure and creates a new data structure, serializing it into JSON. It uses objects and arrays, ensuring the JSON is valid. In Lua, it handles null values in JSON using the luajson library, specifically the json.util.null function.


function nroot(root, num)
  return num^(1/root)
end

Implement the principal nth root algorithm for a positive real number A.


socket = require "socket"
print( socket.dns.gethostname() )

Determines and outputs the hostname of the system where the routine is executed using LuaSocket.


function leoNums (n, L0, L1, add)
  local L0, L1, add = L0 or 1, L1 or 1, add or 1
  local lNums, nextNum = {L0, L1}
  while #lNums < n do
    nextNum = lNums[#lNums] + lNums[#lNums - 1] + add
    table.insert(lNums, nextNum)
  end
  return lNums
end

function show (msg, t)
  print(msg .. ":")
  for i, x in ipairs(t) do
    io.write(x .. " ")
  end
  print("\n")
end

show("Leonardo numbers", leoNums(25))
show("Fibonacci numbers", leoNums(25, 0, 1, 0))

generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.


local function help()
	print [[
 The 24 Game

 Given any four digits in the range 1 to 9, which may have repetitions,
 Using just the +, -, *, and / operators; and the possible use of
 brackets, (), show how to make an answer of 24.

 An answer of "q" will quit the game.
 An answer of "!" will generate a new set of four digits.

 Note: you cannot form multiple digit numbers from the supplied digits,
 so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.

 ]]
end

local function generate(n)
	result = {}
	for i=1,n do
		result[i] = math.random(1,9)
	end
	return result
end

local function check(answer, digits)
	local adig = {}
	local ddig = {}
	local index
	local lastWasDigit = false
	for i=1,9 do adig[i] = 0 ddig[i] = 0 end
	allowed = {['(']=true,[')']=true,[' ']=true,['+']=true,['-']=true,['*']=true,['/']=true,['\t']=true,['1']=true,['2']=true,['3']=true,['4']=true,['5']=true,['6']=true,['7']=true,['8']=true,['9']=true}
	for i=1,string.len(answer) do
		if not allowed[string.sub(answer,i,i)] then
			return false
		end
		index = string.byte(answer,i)-48
		if index > 0 and index < 10 then
			if lastWasDigit then
				return false
			end
			lastWasDigit = true
			adig[index] = adig[index] + 1
		else
			lastWasDigit = false
		end
	end
	for i,digit in next,digits do
		ddig[digit] = ddig[digit]+1
	end
	for i=1,9 do
		if adig[i] ~= ddig[i] then
			return false
		end
	end
	return loadstring('return '..answer)()
end

local function game24()
	help()
	math.randomseed(os.time())
	math.random()
	local digits = generate(4)
	local trial = 0
	local answer = 0
	local ans = false
	io.write 'Your four digits:'
	for i,digit in next,digits do
		io.write (' ' .. digit)
	end
	print()
	while ans ~= 24 do
		trial = trial + 1
		io.write("Expression "..trial..": ")
		answer = io.read()
		if string.lower(answer) == 'q' then
			break
		end
		if answer == '!' then
			digits = generate(4)
			io.write ("New digits:")
			for i,digit in next,digits do
				io.write (' ' .. digit)
			end
			print()
		else
			ans = check(answer,digits)
			if ans == false then
				print ('The input '.. answer ..' was wonky!')
			else
				print (' = '.. ans)
				if ans == 24 then
					print ("Thats right!")
				end
			end
		end
	end
end
game24()

function twentyfour()
   print [[
 The 24 Game

 Given any four digits in the range 1 to 9, which may have repetitions,
 Using just the +, -, *, and / operators; and the possible use of
 brackets, (), show how to make an answer of 24.

 An answer of "q" will quit the game.
 An answer of "!" will generate a new set of four digits.

 Note: you cannot form multiple digit numbers from the supplied digits,
 so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.

 ]]
   expr = re.compile[[   --matches properly formatted infix expressions and returns all numerals as captures
         expr <- (!.) / (<paren> / <number>) (<ws> <oper> <ws> <expr>)?
         number <- {[0-9]}
         ws <- " "*
         oper <- [-+/*]
         paren <- "(" <ws> <expr> <ws> ")"   ]]
   local val_t = {math.random(9), math.random(9), math.random(9), math.random(9)}
   table.sort(val_t)
   print("the digits are " .. table.concat(val_t, ", "))
   local ex = io.read()
   a, b, c, d, e = expr:match(ex)
   if a and b and c and d and not e then --if there is a fifth numeral the player is cheating
      local digs = {a + 0, b + 0, c + 0, d + 0}
      local flag = false -- (terrorism!)
      table.sort(digs)
      for i = 1, 4 do
	   flag = digs[i] ~= val_t[i] and not print"Wrong digits!" or flag
      end
      if not flag and loadstring("return " .. ex)() == 24 then
         print"You win!"
      else
         print"You lose."
      end
   else print"wat" --expression could not be interpreted as arithmetic
   end
end
twentyfour()

The code generates four random digits from 1 to 9 and prompts the player to form an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using only multiplication, division, addition, and subtraction. The division operation preserves remainders. The program checks and evaluates the player's expression, but does not generate or test the feasibility of the expression itself. The order of the digits in the expression doesn't need to match the original order.


local C, Ct, R, Cf, Cc = lpeg.C, lpeg.Ct, lpeg.R, lpeg.Cf, lpeg.Cc
astable = Ct(C(1)^0)

function compress(t)
    local ret = {}
    for i, v in ipairs(t) do
      if t[i-1] and v == t[i-1] then
        ret[#ret - 1] = ret[#ret - 1] + 1
      else
        ret[#ret + 1] = 1
        ret[#ret + 1] = v
      end
    end
    t = ret
    return table.concat(ret)
end
q = io.read()
print(compress(astable:match(q)))

undo = Ct((Cf(Cc"0" * C(R"09")^1, function(a, b) return 10 * a + b end) * C(R"AZ"))^0)

function decompress(s)
  t = undo:match(s)
  local ret = ""
  for i = 1, #t - 1, 2 do
    for _ = 1, t[i] do
      ret = ret .. t[i+1]
    end
  end
  return ret
end

implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.


a = "hello "
print(a .. "world")
c = a .. "world"
print(c)

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


function encodeChar(chr)
	return string.format("%%%X",string.byte(chr))
end

function encodeString(str)
	local output, t = string.gsub(str,"[^%w]",encodeChar)
	return output
end

-- will print "http%3A%2F%2Ffoo%20bar%2F"
print(encodeString("http://foo bar/"))

provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, "http://foo bar/" is encoded as "http%3A%2F%2Ffoo%20bar%2F".


function sort(word)
  local bytes = {word:byte(1, -1)}
  table.sort(bytes)
  return string.char(table.unpack(bytes))
end

-- Read in and organize the words.
-- word_sets[<alphabetized_letter_list>] = {<words_with_those_letters>}
local word_sets = {}
local max_size = 0
for word in io.lines('unixdict.txt') do
  local key = sort(word)
  if word_sets[key] == nil then word_sets[key] = {} end
  table.insert(word_sets[key], word)
  max_size = math.max(max_size, #word_sets[key])
end

-- Print out the answer sets.
for _, word_set in pairs(word_sets) do
  if #word_set == max_size then
    for _, word in pairs(word_set) do io.write(word .. ' ') end
    print('')  -- Finish with a newline.
  end
end

"Output: The code identifies sets of words from the provided URL that are anagrams, i.e., they share the same characters but in a different order. It specifically finds the sets with the most words in them. The code assumes the use of a networking library for Lua, as Lua's core library does not support network functionality."


local function carpet(n, f)
  print("n = " .. n)
  local function S(x, y)
    if x==0 or y==0 then return true
    elseif x%3==1 and y%3==1 then return false end
    return S(x//3, y//3)
  end
  for y = 0, 3^n-1 do
    for x = 0, 3^n-1 do
      io.write(f(S(x, y)))
    end
    print()
  end
  print()
end

for n = 0, 4 do
  carpet(n, function(b) return b and "■ " or "  " end)
end

generate an ASCII or graphical representation of a Sierpinski carpet of a given order N. The representation uses specific placement of whitespace and non-whitespace characters. The code utilizes recursion and tail calls.


local build_freqtable = function (data)
  local freq = { }

  for i = 1, #data do
    local cur = string.sub (data, i, i)
    local count = freq [cur] or 0
    freq [cur] = count + 1
  end

  local nodes = { }
  for w, f in next, freq do
    nodes [#nodes + 1] = { word = w, freq = f }
  end

  table.sort (nodes, function (a, b) return a.freq > b.freq end) --- reverse order!

  return nodes
end

local build_hufftree = function (nodes)
  while true do
    local n = #nodes
    local left = nodes [n]
    nodes [n] = nil

    local right = nodes [n - 1]
    nodes [n - 1] = nil

    local new = { freq = left.freq + right.freq, left = left, right = right }

    if n == 2 then return new end

    --- insert new node at correct priority
    local prio = 1
    while prio < #nodes and nodes [prio].freq > new.freq do
      prio = prio + 1
    end
    table.insert (nodes, prio, new)
  end
end

local print_huffcodes do
  local rec_build_huffcodes
  rec_build_huffcodes = function (node, bits, acc)
    if node.word == nil then
      rec_build_huffcodes (node.left,  bits .. "0", acc)
      rec_build_huffcodes (node.right, bits .. "1", acc)
      return acc
    else --- leaf
      acc [#acc + 1] = { node.freq, node.word, bits }
    end
    return acc
  end

  print_huffcodes = function (root)
    local codes = rec_build_huffcodes (root, "", { })
    table.sort (codes, function (a, b) return a [1] < b [1] end)
    print ("frequency\tword\thuffman code")
    for i = 1, #codes do
      print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i])))
    end
  end
end

local huffcode = function (data)
  local nodes = build_freqtable (data)
  local huff = build_hufftree (nodes)
  print_huffcodes (huff)
  return 0
end

return huffcode "this is an example for huffman encoding"

frequency	word	huffman code
        1	‘g’	“01111”
        1	‘p’	“01011”
        1	‘d’	“01100”
        1	‘c’	“01101”
        1	‘t’	“01010”
        1	‘r’	“10000”
        1	‘u’	“11110”
        1	‘x’	“10001”
        1	‘l’	“01110”
        2	‘o’	“11111”
        2	‘m’	“0011”
        2	‘h’	“0010”
        2	‘s’	“0100”
        3	‘i’	“1101”
        3	‘f’	“1110”
        3	‘a’	“1100”
        3	‘e’	“1001”
        4	‘n’	“000”
        6	‘ ’	“101”

The code takes a string input, calculates the frequency of each character, and generates a Huffman encoding for each character. It constructs a Huffman tree based on character frequencies and assigns binary codes to each character, ensuring that more frequent characters have shorter codes. The output is a table of characters and their corresponding Huffman encodings.


require"iuplua"
l = iup.label{title="There have been no clicks yet."}
b = iup.button{title="Click me!"}
clicks = 0
function b:button_cb()
  clicks = clicks + 1
  l.title = "There have been " .. clicks/2 .. " clicks so far." --yes, this is correct.
end
dlg = iup.dialog{iup.vbox{l, b}, title="Simple Windowed Application"}
dlg:show()

if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then
  iup.MainLoop()
end

Implement a windowed application with a label and a button. The label initially displays "There have been no clicks yet". The button, labelled "click me", updates the label to show the number of times it has been clicked when interacted with.


-- Import module
local sql = require("ljsqlite3")

-- Open connection to database file
local conn = sql.open("address.sqlite")

-- Create address table unless it already exists
conn:exec[[
CREATE TABLE IF NOT EXISTS address(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  street TEXT NOT NULL,
  city TEXT NOT NULL,
  state TEXT NOT NULL,
  zip TEXT NOT NULL)
]]

-- Explicitly close connection
conn:close()

"Create a table in a database to store US postal addresses, including fields for unique identifier, street address, city, state code, and zipcode. The code also demonstrates how to open a database connection in non-database languages using LJSQLite3."


The code performs a countdown from 10 to 0 using a downward for loop.


function Encrypt( _msg, _key )
    local msg = { _msg:upper():byte( 1, -1 ) }
    local key = { _key:upper():byte( 1, -1 ) }
    local enc = {}

    local j, k = 1, 1
    for i = 1, #msg do
        if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then
            enc[k] = ( msg[i] + key[j] - 2*string.byte('A') ) % 26 + string.byte('A')

            k = k + 1
            if j == #key then j = 1 else j = j + 1 end
        end
    end

    return string.char( unpack(enc) )
end

function Decrypt( _msg, _key )
    local msg = { _msg:byte( 1, -1 ) }
    local key = { _key:upper():byte( 1, -1 ) }
    local dec = {}

    local j = 1
    for i = 1, #msg do
       dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A')

       if j == #key then j = 1 else j = j + 1 end
    end

    return string.char( unpack(dec) )
end

original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
key = "VIGENERECIPHER";

encrypted = Encrypt( original, key )
decrypted = Decrypt( encrypted, key )

print( encrypted )
print( decrypted )

WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH

Implement both encryption and decryption of a Vigenère cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.


demonstrate a for-loop with a step-value greater than one.


function sum(var, a, b, str)
  local ret = 0
  for i = a, b do
    ret = ret + setfenv(loadstring("return "..str), {[var] = i})()
  end
  return ret
end
print(sum("i", 1, 100, "1/i"))

implement Jensen's Device, a programming technique devised by Jørn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.


Works with: LÖVE version 11.0 or higher
local clr =  {}
function drawMSquares()
	local points = {}
	for y = 0, hei-1 do
		for x = 0, wid-1 do
			local idx = bit.bxor(x, y)%256
			local r, g, b = clr[idx][1], clr[idx][2], clr[idx][3]
			local point = {x+1, y+1, r/255, g/255, b/255, 1}
			table.insert (points, point)
		end
	end
	love.graphics.points(points)
end

function createPalette()
	for i = 0, 255 do
		clr[i] = {i*2.8%256, i*3.2%256, i*1.5%256}
	end
end

function love.load()
	wid, hei = 256, 256
	love.window.setMode(wid, hei)
	canvas = love.graphics.newCanvas()
	love.graphics.setCanvas(canvas)
		createPalette()
		drawMSquares()
	love.graphics.setCanvas()
end

function love.draw()
	love.graphics.setColor(1,1,1)
	love.graphics.draw(canvas)
end

generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.


Works with: Lua version 5.1
math.randomseed( os.time() )

-- Fisher-Yates shuffle from http://santos.nfshost.com/shuffling.html
function shuffle(t)
  for i = 1, #t - 1 do
    local r = math.random(i, #t)
    t[i], t[r] = t[r], t[i]
  end
end

-- builds a width-by-height grid of trues
function initialize_grid(w, h)
  local a = {}
  for i = 1, h do
    table.insert(a, {})
    for j = 1, w do
      table.insert(a[i], true)
    end
  end
  return a
end

-- average of a and b
function avg(a, b)
  return (a + b) / 2
end

dirs = {
  {x = 0, y = -2}, -- north
  {x = 2, y = 0}, -- east
  {x = -2, y = 0}, -- west
  {x = 0, y = 2}, -- south
}

function make_maze(w, h)
  w = w or 16
  h = h or 8

  local map = initialize_grid(w*2+1, h*2+1)

  function walk(x, y)
    map[y][x] = false

    local d = { 1, 2, 3, 4 }
    shuffle(d)
    for i, dirnum in ipairs(d) do
      local xx = x + dirs[dirnum].x
      local yy = y + dirs[dirnum].y
      if map[yy] and map[yy][xx] then
        map[avg(y, yy)][avg(x, xx)] = false
        walk(xx, yy)
      end
    end
  end

  walk(math.random(1, w)*2, math.random(1, h)*2)

  local s = {}
  for i = 1, h*2+1 do
    for j = 1, w*2+1 do
      if map[i][j] then
        table.insert(s, '#')
      else
        table.insert(s, ' ')
      end
    end
    table.insert(s, '\n')
  end
  return table.concat(s)
end

print(make_maze())

generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.


a = {}
n = 1000
len = math.modf( 10 * n / 3 )

for j = 1, len do
    a[j] = 2
end
nines = 0
predigit = 0
for j = 1, n do
    q = 0
    for i = len, 1, -1 do
        x = 10 * a[i] + q * i
        a[i] = math.fmod( x, 2 * i - 1 )
        q = math.modf( x / ( 2 * i - 1 ) )
    end
    a[1] = math.fmod( q, 10 )
    q = math.modf( q / 10 )
    if q == 9 then
        nines = nines + 1
    else
        if q == 10 then
            io.write( predigit + 1 )
            for k = 1, nines do
                io.write(0)
            end
            predigit = 0
            nines = 0
        else
            io.write( predigit )
            predigit = q
            if nines ~= 0 then
                for k = 1, nines do
                    io.write( 9 )
                end
                nines = 0
            end
        end
    end
end
print( predigit )

03141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086 ...

are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.


function arraycompare(a, b)
    for i = 1, #a do
        if b[i] == nil then
            return true
        end
        if a[i] ~= b[i] then
            return a[i] < b[1]
        end
    end
    return true
end

function randomarray()
    local t = {}
    for i = 1, math.random(1, 10) do
        t[i] = math.random(1, 10)
    end
    return t
end

math.randomseed(os.time())

for i = 1, 10 do
    local a = randomarray()
    local b = randomarray()

    print(
        string.format("{%s} %s {%s}",
        table.concat(a, ', '),
        arraycompare(a, b) and "<=" or ">",
        table.concat(b, ', ')))
end

implement a function to compare two numerical lists or arrays lexicographically. The function returns true if the first list should be ordered before the second, and false otherwise. It compares elements sequentially until one list runs out of elements. If the first list ends first, the function returns true, but if the second list or both lists end simultaneously, it returns false. This function is particularly useful in Lua, where tables with numerical indices do not support comparison by default.


function ack(M,N)
    if M == 0 then return N + 1 end
    if N == 0 then return ack(M-1,1) end
    return ack(M-1,ack(M, N-1))
end

#!/usr/bin/env luajit
local gmp = require 'gmp' ('libgmp')
local mpz, 		z_mul, 		z_add, 		z_add_ui, 		z_set_d =
	gmp.types.z, gmp.z_mul,	gmp.z_add,	gmp.z_add_ui, 	gmp.z_set_d
local z_cmp, 	z_cmp_ui, 		z_init_d, 			z_set=
	gmp.z_cmp,	gmp.z_cmp_ui, 	gmp.z_init_set_d, 	gmp.z_set
local printf = gmp.printf

local function ack(i,n)
	local nxt=setmetatable({},  {__index=function(t,k) local z=mpz() z_init_d(z, 0) t[k]=z return z end})
	local goal=setmetatable({}, {__index=function(t,k) local o=mpz() z_init_d(o, 1) t[k]=o return o end})
	goal[i]=mpz() z_init_d(goal[i], -1)
	local v=mpz() z_init_d(v, 0)
	local ic
	local END=n+1
	local ntmp,gtmp
	repeat
		ic=0
		ntmp,gtmp=nxt[ic], goal[ic]
		z_add_ui(v, ntmp, 1)
		while z_cmp(ntmp, gtmp) == 0 do
			z_set(gtmp,v)
			z_add_ui(ntmp, ntmp, 1)
			nxt[ic], goal[ic]=ntmp, gtmp
			ic=ic+1
			ntmp,gtmp=nxt[ic], goal[ic]
		end
		z_add_ui(ntmp, ntmp, 1)
		nxt[ic]=ntmp
	until z_cmp_ui(nxt[i], END) == 0
	return v
end

if #arg<1 then
	print("Ackermann: "..arg[0].." <num1> [num2]")
else
	printf("%Zd\n", ack(tonumber(arg[1]), arg[2] and tonumber(arg[2]) or 0))
end

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.


gamma, coeff, quad, qui, set = 0.577215664901, -0.65587807152056, -0.042002635033944, 0.16653861138228,	-0.042197734555571
function recigamma(z)
  return z + gamma * z^2 + coeff * z^3 + quad * z^4 + qui * z^5 + set * z^6
end

function gammafunc(z)
  if z == 1 then return 1
  elseif math.abs(z) <= 0.5 then return 1 / recigamma(z)
  else return (z - 1) * gammafunc(z-1)
  end
end

Implement and compare the Gamma function using built-in/library function and other algorithms like Lanczos approximation, Stirling's approximation, and Reciprocal gamma function for small values. The Gamma function is computed through numerical integration.


N = 8

-- We'll use nil to indicate no queen is present.
grid = {}
for i = 0, N do
  grid[i] = {}
end

function can_find_solution(x0, y0)
  local x0, y0 = x0 or 0, y0 or 1  -- Set default vals (0, 1).
  for x = 1, x0 - 1 do
    if grid[x][y0] or grid[x][y0 - x0 + x] or grid[x][y0 + x0 - x] then
      return false
    end
  end
  grid[x0][y0] = true
  if x0 == N then return true end
  for y0 = 1, N do
    if can_find_solution(x0 + 1, y0) then return true end
  end
  grid[x0][y0] = nil
  return false
end

if can_find_solution() then
  for y = 1, N do
    for x = 1, N do
      -- Print "|Q" if grid[x][y] is true; "|_" otherwise.
      io.write(grid[x][y] and "|Q" or "|_")
    end
    print("|")
  end
else
  print(string.format("No solution for %d queens.\n", N))
end

"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N."


a = {1, 2, 3}
b = {4, 5, 6}

for _, v in pairs(b) do
    table.insert(a, v)
end

print(table.concat(a, ", "))

demonstrate how to concatenate two arrays.


items = {
    {"map", 9, 150},
    {"compass", 13, 35},
    {"water", 153, 200},
    {"sandwich", 50, 160},
    {"glucose", 15, 60},
    {"tin", 68, 45},
    {"banana", 27, 60},
    {"apple", 39,  40},
    {"cheese", 23, 30},
    {"beer", 52, 10},
    {"suntan cream", 11, 70},
    {"camera", 32, 30},
    {"t-shirt", 24, 15},
    {"trousers", 48, 10},
    {"umbrella", 73, 40},
    {"waterproof trousers", 42, 70},
    {"waterproof overclothes", 43, 75},
    {"note-case", 22, 80},
    {"sunglasses", 7, 20},
    {"towel", 18, 12},
    {"socks", 4, 50},
    {"book", 30, 10},
}

local unpack = table.unpack

function m(i, w)
    if i<1 or w==0 then
        return 0, {}
    else
        local _, wi, vi = unpack(items[i])
        if wi > w then
            return mm(i - 1, w)
        else
            local vn, ln = mm(i - 1, w)
            local vy, ly = mm(i - 1, w - wi)
            if vy + vi > vn then
                return vy + vi, { i, ly }
            else
                return vn, ln
            end
        end
    end
end

local memo, mm_calls = {}, 0
function mm(i, w) -- memoization function for m
    mm_calls = mm_calls + 1
    local key = 10000*i + w
    local result = memo[key]
    if not result then
        result = { m(i, w) }
        memo[key] = result
    end
    return unpack(result)
end

local total_value, index_list = m(#items, 400)

function list_items(head) -- makes linked list iterator function
    return function()
        local item, rest = unpack(head)
        head = rest
        return item
    end
end

local names = {}
local total_weight = 0
for i in list_items(index_list) do
    local name, weight = unpack(items[i])
    table.insert(names, 1, name)
    total_weight = total_weight + weight
end

local function printf(fmt, ...) print(string.format(fmt, ...)) end
printf("items to pack: %s", table.concat(names, ", "))
printf("total value: %d", total_value)
printf("total weight: %d", total_weight)

-- out of curiosity
local count = 0
for k,v in pairs(memo) do count = count + 1 end
printf("\n(memo count: %d; mm call count: %d)", count, mm_calls)

The code implements a solution to the 0-1 Knapsack problem. It helps a tourist to determine the combination of items to carry in his knapsack, with a weight limit of 4kg, in a way that maximizes the total value of the items. The items, their weights and values are given in a list, and only one unit of each item can be taken.


local Person = {}
Person.__index = Person

function Person.new(inName)
    local o = {
        name            = inName,
        prefs           = nil,
        fiance          = nil,
        _candidateIndex = 1,
    }
    return setmetatable(o, Person)
end

function Person:indexOf(other)
    for i, p in pairs(self.prefs) do
        if p == other then return i end
    end
    return 999
end

function Person:prefers(other)
    return self:indexOf(other) < self:indexOf(self.fiance)
end

function Person:nextCandidateNotYetProposedTo()
    if self._candidateIndex >= #self.prefs then return nil end
    local c = self.prefs[self._candidateIndex];
    self._candidateIndex = self._candidateIndex + 1
    return c;
end

function Person:engageTo(other)
    if other.fiance then
        other.fiance.fiance = nil
    end
    other.fiance = self
    if self.fiance then
        self.fiance.fiance = nil
    end
    self.fiance = other;
end

local function isStable(men)
    local women = men[1].prefs
    local stable = true
    for _, guy in pairs(men) do
        for _, gal in pairs(women) do
            if guy:prefers(gal) and gal:prefers(guy) then
                stable = false
                print(guy.name .. ' and ' .. gal.name ..
                      ' prefer each other over their partners ' ..
                      guy.fiance.name .. ' and ' .. gal.fiance.name)
            end
        end
    end
    return stable
end

local abe  = Person.new("Abe")
local bob  = Person.new("Bob")
local col  = Person.new("Col")
local dan  = Person.new("Dan")
local ed   = Person.new("Ed")
local fred = Person.new("Fred")
local gav  = Person.new("Gav")
local hal  = Person.new("Hal")
local ian  = Person.new("Ian")
local jon  = Person.new("Jon")

local abi  = Person.new("Abi")
local bea  = Person.new("Bea")
local cath = Person.new("Cath")
local dee  = Person.new("Dee")
local eve  = Person.new("Eve")
local fay  = Person.new("Fay")
local gay  = Person.new("Gay")
local hope = Person.new("Hope")
local ivy  = Person.new("Ivy")
local jan  = Person.new("Jan")

abe.prefs  = { abi,  eve,  cath, ivy,  jan,  dee,  fay,  bea,  hope, gay  }
bob.prefs  = { cath, hope, abi,  dee,  eve,  fay,  bea,  jan,  ivy,  gay  }
col.prefs  = { hope, eve,  abi,  dee,  bea,  fay,  ivy,  gay,  cath, jan  }
dan.prefs  = { ivy,  fay,  dee,  gay,  hope, eve,  jan,  bea,  cath, abi  }
ed.prefs   = { jan,  dee,  bea,  cath, fay,  eve,  abi,  ivy,  hope, gay  }
fred.prefs = { bea,  abi,  dee,  gay,  eve,  ivy,  cath, jan,  hope, fay  }
gav.prefs  = { gay,  eve,  ivy,  bea,  cath, abi,  dee,  hope, jan,  fay  }
hal.prefs  = { abi,  eve,  hope, fay,  ivy,  cath, jan,  bea,  gay,  dee  }
ian.prefs  = { hope, cath, dee,  gay,  bea,  abi,  fay,  ivy,  jan,  eve  }
jon.prefs  = { abi,  fay,  jan,  gay,  eve,  bea,  dee,  cath, ivy,  hope }

abi.prefs  = { bob,  fred, jon,  gav,  ian,  abe,  dan,  ed,   col,  hal  }
bea.prefs  = { bob,  abe,  col,  fred, gav,  dan,  ian,  ed,   jon,  hal  }
cath.prefs = { fred, bob,  ed,   gav,  hal,  col,  ian,  abe,  dan,  jon  }
dee.prefs  = { fred, jon,  col,  abe,  ian,  hal,  gav,  dan,  bob,  ed   }
eve.prefs  = { jon,  hal,  fred, dan,  abe,  gav,  col,  ed,   ian,  bob  }
fay.prefs  = { bob,  abe,  ed,   ian,  jon,  dan,  fred, gav,  col,  hal  }
gay.prefs  = { jon,  gav,  hal,  fred, bob,  abe,  col,  ed,   dan,  ian  }
hope.prefs = { gav,  jon,  bob,  abe,  ian,  dan,  hal,  ed,   col,  fred }
ivy.prefs  = { ian,  col,  hal,  gav,  fred, bob,  abe,  ed,   jon,  dan  }
jan.prefs  = { ed,   hal,  gav,  abe,  bob,  jon,  col,  ian,  fred, dan  }

local men = abi.prefs
local freeMenCount = #men
while freeMenCount > 0 do
    for _, guy in pairs(men) do
        if not guy.fiance then
            local gal = guy:nextCandidateNotYetProposedTo()
            if not gal.fiance then
                guy:engageTo(gal)
                freeMenCount = freeMenCount - 1
            elseif gal:prefers(guy) then
                guy:engageTo(gal)
            end
        end
    end
end

print(' ')
for _, guy in pairs(men) do
    print(guy.name .. ' is engaged to ' .. guy.fiance.name)
end
print('Stable: ', isStable(men))

print(' ')
print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners")
jon.fiance, fred.fiance = fred.fiance, jon.fiance
print('Stable: ', isStable(men))

"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability."


function a(i)
    print "Function a(i) called."
    return i
end

function b(i)
    print "Function b(i) called."
    return i
end

i = true
x = a(i) and b(i);  print ""
y = a(i) or  b(i);  print ""

i = false
x = a(i) and b(i);  print ""
y = a(i) or  b(i)

create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.


local M = {}

-- module-local variables
local BUZZER = pio.PB_10
local dit_length, dah_length, word_length

-- module-local functions
local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap

buzz = function(duration)
  pio.pin.output(BUZZER)
  pio.pin.setlow(BUZZER)
  tmr.delay(tmr.SYS_TIMER, duration)
  pio.pin.sethigh(BUZZER)
  pio.pin.input(BUZZER)
end

dah = function()
  buzz(dah_length)
end

dit = function()
  buzz(dit_length)
end

init = function(baseline)
  dit_length = baseline
  dah_length = 2 * baseline
  word_length = 4 * baseline
end

inter_element_gap = function()
  pause(dit_length)
end

medium_gap = function()
  pause(word_length)
end

pause = function(duration)
  tmr.delay(tmr.SYS_TIMER, duration)
end

sequence = function(codes)
  if codes then
    for _,f in ipairs(codes) do
      f()
      inter_element_gap()
    end
    short_gap()
  end
end

short_gap = function()
  pause(dah_length)
end

local morse = {
  a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit },
  d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit },
  g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit },
  j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit },
  m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah },
  p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit },
  s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah },
  v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah },
  y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit },

  ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah },
  ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah },
  ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit },
  ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit },
  ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit },

  [" "] = { medium_gap }
}

-- public interface
M.beep = function(message)
  message = message:lower()
  for _,ch in ipairs { message:byte(1, #message) } do
    sequence(morse[string.char(ch)])
  end
end

M.set_dit = function(duration)
  init(duration)
end

-- initialization code
init(50000)

return M

morse = require 'morse'
morse.beep "I am the very model of a modern major-general."

send a string as audible Morse code to an audio device, ignoring unknown characters or indicating them with a different pitch. It uses eLua code to beep the speaker in Morse code on a specific evaluation board. The code can be converted for other Lua 5.n environments with a sound library.


blocks = {
	{"B","O"};	{"X","K"};	{"D","Q"};	{"C","P"};
	{"N","A"};	{"G","T"};	{"R","E"};	{"T","G"};
	{"Q","D"};	{"F","S"};	{"J","W"};	{"H","U"};
	{"V","I"};	{"A","N"};	{"O","B"};	{"E","R"};
	{"F","S"};	{"L","Y"};	{"P","C"};	{"Z","M"};
	};

function canUse(table, letter)
	for i,v in pairs(blocks) do
		if (v[1] == letter:upper() or v[2] == letter:upper())  and table[i] then
			table[i] = false;
			return true;
		end
	end
	return false;
end

function canMake(Word)
	local Taken = {};
	for i,v in pairs(blocks) do
		table.insert(Taken,true);
	end
	local found = true;
	for i = 1,#Word do
		if not canUse(Taken,Word:sub(i,i)) then
			found = false;
		end
	end
	print(found)
end

"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed."


require "md5"

--printing a sum:
print(md5.sumhexa"The quick brown fox jumps over the lazy dog")

--running the test suite:

local function test(msg,sum) assert(md5.sumhexa(msg)==sum) end

test("","d41d8cd98f00b204e9800998ecf8427e")
test("a","0cc175b9c0f1b6a831c399e269772661")
test("abc","900150983cd24fb0d6963f7d28e17f72")
test("message digest","f96b697d7cb7938d525a2f31aaf161d0")
test("abcdefghijklmnopqrstuvwxyz","c3fcd3d76192e4007dfb496cca67e13b")
test("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789","d174ab98d277d9f5a5611c2c9f419d9f")
test("12345678901234567890123456789012345678901234567890123456789012345678901234567890","57edf4a22be3c955ac49da2e2107b67a")

Implement and validate an MD5 encoding for a given string, with optional testing against IETF RFC (1321) values. Note the known weaknesses of MD5 and consider alternatives for production-grade cryptography. The code may use the Kepler MD5 library.


local OIDs = {
    "1.3.6.1.4.1.11.2.17.19.3.4.0.10",
    "1.3.6.1.4.1.11.2.17.5.2.0.79",
    "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
    "1.3.6.1.4.1.11150.3.4.0.1",
    "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
    "1.3.6.1.4.1.11150.3.4.0"
}

function compare (a, b)
    local aList, bList, Na, Nb = {}, {}
    for num in a:gmatch("%d+") do table.insert(aList, num) end
    for num in b:gmatch("%d+") do table.insert(bList, num) end
    for i = 1, math.max(#aList, #bList) do
        Na, Nb = tonumber(aList[i]) or 0, tonumber(bList[i]) or 0
        if Na ~= Nb then return Na < Nb end
    end
end

table.sort(OIDs, compare)
for _, oid in pairs(OIDs) do print(oid) end

sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots. The sorting is done using a custom compare function with the in-built table.sort.


Library: LuaSocket
socket = require "socket"
host, port = "127.0.0.1", 256

sid = socket.udp()
sid:sendto( "hello socket world", host, port )
sid:close()

opens a socket to localhost on port 256, sends the message "hello socket world", and then closes the socket.


-- load the smtp support
local smtp = require("socket.smtp")

-- Connects to server "localhost" and sends a message to users
-- "fulano@example.com",  "beltrano@example.com",
-- and "sicrano@example.com".
-- Note that "fulano" is the primary recipient, "beltrano" receives a
-- carbon copy and neither of them knows that "sicrano" received a blind
-- carbon copy of the message.
from = "<luasocket@example.com>"

rcpt = {
  "<fulano@example.com>",
  "<beltrano@example.com>",
  "<sicrano@example.com>"
}

mesgt = {
  headers = {
    to = "Fulano da Silva <fulano@example.com>",
    cc = '"Beltrano F. Nunes" <beltrano@example.com>',
    subject = "My first message"
  },
  body = "I hope this works. If it does, I can send you another 1000 copies."
}

r, e = smtp.send{
  from = from,
  rcpt = rcpt,
  source = smtp.message(mesgt)
}

implement a function to send an email using LuaSocket's SMTP module. The function includes parameters for setting From, To, Cc addresses, Subject, and message text, with optional fields for server name and login details. The code may also provide notifications for success or issues. The solution is portable across multiple operating systems.


for l=1,2147483647 do
  print(string.format("%o",l))
end

generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.


x, y = y, x                -- swap the values inside x and y
t[1], t[2] = t[2], t[1]    -- swap the first and second values inside table t

x, y = 3, 4
print(x, y)                --> 3 4
x, y = y, x                -- swap
print(x, y)                --> 4 3

implement a generic swap function or operator that exchanges the values of two variables, regardless of their types. The function handles the constraints of statically typed languages and dynamically typed languages, and also manages issues related to parametric polymorphism. It doesn't necessarily support swapping of incompatible types like string and integer. The function also considers the evaluation behavior of languages like Lua.


function ispalindrome(s) return s == string.reverse(s) end

implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.


"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system."


function F (n, x, y)
    if n == 0 then
        return x + y
    elseif y == 0 then
        return x
    else
        return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y)
    end
end

local testCases = {
    {0, 0, 0},
    {1, 1, 1},
    {1, 3, 3},
    {2, 1, 1},
    {2, 2, 1},
    {3, 1, 1}
}

for _, v in pairs(testCases) do
    io.write("F(" .. table.concat(v, ",") .. ") = ")
    print(F(unpack(v)))
end

Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.


Works with: Julia version 0.6

stack = Int[]           # []
@show push!(stack, 1)   # [1]
@show push!(stack, 2)   # [1, 2]
@show push!(stack, 3)   # [1, 2, 3]
@show pop!(stack)       # 3
@show length(stack)     # 2
@show empty!(stack)     # []
@show isempty(stack)    # true

implement a stack data structure with basic operations such as push (adds an element to the top of the stack), pop (removes and returns the last added element from the stack), and empty (checks if the stack is empty). The stack follows a Last In, First Out (LIFO) access policy. The top operation is also supported for accessing the topmost element without modifying the stack.


fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)
function fib(n)
  x,y = (0,1)
  for i = 1:n x,y = (y, x+y) end
  x
end
fib(n) = ([1 1 ; 1 0]^n)[1,2]

generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.


Works with: Julia version 0.6
@show filter(iseven, 1:10)

select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.


julia> s = "abcdefg"
"abcdefg"

julia> n = 3
3

julia> s[n:end]
"cdefg"

julia> m=2
2

julia> s[n:n+m]
"cde"

julia> s[1:end-1]
"abcdef"

julia> s[search(s,'c')]
'c'

julia> s[search(s,'c'):search(s,'c')+m]
"cde"

The code performs various operations on a string such as displaying a substring starting from a specific character position and of a certain length, displaying a substring from a specific character position to the end of the string, displaying the whole string minus the last character, and displaying a substring starting from a known character or substring within the string. The code is designed to work with any valid Unicode code point, referencing logical characters rather than 8-bit or 16-bit code units. The string type is inferred from its elements and can be interpreted as an UTF8 string with logical access to its argument using the CharString declaration.


julia> reverse("hey")
"yeh"

julia> join(reverse(collect(graphemes("as⃝df̅"))))
"f̅ds⃝a"

The code reverses a given string, for instance, "asdf" is transformed to "fdsa". It also preserves Unicode combining characters during the reversal. For example, "as⃝df̅" is reversed to "f̅ds⃝a". The code primarily reverses codepoints, suitable for string reversal applications in external C libraries. However, from Julia 0.4, it also offers the option to reverse graphemes for reversing "visual order" including combining characters.


function playfair(key, txt, isencode=true, from = "J", to = "")
    to = (to == "" && from == "J") ? "I" : to

    function canonical(s, dup_toX=true)
        s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "")
        a, dupcount = [c for c in s], 0
        for i in 1:2:length(a)-1
            if s[i] == s[i + 1]
                dup_toX && splice!(a, i+1+dupcount:i+dupcount, 'X')
                dupcount += 1
            end
        end
        s = String(a)
        return isodd(length(s)) ? s * "X" : s
    end

    # Translate key into an encoding 5x5 translation matrix.
    keyletters = unique([c for c in canonical(key * "ABCDEFGHIJKLMNOPQRSTUVWXYZ", false)])
    m = Char.((reshape(UInt8.(keyletters[1:25]), 5, 5)'))

    # encod is a dictionary of letter pairs for encoding.
    encod = Dict()

    # Map pairs in same row or same column of matrix m.
    for i in 1:5, j in 1:5, k in 1:5
        if j != k
            encod[m[i, j] * m[i, k]] = m[i, mod1(j + 1, 5)] * m[i, mod1(k + 1, 5)]
        end
        if i != k
            encod[m[i, j] * m[k, j]] = m[mod1(i + 1, 5), j] * m[mod1(k + 1, 5), j]
        end
        # Map pairs not on same row or same column.
        for l in 1:5
            if i != k && j != l
                encod[m[i, j] * m[k, l]] = m[i, l] * m[k, j]
            end
        end
    end

    # Get array of pairs of letters from text.
    canontxt = canonical(txt)
    letterpairs = [canontxt[i:i+1] for i in 1:2:length(canontxt)-1]

    if isencode
        # Encode text
        return join([encod[pair] for pair in letterpairs], " ")
    else
        # Decode text
        decod = Dict((v, k) for (k, v) in encod)
        return join([decod[pair] for pair in letterpairs], " ")
    end
end

orig = "Hide the gold in...the TREESTUMP!!!"
println("Original: ", orig)

encoded = playfair("Playfair example", orig)
println("Encoded: ", encoded)

println("Decoded: ", playfair("Playfair example", encoded, false))

Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.


Works with: Julia version 1.8
using Printf

struct Digraph{T <: Real,U}
    edges::Dict{Tuple{U,U},T}
    verts::Set{U}
end

function Digraph(edges::Vector{Tuple{U,U,T}}) where {T <: Real,U}
    vnames = Set{U}(v for edge in edges for v in edge[1:2])
    adjmat = Dict((edge[1], edge[2]) => edge[3] for edge in edges)
    return Digraph(adjmat, vnames)
end

vertices(g::Digraph) = g.verts
edges(g::Digraph)    = g.edges

neighbours(g::Digraph, v) = Set((b, c) for ((a, b), c) in edges(g) if a == v)

function dijkstrapath(g::Digraph{T,U}, source::U, dest::U) where {T, U}
    @assert source ∈ vertices(g) "$source is not a vertex in the graph"

    # Easy case
    if source == dest return [source], 0 end
    # Initialize variables
    inf  = typemax(T)
    dist = Dict(v => inf for v in vertices(g))
    prev = Dict(v => v   for v in vertices(g))
    dist[source] = 0
    Q = copy(vertices(g))
    neigh = Dict(v => neighbours(g, v) for v in vertices(g))

    # Main loop
    while !isempty(Q)
        u = reduce((x, y) -> dist[x] < dist[y] ? x : y, Q)
        pop!(Q, u)
        if dist[u] == inf || u == dest break end
        for (v, cost) in neigh[u]
            alt = dist[u] + cost
            if alt < dist[v]
                dist[v] = alt
                prev[v] = u
            end
        end
    end

    # Return path
    rst, cost = U[], dist[dest]
    if prev[dest] == dest
        return rst, cost
    else
        while dest != source
            pushfirst!(rst, dest)
            dest = prev[dest]
        end
        pushfirst!(rst, dest)
        return rst, cost
    end
end

# testgraph = [("a", "b", 1), ("b", "e", 2), ("a", "e", 4)]
const testgraph = [("a", "b", 7),  ("a", "c", 9),  ("a", "f", 14), ("b", "c", 10),
             ("b", "d", 15), ("c", "d", 11), ("c", "f", 2),  ("d", "e", 6),
             ("e", "f", 9)]

function testpaths()
    g = Digraph(testgraph)
    src, dst = "a", "e"
    path, cost = dijkstrapath(g, src, dst)
    println("Shortest path from $src to $dst: ", isempty(path) ?
       "no possible path" : join(path, " → "), " (cost $cost)")
    # Print all possible paths
    @printf("\n%4s | %3s | %s\n", "src", "dst", "path")
    @printf("----------------\n")
    for src in vertices(g), dst in vertices(g)
        path, cost = dijkstrapath(g, src, dst)
        @printf("%4s | %3s | %s\n", src, dst, isempty(path) ? "no possible path" : join(path, " → ") * " ($cost)")
    end
end

testpaths()

Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.