{"title": "100 doors", "language": "Lua", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "local is_open = {}\n\nfor pass = 1,100 do\n for door = pass,100,pass do\n is_open[door] = not is_open[door]\n end\nend\n\nfor i,v in next,is_open do\n print ('Door '..i..':',v and 'open' or 'close')\nend"} {"title": "100 prisoners", "language": "Lua from lang", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "function shuffle(tbl)\n for i = #tbl, 2, -1 do\n local j = math.random(i)\n tbl[i], tbl[j] = tbl[j], tbl[i]\n end\n return tbl\nend\n\nfunction playOptimal()\n local secrets = {}\n for i=1,100 do\n secrets[i] = i\n end\n shuffle(secrets)\n\n for p=1,100 do\n local success = false\n\n local choice = p\n for i=1,50 do\n if secrets[choice] == p then\n success = true\n break\n end\n choice = secrets[choice]\n end\n\n if not success then\n return false\n end\n end\n\n return true\nend\n\nfunction playRandom()\n local secrets = {}\n for i=1,100 do\n secrets[i] = i\n end\n shuffle(secrets)\n\n for p=1,100 do\n local choices = {}\n for i=1,100 do\n choices[i] = i\n end\n shuffle(choices)\n\n local success = false\n for i=1,50 do\n if choices[i] == p then\n success = true\n break\n end\n end\n\n if not success then\n return false\n end\n end\n\n return true\nend\n\nfunction exec(n,play)\n local success = 0\n for i=1,n do\n if play() then\n success = success + 1\n end\n end\n return 100.0 * success / n\nend\n\nfunction main()\n local N = 1000000\n print(\"# of executions: \"..N)\n print(string.format(\"Optimal play success rate: %f\", exec(N, playOptimal)))\n print(string.format(\"Random play success rate: %f\", exec(N, playRandom)))\nend\n\nmain()"} {"title": "15 puzzle game", "language": "Lua", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "math.randomseed( os.time() )\nlocal puz = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 }\nlocal dir = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }\nlocal sx, sy = 4, 4 \n\nfunction isValid( tx, ty )\n return tx > 0 and tx < 5 and ty > 0 and ty < 5 \nend\nfunction display()\n io.write( \"\\n\\n\" )\n for j = 1, 4 do\n io.write( \"+----+----+----+----+\\n\" )\n for i = 1, 4 do\n local d = puz[i + j * 4 - 4]\n io.write( \": \" )\n if d < 10 then io.write( \" \" ) end\n if d < 1 then\n io.write( \" \" )\n else\n io.write( string.format( \"%d \", d ) )\n end\n end\n io.write( \":\\n\" )\n end\n io.write( \"+----+----+----+----+\\n\\n\" )\nend\nfunction getUserNove()\n local moves, r, tx, ty = {}\n for d = 1, 4 do\n tx = sx; ty = sy\n tx = tx + dir[d][1]; ty = ty + dir[d][2]\n \n if isValid( tx, ty ) then \n table.insert( moves, puz[tx + ty * 4 - 4] )\n end\n end\n \n io.write( \"Your possible moves are: \" )\n for i = 1, #moves do \n io.write( string.format( \"%d \", moves[i] ) )\n end\n \n io.write ( \"\\nYour move: \" ); r = tonumber( io.read() )\n if r ~= nil then\n for i = 1, #moves do\n if moves[i] == r then return r end\n end\n end\n print( \"Invalid move!\" )\n return -1\nend\nfunction checked( r )\n for i = 1, #puz do\n if puz[i] == r then \n puz[i] = 0\n sx = 1 + ( i - 1 ) % 4; sy = math.floor( ( i + 3 ) / 4 )\n elseif puz[i] == 0 then\n puz[i] = r\n end\n end\n for i = 2, #puz - 1 do\n if puz[i - 1] + 1 ~= puz[i] then return false end\n end\n return true\nend\nfunction beginGame()\n local r, d, tx, ty\n while( true ) do\n for i = 1, 100 do\n while( true ) do\n tx = sx; ty = sy; d = math.random( 4 )\n tx = tx + dir[d][1]; ty = ty + dir[d][2]\n if isValid( tx, ty ) then break end\n end\n puz[sx + sy * 4 - 4] = puz[tx + ty * 4 - 4]\n puz[tx + ty * 4 - 4] = 0; sx = tx; sy = ty\n end\n while( true ) do\n display(); r = getUserNove()\n if r > 0 then\n if checked( r ) then\n display()\n io.write( \"\\nDone!\\n\\nPlay again (Y/N)?\" )\n r = io.read()\n if r ~= \"Y\" and r ~= \"y\" then \n return\n else\n break\n end\n end\n end\n end\n end\nend\n-- [ entry point ] --\nbeginGame()\n"} {"title": "21 game", "language": "Lua", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "gamewon = false\nrunning_total = 0\nplayer = 1\nopponent = 2\n\nwhile not gamewon do\n num = 0\n \n if player == 1 then\n opponent = 2\n repeat\n print(\"Enter a number between 1 and 3 (0 to quit):\")\n num = io.read(\"*n\")\n if num == 0 then\n os.exit()\n end\n until (num > 0) and (num <=3)\n end\n \n if player == 2 and not (gamewon) then\n opponent = 1\n if (21 - running_total <= 3) then\n num = 21 - running_total\n else\n num = math.random(1,3)\n end\n print(\"Player 2 picks number \"..num)\n end\n \n running_total = running_total + num\n print(\"Total: \"..running_total)\n \n if running_total == 21 then\n print(\"Player \"..player..\" wins!\")\n gamewon = true\n end\n \n if running_total > 21 then\n print(\"Player \"..player..\" lost...\")\n print(\"Player \"..opponent..\" wins!\")\n gamewon = true\n end\n \n if player == 1 then\n player = 2\n else player = 1 \n end\n\nend\n"} {"title": "24 game", "language": "Lua", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "local function help()\n\tprint [[\n The 24 Game\n\n Given any four digits in the range 1 to 9, which may have repetitions,\n Using just the +, -, *, and / operators; and the possible use of\n brackets, (), show how to make an answer of 24.\n\n An answer of \"q\" will quit the game.\n An answer of \"!\" will generate a new set of four digits.\n\n Note: you cannot form multiple digit numbers from the supplied digits,\n so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n ]]\nend\n\nlocal function generate(n)\n\tresult = {}\n\tfor i=1,n do\n\t\tresult[i] = math.random(1,9)\n\tend\n\treturn result\nend\n\nlocal function check(answer, digits)\n\tlocal adig = {}\n\tlocal ddig = {}\n\tlocal index\n\tlocal lastWasDigit = false\n\tfor i=1,9 do adig[i] = 0 ddig[i] = 0 end\n\tallowed = {['(']=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}\n\tfor i=1,string.len(answer) do\n\t\tif not allowed[string.sub(answer,i,i)] then\n\t\t\treturn false\n\t\tend\n\t\tindex = string.byte(answer,i)-48\n\t\tif index > 0 and index < 10 then\n\t\t\tif lastWasDigit then\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tlastWasDigit = true\n\t\t\tadig[index] = adig[index] + 1\n\t\telse\n\t\t\tlastWasDigit = false\n\t\tend\n\tend\n\tfor i,digit in next,digits do\n\t\tddig[digit] = ddig[digit]+1\n\tend\n\tfor i=1,9 do\n\t\tif adig[i] ~= ddig[i] then\n\t\t\treturn false\n\t\tend\n\tend\n\treturn loadstring('return '..answer)()\nend\n\nlocal function game24()\n\thelp()\n\tmath.randomseed(os.time())\n\tmath.random()\n\tlocal digits = generate(4)\n\tlocal trial = 0\n\tlocal answer = 0\n\tlocal ans = false\n\tio.write 'Your four digits:'\n\tfor i,digit in next,digits do\n\t\tio.write (' ' .. digit)\n\tend\n\tprint()\n\twhile ans ~= 24 do\n\t\ttrial = trial + 1\n\t\tio.write(\"Expression \"..trial..\": \")\n\t\tanswer = io.read()\n\t\tif string.lower(answer) == 'q' then\n\t\t\tbreak\n\t\tend\n\t\tif answer == '!' then\n\t\t\tdigits = generate(4)\n\t\t\tio.write (\"New digits:\")\n\t\t\tfor i,digit in next,digits do\n\t\t\t\tio.write (' ' .. digit)\n\t\t\tend\n\t\t\tprint()\n\t\telse\n\t\t\tans = check(answer,digits)\n\t\t\tif ans == false then\n\t\t\t\tprint ('The input '.. answer ..' was wonky!')\n\t\t\telse\n\t\t\t\tprint (' = '.. ans)\n\t\t\t\tif ans == 24 then\n\t\t\t\t\tprint (\"Thats right!\")\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\ngame24()"} {"title": "24 game/Solve", "language": "Lua", "task": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "local SIZE = #arg[1]\nlocal GOAL = tonumber(arg[2]) or 24\n\nlocal input = {}\nfor v in arg[1]:gmatch(\"%d\") do\n\ttable.insert(input, v)\nend\nassert(#input == SIZE, 'Invalid input')\n\nlocal operations = {'+', '-', '*', '/'}\n\nlocal function BinaryTrees(vert)\n\tif vert == 0 then\n\t\treturn {false}\n\telse\n\t\tlocal buf = {}\n\t\tfor leften = 0, vert - 1 do\n\t\t\tlocal righten = vert - leften - 1\n\t\t\tfor _, left in pairs(BinaryTrees(leften)) do\n\t\t\t\tfor _, right in pairs(BinaryTrees(righten)) do\n\t\t\t\t\ttable.insert(buf, {left, right})\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn buf\n\tend\nend\nlocal trees = BinaryTrees(SIZE-1)\nlocal c, opc, oper, str\nlocal max = math.pow(#operations, SIZE-1)\nlocal function op(a,b)\n\topc = opc + 1\n\tlocal i = math.floor(oper/math.pow(#operations, opc-1))%#operations+1\n\treturn '('.. a .. operations[i] .. b ..')'\nend\n\nlocal function EvalTree(tree)\n\tif tree == false then\n\t\tc = c + 1\n\t\treturn input[c-1]\n\telse\n\t\treturn op(EvalTree(tree[1]), EvalTree(tree[2]))\n\tend\nend\n\nlocal function printResult()\n\tfor _, v in ipairs(trees) do\n\t\tfor i = 0, max do\n\t\t\tc, opc, oper = 1, 0, i\n\t\t\tstr = EvalTree(v)\n\t\t\tloadstring('res='..str)()\n\t\t\tif(res == GOAL) then print(str, '=', res) end\n\t\tend\n\tend\nend\n\nlocal uniq = {}\nlocal function permgen (a, n)\n\tif n == 0 then\n\t\tlocal str = table.concat(a)\n\t\tif not uniq[str] then \n\t\t\tprintResult()\n\t\t\tuniq[str] = true\n\t\tend\n\telse\n\t\tfor i = 1, n do\n\t\t\ta[n], a[i] = a[i], a[n]\n\t\t\tpermgen(a, n - 1)\n\t\t\ta[n], a[i] = a[i], a[n]\n\t\tend\n\tend\nend\n\npermgen(input, SIZE)\n"} {"title": "4-rings or 4-squares puzzle", "language": "Lua from D", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "function valid(unique,needle,haystack)\n if unique then\n for _,value in pairs(haystack) do\n if needle == value then\n return false\n end\n end\n end\n return true\nend\n\nfunction fourSquare(low,high,unique,prnt)\n count = 0\n if prnt then\n print(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\")\n end\n for a=low,high do\n for b=low,high do\n if valid(unique, a, {b}) then\n fp = a + b\n for c=low,high do\n if valid(unique, c, {a, b}) then\n for d=low,high do\n if valid(unique, d, {a, b, c}) and fp == b + c + d then\n for e=low,high do\n if valid(unique, e, {a, b, c, d}) then\n for f=low,high do\n if valid(unique, f, {a, b, c, d, e}) and fp == d + e + f then\n for g=low,high do\n if valid(unique, g, {a, b, c, d, e, f}) and fp == f + g then\n count = count + 1\n if prnt then\n print(a, b, c, d, e, f, g)\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n end\n if unique then\n print(string.format(\"There are %d unique solutions in [%d, %d]\", count, low, high))\n else\n print(string.format(\"There are %d non-unique solutions in [%d, %d]\", count, low, high))\n end\nend\n\nfourSquare(1,7,true,true)\nfourSquare(3,9,true,true)\nfourSquare(0,9,false,false)"} {"title": "99 bottles of beer", "language": "Lua", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "local bottles = 99\n\nlocal function plural (bottles) if bottles == 1 then return '' end return 's' end\nwhile bottles > 0 do\n print (bottles..' bottle'..plural(bottles)..' of beer on the wall')\n print (bottles..' bottle'..plural(bottles)..' of beer')\n print ('Take one down, pass it around')\n bottles = bottles - 1\n print (bottles..' bottle'..plural(bottles)..' of beer on the wall')\n print ()\nend"} {"title": "9 billion names of God the integer", "language": "Lua", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "function nog(n)\n local tri = {{1}}\n for r = 2, n do\n tri[r] = {}\n for c = 1, r do\n tri[r][c] = (tri[r-1][c-1] or 0) + (tri[r-c] and tri[r-c][c] or 0)\n end\n end\n return tri\nend\n\nfunction G(n)\n local tri, sum = nog(n), 0\n for _, v in ipairs(tri[n]) do sum = sum + v end\n return sum\nend\n\ntri = nog(25)\nfor i, row in ipairs(tri) do\n print(i .. \": \" .. table.concat(row, \" \"))\nend\nprint(\"G(23) = \" .. G(23))\nprint(\"G(123) = \" .. G(123))"} {"title": "ABC problem", "language": "Lua", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "blocks = {\n\t{\"B\",\"O\"};\t{\"X\",\"K\"};\t{\"D\",\"Q\"};\t{\"C\",\"P\"};\n\t{\"N\",\"A\"};\t{\"G\",\"T\"};\t{\"R\",\"E\"};\t{\"T\",\"G\"};\n\t{\"Q\",\"D\"};\t{\"F\",\"S\"};\t{\"J\",\"W\"};\t{\"H\",\"U\"};\n\t{\"V\",\"I\"};\t{\"A\",\"N\"};\t{\"O\",\"B\"};\t{\"E\",\"R\"};\n\t{\"F\",\"S\"};\t{\"L\",\"Y\"};\t{\"P\",\"C\"};\t{\"Z\",\"M\"};\n\t};\n\nfunction canUse(table, letter)\n\tfor i,v in pairs(blocks) do\n\t\tif (v[1] == letter:upper() or v[2] == letter:upper()) and table[i] then\n\t\t\ttable[i] = false;\n\t\t\treturn true;\n\t\tend\n\tend\n\treturn false;\nend\n\nfunction canMake(Word)\n\tlocal Taken = {};\n\tfor i,v in pairs(blocks) do\n\t\ttable.insert(Taken,true);\n\tend\n\tlocal found = true;\n\tfor i = 1,#Word do\n\t\tif not canUse(Taken,Word:sub(i,i)) then\n\t\t\tfound = false;\n\t\tend\n\tend\n\tprint(found)\nend"} {"title": "ASCII art diagram converter", "language": "Lua", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "local function validate(diagram)\n local lines = {}\n for s in diagram:gmatch(\"[^\\r\\n]+\") do\n s = s:match(\"^%s*(.-)%s*$\")\n if s~=\"\" then lines[#lines+1]=s end\n end\n -- \"a little of validation\"..\"for brevity\"\n assert(#lines>0, \"FAIL: no non-empty lines\")\n assert(#lines%2==1, \"FAIL: even number of lines\")\n return lines\nend\n\nlocal function parse(lines)\n local schema, offset = {}, 0\n for i = 2,#lines,2 do\n for part in lines[i]:gmatch(\"\\|([^\\|]+)\") do\n schema[#schema+1] = { name=part:match(\"^%s*(.-)%s*$\"), numbits=(#part+1)/3, offset=offset }\n offset = offset + (#part+1)/3\n end\n end\n return schema\nend\n\nlocal diagram = [[\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ID | \n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| QDCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n| ANCOUNT | \n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| NSCOUNT |\n\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ \n\n]] -- extra whitespace added for testing\n\nlocal schema = parse(validate(diagram))\nprint(\"NAME NUMBITS OFFSET\")\nprint(\"-------- -------- --------\")\nfor i = 1,#schema do\n local item = schema[i]\n print(string.format(\"%-8s %8d %8d\", item.name, item.numbits, item.offset))\nend"} {"title": "AVL tree", "language": "Lua", "task": "{{wikipedia|AVL tree}}\n\n\n\nIn computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\n\n;Task:\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\n;Related task\n[[Red_black_tree_sort]]\n\n", "solution": "AVL={balance=0}\nAVL.__mt={__index = AVL}\n\n\nfunction AVL:new(list)\n local o={} \n setmetatable(o, AVL.__mt)\n for _,v in ipairs(list or {}) do\n o=o:insert(v)\n end\n return o\nend\n \nfunction AVL:rebalance()\n local rotated=false\n if self.balance>1 then\n if self.right.balance<0 then\n self.right, self.right.left.right, self.right.left = self.right.left, self.right, self.right.left.right\n self.right.right.balance=self.right.balance>-1 and 0 or 1\n self.right.balance=self.right.balance>0 and 2 or 1\n end\n self, self.right.left, self.right = self.right, self, self.right.left\n self.left.balance=1-self.balance\n self.balance=self.balance==0 and -1 or 0\n rotated=true\n elseif self.balance<-1 then\n if self.left.balance>0 then\n self.left, self.left.right.left, self.left.right = self.left.right, self.left, self.left.right.left\n self.left.left.balance=self.left.balance<1 and 0 or -1\n self.left.balance=self.left.balance<0 and -2 or -1\n end\n self, self.left.right, self.left = self.left, self, self.left.right\n self.right.balance=-1-self.balance\n self.balance=self.balance==0 and 1 or 0\n rotated=true\n end\n return self,rotated\nend\n\nfunction AVL:insert(v)\n if not self.value then \n self.value=v\n self.balance=0\n return self,1\n end\n local grow\n if v==self.value then\n return self,0\n elseif v0 then\n self.right,grow,v=self.right:delete_move(\"left\",\"right\",-1)\n elseif self.left then\n self.left,grow,v=self.left:delete_move(\"right\",\"left\",1)\n grow=-grow\n else\n return not isSubtree and AVL:new(),-1\n end\n self.value=v\n self.balance=self.balance+grow\n elseif vself.value and self.right then\n self.right,grow=self.right:delete(v,true)\n self.balance=self.balance+grow\n else\n return self,0\n end\n self,rotated=self:rebalance()\n return self, grow~=0 and (rotated or self.balance==0) and -1 or 0\nend\n\n-- output functions\n\nfunction AVL:toList(list)\n if not self.value then return {} end\n list=list or {}\n if self.left then self.left:toList(list) end\n list[#list+1]=self.value\n if self.right then self.right:toList(list) end\n return list\nend\n\nfunction AVL:dump(depth)\n if not self.value then return end\n depth=depth or 0\n if self.right then self.right:dump(depth+1) end\n print(string.rep(\" \",depth)..self.value..\" (\"..self.balance..\")\")\n if self.left then self.left:dump(depth+1) end\nend\n\n-- test\n\nlocal test=AVL:new{1,10,5,15,20,3,5,14,7,13,2,8,3,4,5,10,9,8,7}\n\ntest:dump()\nprint(\"\\ninsert 17:\")\ntest=test:insert(17)\ntest:dump()\nprint(\"\\ndelete 10:\")\ntest=test:delete(10)\ntest:dump()\nprint(\"\\nlist:\")\nprint(unpack(test:toList()))\n"} {"title": "Abbreviations, automatic", "language": "Lua", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mercores Joves Venres Sabado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "function split(line)\n local wa = {}\n for i in string.gmatch(line, \"%S+\") do\n table.insert(wa, i)\n end\n return wa\nend\n\n-- main\nlocal file = assert(io.open(\"days_of_week.txt\", \"r\"))\nio.input(file)\n\nlocal line_num = 0\nwhile true do\n local line = io.read()\n if line == nil then break end\n line_num = line_num + 1\n\n if string.len(line) > 0 then\n local days = split(line)\n if #days ~= 7 then\n error(\"There aren't 7 days in line \"..line_num)\n end\n\n local temp = {}\n for i,day in pairs(days) do\n if temp[day] ~= nil then\n io.stderr:write(\" \u221e \"..line..\"\\n\")\n else\n temp[day] = true\n end\n end\n\n local length = 1\n while length < 50 do\n temp = {}\n local count = 0\n for i,day in pairs(days) do\n local key = string.sub(day, 0, length)\n if temp[key] ~= nil then break end\n temp[key] = true\n count = count + 1\n end\n if count == 7 then\n print(string.format(\"%2d %s\", length, line))\n break\n end\n length = length + 1\n end\n end\nend"} {"title": "Abbreviations, easy", "language": "Lua", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "#!/usr/bin/lua\n\nlocal list1 = [[\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst\n COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate\n Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp\n FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN\n LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge\n MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query\n QUIT READ RECover REFRESH RENum REPeat Replace CReplace\n RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT\n SOS STAck STATus TOP TRAnsfer Type Up ]]\n\n\nlocal indata1 = [[riG rePEAT copies put mo rest types\n fup. 6 poweRin]]\n\nlocal indata2 = [[ALT aLt ALTE ALTER AL ALF ALTERS TER A]]\nlocal indata3 = [[o ov oVe over overL overla]]\n\nlocal function split(text)\n local result = {}\n for w in string.gmatch(text, \"%g+\") do\n result[#result+1]=w\n -- print(#result,w,#w)\n end\n return result\nend\n\n\nlocal function print_line( t )\n for i = 1,#t do\n io.write( string.format(\"%s \", t[i] ) )\n end\n print()\nend\n\n\nlocal function is_valid(cmd,abbrev)\n --print(abbrev,cmd,\"##\")\n \n local sm = string.match( cmd:lower(), abbrev:lower() )\n if sm == nil then return -1 end\n\n -- test if any lowercase in \"cmd\"\n if false then do -- NOTE!: requirement spec error .. put not equal PUT\n\t local lowcase = string.match(cmd,\"%l+\")\n\t if lowcase == nil then return -2 end\n\t if #lowcase < 1 then return -3 end\n\t\t end\n end\n \n -- test if abbrev is too long\n if #abbrev > #cmd then return -4 end\n\n --- num caps in \"cmd\" is minimum length of abbrev\n local caps = string.match(cmd,\"%u+\")\n if #abbrev < #caps then return -5 end\n\n local s1 = abbrev:sub(1,#caps)\n local s2 = cmd:sub(1,#caps)\n if s1:lower() ~= s2:lower() then return -6 end\n\n return 1\nend\n\nlocal function start()\n local t1 = {}\n local t2 = {}\n local result = {}\n t1 = split(list1)\n t2 = split(indata1)\n print_line(t2);\n\n for i = 1,#t2 do\n good = 0\n for j = 1,#t1 do\n\t local abbrev = t2[i]\n\t local cmd = t1[j]\n\t good = is_valid(cmd,abbrev)\n\t if good==1 then do\n\t result[#result+1] = t1[j]:upper()\n\t break end\n\t end --if\n end --for j\n if good < 1 then result[#result+1] = \"*error*\" end\n end --for i\n print_line(result)\nend\n\nstart() -- run the program\n"} {"title": "Abbreviations, simple", "language": "Lua", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "abbr = {\n define = function(self, cmdstr)\n local cmd\n self.hash = {}\n for word in cmdstr:upper():gmatch(\"%S+\") do\n if cmd then\n local n = tonumber(word)\n for len = n or #cmd, #cmd do\n self.hash[cmd:sub(1,len)] = cmd\n end\n cmd = n==nil and word or nil\n else\n cmd = word\n end\n end\n end,\n expand = function(self, input)\n local output = {}\n for word in input:upper():gmatch(\"%S+\") do\n table.insert(output, self.hash[word] or \"*error*\")\n end\n return table.concat(output, \" \")\n end\n}\nabbr:define[[\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n]]\nlocal input = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\nprint(\"Input:\", input)\nprint(\"Output:\", abbr:expand(input))"} {"title": "Abelian sandpile model", "language": "Lua", "task": "{{wikipedia|Abelian sandpile model}}\nImplement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article.\n\nThe task requires the creation of a 2D grid of arbitrary size on which \"piles of sand\" can be placed. Any \"pile\" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.'''\n\nIt is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.\nExamples up to 2^30, wow!\njavascript running on web\n'''Examples:'''\n\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 4 0 0 -> 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n", "solution": "local sandpile = {\n init = function(self, dim, val)\n self.cell, self.dim = {}, dim\n for r = 1, dim do\n self.cell[r] = {}\n for c = 1, dim do\n self.cell[r][c] = 0\n end\n end\n self.cell[math.floor(dim/2)+1][math.floor(dim/2)+1] = val\n end,\n iter = function(self)\n local dim, cel, more = self.dim, self.cell\n repeat\n more = false\n for r = 1, dim do\n for c = 1, dim do\n if cel[r][c] >= 4 then\n cel[r][c] = cel[r][c] - 4\n if c > 1 then cel[r][c-1], more = cel[r][c-1]+1, more or cel[r][c-1]>=3 end\n if c < dim then cel[r][c+1], more = cel[r][c+1]+1, more or cel[r][c+1]>=3 end\n if r > 1 then cel[r-1][c], more = cel[r-1][c]+1, more or cel[r-1][c]>=3 end\n if r < dim then cel[r+1][c], more = cel[r+1][c]+1, more or cel[r+1][c]>=3 end\n end\n more = more or cel[r][c] >= 4\n end\n end\n until not more\n end,\n draw = function(self)\n for r = 1, self.dim do\n print(table.concat(self.cell[r],\" \"))\n end\n end,\n}\nsandpile:init(15, 256)\nsandpile:iter()\nsandpile:draw()"} {"title": "Abelian sandpile model/Identity", "language": "Lua", "task": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that \ncontain a number from 0 to 3 inclusive. (The numbers are said to represent \ngrains of sand in each area of the sandpile).\n\nE.g. s1 =\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n\nand s2 =\n\n 2 1 3\n 1 0 1\n 0 1 0\n \n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then \nthose areas cause the whole sandpile to become \"unstable\" and the sandpile \nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of \nsand to each of its four horizontal or vertical neighbours. Grains are lost \nat the edge of the grid, but otherwise increase the number in neighbouring \ncells by one, whilst decreasing the count in the toppled cell by four in each \ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n\nThe final result is the stable sandpile on the right. \n\n'''Note:''' The order in which cells are toppled does not affect the final result.\n\n;Task:\n* Create a class or datastructure and functions to represent and operate on sandpiles. \n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:\n\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n\n* Show that s3 + s3_id == s3\n* Show that s3_id + s3_id == s3_id\n\n\nShow confirming output here, with your examples.\n\n\n;References:\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian_sandpile_model\n\n", "solution": "sandpile.__index = sandpile\nsandpile.new = function(self, vals)\n local inst = setmetatable({},sandpile)\n inst.cell, inst.dim = {}, #vals\n for r = 1, inst.dim do\n inst.cell[r] = {}\n for c = 1, inst.dim do\n inst.cell[r][c] = vals[r][c]\n end\n end\n return inst\nend\nsandpile.add = function(self, other)\n local vals = {}\n for r = 1, self.dim do\n vals[r] = {}\n for c = 1, self.dim do\n vals[r][c] = self.cell[r][c] + other.cell[r][c]\n end\n end\n local inst = sandpile:new(vals)\n inst:iter()\n return inst\nend\n\nlocal s1 = sandpile:new{{1,2,0},{2,1,1},{0,1,3}}\nlocal s2 = sandpile:new{{2,1,3},{1,0,1},{0,1,0}}\nprint(\"s1 =\") s1:draw()\nprint(\"\\ns2 =\") s2:draw()\nlocal s1ps2 = s1:add(s2)\nprint(\"\\ns1 + s2 =\") s1ps2:draw()\nlocal s2ps1 = s2:add(s1)\nprint(\"\\ns2 + s1 =\") s2ps1:draw()\nlocal topple = sandpile:new{{4,3,3},{3,1,2},{0,2,3}}\nprint(\"\\ntopple, before =\") topple:draw()\ntopple:iter()\nprint(\"\\ntopple, after =\") topple:draw()\nlocal s3 = sandpile:new{{3,3,3},{3,3,3},{3,3,3}}\nprint(\"\\ns3 =\") s3:draw()\nlocal s3_id = sandpile:new{{2,1,2},{1,0,1},{2,1,2}}\nprint(\"\\ns3_id =\") s3_id:draw()\nlocal s3ps3_id = s3:add(s3_id)\nprint(\"\\ns3 + s3_id =\") s3ps3_id:draw()\nlocal s3_idps3_id = s3_id:add(s3_id)\nprint(\"\\ns3_id + s3_id =\") s3_idps3_id:draw()"} {"title": "Abundant odd numbers", "language": "Lua", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "-- Return the sum of the proper divisors of x\nfunction sumDivs (x)\n local sum, sqr = 1, math.sqrt(x)\n for d = 2, sqr do\n if x % d == 0 then\n sum = sum + d\n if d ~= sqr then sum = sum + (x/d) end\n end\n end\n return sum\nend\n\n-- Return a table of odd abundant numbers\nfunction oddAbundants (mode, limit)\n local n, count, divlist, divsum = 1, 0, {}\n repeat\n n = n + 2\n divsum = sumDivs(n)\n if divsum > n then\n table.insert(divlist, {n, divsum})\n count = count + 1\n if mode == \"Above\" and n > limit then return divlist[#divlist] end\n end\n until count == limit\n if mode == \"First\" then return divlist end\n if mode == \"Nth\" then return divlist[#divlist] end\nend\n\n-- Write a result to stdout\nfunction showResult (msg, t)\n print(msg .. \": the proper divisors of \" .. t[1] .. \" sum to \" .. t[2])\nend\n\n-- Main procedure\nfor k, v in pairs(oddAbundants(\"First\", 25)) do showResult(k, v) end\nshowResult(\"1000\", oddAbundants(\"Nth\", 1000))\nshowResult(\"Above 1e6\", oddAbundants(\"Above\", 1e6))"} {"title": "Accumulator factory", "language": "Lua", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "function acc(init)\n init = init or 0\n return function(delta)\n init = init + (delta or 0)\n return init\n end\nend"} {"title": "Accumulator factory", "language": "Lua 5.1", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "do\n local accSum = 0; -- accumulator factory 'upvalue'\n function acc(v) -- the accumulator factory\n accSum = accSum + (v or 0) -- increment factory sum\n \n local closuredSum = accSum; -- new 'upvalue' at each factory call\n return function (w) -- the produced accumulator function\n closuredSum = closuredSum + (w or 0) -- increment product 'upvalue'\n return closuredSum -- return 'upvalue'\n end, accSum -- end of product closure\n \n end--acc\nend--end of factory closure"} {"title": "Amb", "language": "Lua", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "print(\"Per task requirements:\")\nw1 = Amb('the','that','a')\nw2 = Amb('frog','elephant','thing')\nw3 = Amb('walked','treaded','grows')\nw4 = Amb('slowly','quickly')\nfunction rule(t) local a,b,c,d = unpack(t) return a:byte(#a)==b:byte(1) and b:byte(#b)==c:byte(1) and c:byte(#c)==d:byte(1) end\nanswers = Amb(rule, w1, w2, w3, w4)\nanswers:map(function(t) return t:concat(\" \") end):each(print)\n\nprint()\n\nprint(\"Modified task, seek equal length of words:\")\nw1 = Amb('the','that','a','which')\nw2 = Amb('red','green','blue','yellow')\nw3 = Amb('frog','elephant','cow','thing')\nw4 = Amb('walked','treaded','grew','shrunk')\nw5 = Amb('slow','quick','moderately')\nfunction rule(t) local a,b,c,d,e = unpack(t) return #a==#b and #b==#c and #c==#d and #d==#e end\nanswers = Amb(rule, w1, w2, w3, w4, w5)\nanswers:map(function(t) return t:concat(\" \") end):each(print)\n\nprint()\n\nprint(\"Modified example, seek product of 12:\")\nx = Amb(1,2,3)\ny = Amb(4,5,6)\nfunction rule(t) local x,y = unpack(t) return x*y==12 end\nanswers = Amb(rule, x, y)\nanswers:map(function(t) return t:concat(\" \") end):each(print)\n\nprint()\n\nprint(\"Pythagorean triples:\")\nx = Amb(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)\ny = Amb(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)\nz = Amb(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)\nfunction rule(t) local x,y,z = unpack(t) return x^2 + y^2 == z^2 end\nanswers = Amb(rule, x, y, z)\nanswers:map(function(t) return t:concat(\" \") end):each(print)\n\nprint()\n\nprint(\"When there is no solution:\")\nx = Amb(1,2,3)\ny = Amb(4,5,6)\nfunction rule(t) local x,y = unpack(t) return x*y==7 end\nanswers = Amb(rule, x, y, z)\nprint(\"#answers = \" .. #answers)\n\nprint()\n\nprint(\"send + more = money:\")\n-- intuitive simplification applied: m must be 1 ==> others may not be 1 (reduces complexity from 10^8 to 9^7)\n-- (\"m is allowed to be leading zero\" solutions exist, e.g. 2 8 1 7 0 3 6 5, and this could find them, but why?)\ns = Amb(0,2,3,4,5,6,7,8,9)\ne = Amb(0,2,3,4,5,6,7,8,9)\nn = Amb(0,2,3,4,5,6,7,8,9)\nd = Amb(0,2,3,4,5,6,7,8,9)\nm = Amb(1)\no = Amb(0,2,3,4,5,6,7,8,9)\nr = Amb(0,2,3,4,5,6,7,8,9)\ny = Amb(0,2,3,4,5,6,7,8,9)\nfunction rule(t)\n for i=1,#t do for j=i+1,#t do if t[i]==t[j] then return false end end end\n local s,e,n,d,m,o,r,y = unpack(t)\n return s*1000 + e*100 + 10*n + d + m*1000 + o*100 + r*10 + e == m*10000 + o*1000 + n*100 + e*10 + y\nend\nanswers = Amb(rule, s, e, n, d, m, o, r, y)\nanswers:map(function(t) return t:concat(\" \") end):each(print)"} {"title": "Anagrams/Deranged anagrams", "language": "Lua", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "string.tacnoc = function(str) -- 'inverse' of table.concat\n local arr={}\n for ch in str:gmatch(\".\") do arr[#arr+1]=ch end\n return arr\nend\n\nlocal function deranged(s1, s2)\n if s1==s2 then return false end\n local t1, t2 = s1:tacnoc(), s2:tacnoc()\n for i,v in ipairs(t1) do if t2[i]==v then return false end end\n return true\nend\n\nlocal dict = {}\nlocal f = io.open(\"unixdict.txt\", \"r\")\nfor word in f:lines() do\n local ltrs = word:tacnoc()\n table.sort(ltrs)\n local hash = table.concat(ltrs)\n dict[hash] = dict[hash] or {}\n table.insert(dict[hash], word)\nend\n\nlocal answer = { word=\"\", anag=\"\", len=0 }\nfor _,list in pairs(dict) do\n if #list>1 and #list[1]>answer.len then\n for _,word in ipairs(list) do\n for _,anag in ipairs(list) do\n if deranged(word, anag) then\n answer.word, answer.anag, answer.len = word, anag, #word\n end\n end\n end\n end\nend\nprint(answer.word, answer.anag, answer.len)"} {"title": "Angle difference between two bearings", "language": "Lua", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "bearing = {degrees = 0} -- prototype object\n\nfunction bearing:assign(angle)\n\tangle = tonumber(angle) or 0\n\twhile angle > 180 do\n\t\tangle = angle - 360\n\tend\n\twhile angle < -180 do\n\t\tangle = angle + 360\n\tend\n\tself.degrees = angle\nend\n\nfunction bearing:new(size)\n\tlocal child_object = {}\n\tsetmetatable(child_object, {__index = self})\n\tchild_object:assign(size)\n\treturn child_object\nend\n\nfunction bearing:subtract(other)\n\tlocal difference = self.degrees - other.degrees\n\treturn self:new(difference)\nend\n\nfunction bearing:list(sizes)\n\tlocal bearings = {}\n\tfor index, size in ipairs(sizes) do\n\t\ttable.insert(bearings, self:new(size))\n\tend\n\treturn bearings\nend\n\nfunction bearing:text()\n\treturn string.format(\"%.4f deg\", self.degrees)\nend\n\nfunction main()\n\tlocal subtrahends = bearing:list{\n\t\t20, -45, -85, -95, -45, -45, 29.4803, -78.3251,\n\t\t-70099.74233810938, -165313.6666297357,\n\t\t1174.8380510598456, 60175.77306795546\n\t}\n\tlocal minuends = bearing:list{\n\t\t45, 45, 90, 90, 125, 145, -88.6381, -159.036,\n\t\t29840.67437876723, 33693.9894517456,\n\t\t-154146.66490124757, 42213.07192354373\n\t}\n\tfor index = 1, #minuends do\n\t\tlocal b2, b1 = minuends[index], subtrahends[index]\n\t\tlocal b3 = b2:subtract(b1)\n\t\tlocal statement = string.format(\n\t\t\t\"%s - %s = %s\\n\",\n\t\t\tb2:text(), b1:text(), b3:text()\n\t\t)\n\t\tio.write(statement)\n\tend\nend\n\nmain()"} {"title": "Anti-primes", "language": "Lua", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "-- First 20 antiprimes.\n\nfunction count_factors(number)\n\tlocal count = 0\n\tfor attempt = 1, number do\n\t\tlocal remainder = number % attempt\n\t\tif remainder == 0 then\n\t\t\tcount = count + 1\n\t\tend\n\tend\n\treturn count\nend\n\nfunction antiprimes(goal)\n\tlocal list, number, mostFactors = {}, 1, 0\n\twhile #list < goal do\n\t\tlocal factors = count_factors(number)\n\t\tif factors > mostFactors then\n\t\t\ttable.insert(list, number)\n\t\t\tmostFactors = factors\n\t\tend\n\t\tnumber = number + 1\n\tend\n\treturn list\nend\n\nfunction recite(list)\n\tfor index, item in ipairs(list) do\n\t\tprint(item)\n\tend\nend\n\nprint(\"The first 20 antiprimes:\")\nrecite(antiprimes(20))\nprint(\"Done.\")\n"} {"title": "Apply a digital filter (direct form II transposed)", "language": "Lua from C++", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "function filter(b,a,input)\n local out = {}\n for i=1,table.getn(input) do\n local tmp = 0\n local j = 0\n out[i] = 0\n\n for j=1,table.getn(b) do\n if i - j < 0 then\n --continue\n else\n tmp = tmp + b[j] * input[i - j + 1]\n end\n end\n\n for j=2,table.getn(a) do\n if i - j < 0 then\n --continue\n else\n tmp = tmp - a[j] * out[i - j + 1]\n end\n end\n\n tmp = tmp / a[1]\n out[i] = tmp\n end\n return out\nend\n\nfunction main()\n local sig = {\n -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,-0.662370894973,\n -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172,\n 0.741527555207, 0.277841675195, 0.400833448236,-0.2085993586, -0.172842103641,\n -0.134316096293, 0.0259303398477,0.490105989562, 0.549391221511, 0.9047198589\n }\n\n --Constants for a Butterworth filter (order 3, low pass)\n local a = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}\n local b = {0.16666667, 0.5, 0.5, 0.16666667}\n\n local result = filter(b,a,sig)\n for i=1,table.getn(result) do\n io.write(result[i] .. \", \")\n end\n print()\n\n return nil\nend\n\nmain()"} {"title": "Approximate equality", "language": "Lua from C", "task": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant. \n\nFor example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by \nabout the 8th significant digit in base 10 arithmetic.\n\n\n;Task:\nCreate a function which returns true if two floating point numbers are approximately equal. \n\n\nThe function should allow for differences in the magnitude of numbers, so that, for example, \n'''100000000000000.01''' may be approximately equal to '''100000000000000.011''', \neven though '''100.01''' is not approximately equal to '''100.011'''.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')\n:# 100.01, 100.011 (note: should return ''false'')\n:# 10000000000000.001 / 10000.0, 1000000000.0000001000\n:# 0.001, 0.0010000001\n:# 0.000000000000000000000101, 0.0\n:# sqrt(2) * sqrt(2), 2.0\n:# -sqrt(2) * sqrt(2), -2.0\n:# 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.\n\n\n__TOC__\n\n", "solution": "function approxEquals(value, other, epsilon)\n return math.abs(value - other) < epsilon\nend\n\nfunction test(a, b)\n local epsilon = 1e-18\n print(string.format(\"%f, %f => %s\", a, b, tostring(approxEquals(a, b, epsilon))))\nend\n\nfunction main()\n test(100000000000000.01, 100000000000000.011);\n test(100.01, 100.011)\n test(10000000000000.001 / 10000.0, 1000000000.0000001000)\n test(0.001, 0.0010000001)\n test(0.000000000000000000000101, 0.0)\n test(math.sqrt(2.0) * math.sqrt(2.0), 2.0)\n test(-math.sqrt(2.0) * math.sqrt(2.0), -2.0)\n test(3.14159265358979323846, 3.14159265358979324)\nend\n\nmain()"} {"title": "Arena storage pool", "language": "Lua", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "pool = {} -- create an \"arena\" for the variables a,b,c,d\npool.a = 1 -- individually allocated..\npool.b = \"hello\"\npool.c = true\npool.d = { 1,2,3 }\npool = nil -- release reference allowing garbage collection of entire structure"} {"title": "Arithmetic-geometric mean", "language": "Lua", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "function agm(a, b, tolerance)\n if not tolerance or tolerance < 1e-15 then\n tolerance = 1e-15\n end\n repeat\n a, b = (a + b) / 2, math.sqrt(a * b)\n until math.abs(a-b) < tolerance\n return a\nend\n\nprint(string.format(\"%.15f\", agm(1, 1 / math.sqrt(2))))"} {"title": "Arithmetic evaluation", "language": "Lua", "task": "Create a program which parses and evaluates arithmetic expressions.\n;Requirements:\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input. \n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) \n* The expression will be a string or list of symbols like \"(1+3)*7\". \n* The four symbols + - * / must be supported as binary operators with conventional precedence rules. \n* Precedence-control parentheses must also be supported.\n\n\n;Note:\nFor those who don't remember, mathematical precedence is as follows:\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\n\n;C.f: \n* [[24 game Player]].\n* [[Parsing/RPN calculator algorithm]].\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "require\"lpeg\"\n\nP, R, C, S, V = lpeg.P, lpeg.R, lpeg.C, lpeg.S, lpeg.V\n\n--matches arithmetic expressions and returns a syntax tree\nexpression = P{\"expr\";\nws = P\" \"^0,\nnumber = C(R\"09\"^1) * V\"ws\",\nlp = \"(\" * V\"ws\",\nrp = \")\" * V\"ws\",\nsym = C(S\"+-*/\") * V\"ws\",\nmore = (V\"sym\" * V\"expr\")^0,\nexpr = V\"number\" * V\"more\" + V\"lp\" * lpeg.Ct(V\"expr\" * V\"more\") * V\"rp\" * V\"more\"}\n\n--evaluates a tree\nfunction eval(expr)\n --empty\n if type(expr) == \"string\" or type(expr) == \"number\" then return expr + 0 end\n \n --arithmetic functions\n tb = {[\"+\"] = function(a,b) return eval(a) + eval(b) end,\n\t\t[\"-\"] = function(a,b) return eval(a) - eval(b) end,\n\t\t[\"*\"] = function(a,b) return eval(a) * eval(b) end,\n\t\t[\"/\"] = function(a,b) return eval(a) / eval(b) end}\n \n --you could add ^ or other operators to this pretty easily\n for i, v in ipairs{\"*/\", \"+-\"} do\n for s, u in ipairs(expr) do\n\t local k = type(u) == \"string\" and C(S(v)):match(u)\n\t if k then\n\t expr[s-1] = tb[k](expr[s-1],expr[s+1])\n\t table.remove(expr, s)\n\t table.remove(expr, s)\n\t end\n\tend\n end\n return expr[1]\nend\n\nprint(eval{expression:match(io.read())})"} {"title": "Arithmetic numbers", "language": "Lua", "task": "Definition\nA positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.\n\n;Example\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. \n\n;Task\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.\n\n3. How many of the first '''x''' arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number '''1''' is neither prime nor composite.\n\n;Stretch\nCarry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.\n\n;References\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer\n\n", "solution": "local function factors (n)\n\tlocal f, i = {1, n}, 2\n\twhile true do\n\t\tlocal j = n//i -- floor division by Lua 5.3\n\t\tif j < i then \n\t\t\tbreak\n\t\telseif j == i and i * j == n then \n\t\t\ttable.insert (f, i)\n\t\t\tbreak\n\t\telseif i * j == n then\n\t\t\ttable.insert (f, i)\n\t\t\ttable.insert (f, j)\n\t\tend\n\t\ti = i + 1\n\tend\n\treturn f\nend\n\nlocal function sum (f)\n\tlocal s = 0\n\tfor i, value in ipairs (f) do\n\t\ts = s + value\n\tend\n\treturn s\nend\n\nlocal arithmetic_count = 1\nlocal composite_count = 0\nlocal hundr = {1}\n\nfor n = 2, 1228663 do\n\tlocal f = factors (n)\n\tlocal s = sum (f)\n\tlocal l = #f\n\tif (s/l)%1 == 0 then\n\t\tarithmetic_count = arithmetic_count + 1\n\t\tif l > 2 then\n\t\t\tcomposite_count = composite_count + 1\n\t\tend\n\t\tif arithmetic_count <= 100 then\n\t\t\ttable.insert (hundr, n)\n\t\tend\n\t\tif arithmetic_count == 100 then\n\t\t\tfor i = 0, 9 do\n\t\t\t\tprint (table.concat(hundr, ',\t', 10*i+1, 10*i+10))\n\t\t\tend\n\t\telseif arithmetic_count == 1000 \n\t\t\tor arithmetic_count == 10000 \n\t\t\tor arithmetic_count == 100000 then\n\t\t\tprint (arithmetic_count..'th arithmetic number is '..(n))\n\t\t\tprint ('Number of composite arithmetic numbers <= '..(n)..': '..composite_count)\n\t\telseif arithmetic_count == 1000000 then\n\t\t\tprint (arithmetic_count..'th arithmetic number is '..(n))\n\t\t\tprint ('Number of composite arithmetic numbers <= '..(n)..': '..composite_count)\n\t\t\treturn\n\t\tend\n\tend\nend"} {"title": "Array length", "language": "Lua", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "-- For tables as simple arrays, use the # operator:\nfruits = {\"apple\", \"orange\"}\nprint(#fruits)\n\n-- Note the # symbol does not work for non-integer-indexed tables:\nfruits = {fruit1 = \"apple\", fruit2 = \"orange\"}\nprint(#fruits)\n\n-- For this you can use this short function:\nfunction size (tab)\n local count = 0\n for k, v in pairs(tab) do\n count = count + 1\n end\n return count\nend\n\nprint(size(fruits))"} {"title": "Ascending primes", "language": "Lua", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "local function is_prime(n)\n if n < 2 then return false end\n if n % 2 == 0 then return n==2 end\n if n % 3 == 0 then return n==3 end\n for f = 5, n^0.5, 6 do\n if n%f==0 or n%(f+2)==0 then return false end\n end\n return true\nend\n\nlocal function ascending_primes()\n local digits, candidates, primes = {1,2,3,4,5,6,7,8,9}, {0}, {}\n for i = 1, #digits do\n for j = 1, #candidates do\n local value = candidates[j] * 10 + digits[i]\n if is_prime(value) then primes[#primes+1] = value end\n candidates[#candidates+1] = value\n end\n end\n table.sort(primes)\n return primes\nend\n\nprint(table.concat(ascending_primes(), \", \"))"} {"title": "Associative array/Merging", "language": "Lua", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "base = {name=\"Rocket Skates\", price=12.75, color=\"yellow\"}\nupdate = {price=15.25, color=\"red\", year=1974}\n\n--[[ clone the base data ]]--\nresult = {}\nfor key,val in pairs(base) do\n result[key] = val\nend\n\n--[[ copy in the update data ]]--\nfor key,val in pairs(update) do\n result[key] = val\nend\n\n--[[ print the result ]]--\nfor key,val in pairs(result) do\n print(string.format(\"%s: %s\", key, val))\nend"} {"title": "Attractive numbers", "language": "Lua", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "-- Returns true if x is prime, and false otherwise\nfunction isPrime (x)\n if x < 2 then return false end\n if x < 4 then return true end\n if x % 2 == 0 then return false end\n for d = 3, math.sqrt(x), 2 do\n if x % d == 0 then return false end\n end\n return true\nend\n\n-- Compute the prime factors of n\nfunction factors (n)\n local facList, divisor, count = {}, 1\n if n < 2 then return facList end\n while not isPrime(n) do\n while not isPrime(divisor) do divisor = divisor + 1 end\n count = 0\n while n % divisor == 0 do\n n = n / divisor\n table.insert(facList, divisor)\n end\n divisor = divisor + 1\n if n == 1 then return facList end\n end\n table.insert(facList, n)\n return facList\nend\n\n-- Main procedure\nfor i = 1, 120 do\n if isPrime(#factors(i)) then io.write(i .. \"\\t\") end\nend"} {"title": "Average loop length", "language": "Lua", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "function average(n, reps)\n local count = 0\n for r = 1, reps do\n local f = {}\n for i = 1, n do f[i] = math.random(n) end\n local seen, x = {}, 1\n while not seen[x] do\n seen[x], x, count = true, f[x], count+1\n end\n end\n return count / reps\nend\n\nfunction analytical(n)\n local s, t = 1, 1\n for i = n-1, 1, -1 do t=t*i/n s=s+t end\n return s\nend\n\nprint(\" N average analytical (error)\")\nprint(\"=== ========= ============ =========\")\nfor n = 1, 20 do\n local avg, ana = average(n, 1e6), analytical(n)\n local err = (avg-ana) / ana * 100\n print(string.format(\"%3d %9.4f %12.4f (%6.3f%%)\", n, avg, ana, err))\nend"} {"title": "Averages/Mean angle", "language": "Lua 5.1", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "function meanAngle (angleList)\n local sumSin, sumCos = 0, 0\n for i, angle in pairs(angleList) do\n sumSin = sumSin + math.sin(math.rad(angle))\n sumCos = sumCos + math.cos(math.rad(angle))\n end\n local result = math.deg(math.atan2(sumSin, sumCos))\n return string.format(\"%.2f\", result)\nend\n\nprint(meanAngle({350, 10}))\nprint(meanAngle({90, 180, 270, 360}))\nprint(meanAngle({10, 20, 30}))"} {"title": "Averages/Pythagorean means", "language": "Lua", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "function fsum(f, a, ...) return a and f(a) + fsum(f, ...) or 0 end\nfunction pymean(t, f, finv) return finv(fsum(f, unpack(t)) / #t) end\nnums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\n--arithmetic\na = pymean(nums, function(n) return n end, function(n) return n end)\n--geometric\ng = pymean(nums, math.log, math.exp)\n--harmonic\nh = pymean(nums, function(n) return 1/n end, function(n) return 1/n end)\nprint(a, g, h)\nassert(a >= g and g >= h)"} {"title": "Averages/Root mean square", "language": "Lua", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "function sumsq(a, ...) return a and a^2 + sumsq(...) or 0 end\nfunction rms(t) return (sumsq(unpack(t)) / #t)^.5 end\n\nprint(rms{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"} {"title": "Babbage problem", "language": "Lua from D", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "-- get smallest number <= sqrt(269696)\nk = math.floor(math.sqrt(269696))\n\n-- if root is odd -> make it even\nif k % 2 == 1 then\n k = k - 1\nend\n\n-- cycle through numbers\nwhile not ((k * k) % 1000000 == 269696) do\n k = k + 2\nend\n\nio.write(string.format(\"%d * %d = %d\\n\", k, k, k * k))"} {"title": "Balanced brackets", "language": "Lua", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "function isBalanced(s)\n --Lua pattern matching has a 'balanced' pattern that matches sets of balanced characters.\n --Any two characters can be used.\n return s:gsub('%b[]','')=='' and true or false\nend\n\nfunction randomString()\n math.randomseed(os.time())\n math.random()math.random()math.random()math.random()\n local tokens={'[',']'}\n local result={}\n for i=1,8 do\n table.insert(result,tokens[math.random(1,2)])\n end\n return table.concat(result)\nend\n\nlocal RS=randomString()\nprint(RS)\nprint(isBalanced(RS))\n"} {"title": "Balanced ternary", "language": "Lua from C", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "function to_bt(n)\n local d = { '0', '+', '-' }\n local v = { 0, 1, -1 }\n\n local b = \"\"\n\n while n ~= 0 do\n local r = n % 3\n if r < 0 then\n r = r + 3\n end\n\n b = b .. d[r + 1]\n\n n = n - v[r + 1]\n n = math.floor(n / 3)\n end\n\n return b:reverse()\nend\n\nfunction from_bt(s)\n local n = 0\n\n for i=1,s:len() do\n local c = s:sub(i,i)\n n = n * 3\n if c == '+' then\n n = n + 1\n elseif c == '-' then\n n = n - 1\n end\n end\n\n return n\nend\n\nfunction last_char(s)\n return s:sub(-1,-1)\nend\n\nfunction add(b1,b2)\n local out = \"oops\"\n if b1 ~= \"\" and b2 ~= \"\" then\n local d = \"\"\n\n local L1 = last_char(b1)\n local c1 = b1:sub(1,-2)\n local L2 = last_char(b2)\n local c2 = b2:sub(1,-2)\n if L2 < L1 then\n L2, L1 = L1, L2\n end\n\n if L1 == '-' then\n if L2 == '0' then\n d = \"-\"\n end\n if L2 == '-' then\n d = \"+-\"\n end\n elseif L1 == '+' then\n if L2 == '0' then\n d = \"+\"\n elseif L2 == '-' then\n d = \"0\"\n elseif L2 == '+' then\n d = \"-+\"\n end\n elseif L1 == '0' then\n if L2 == '0' then\n d = \"0\"\n end\n end\n\n local ob1 = add(c1,d:sub(2,2))\n local ob2 = add(ob1,c2)\n\n out = ob2 .. d:sub(1,1)\n elseif b1 ~= \"\" then\n out = b1\n elseif b2 ~= \"\" then\n out = b2\n else\n out = \"\"\n end\n\n return out\nend\n\nfunction unary_minus(b)\n local out = \"\"\n\n for i=1, b:len() do\n local c = b:sub(i,i)\n if c == '-' then\n out = out .. '+'\n elseif c == '+' then\n out = out .. '-'\n else\n out = out .. c\n end\n end\n\n return out\nend\n\nfunction subtract(b1,b2)\n return add(b1, unary_minus(b2))\nend\n\nfunction mult(b1,b2)\n local r = \"0\"\n local c1 = b1\n local c2 = b2:reverse()\n\n for i=1,c2:len() do\n local c = c2:sub(i,i)\n if c == '+' then\n r = add(r, c1)\n elseif c == '-' then\n r = subtract(r, c1)\n end\n c1 = c1 .. '0'\n end\n\n while r:sub(1,1) == '0' do\n r = r:sub(2)\n end\n\n return r\nend\n\nfunction main()\n local a = \"+-0++0+\"\n local b = to_bt(-436)\n local c = \"+-++-\"\n local d = mult(a, subtract(b, c))\n\n print(string.format(\" a: %14s %10d\", a, from_bt(a)))\n print(string.format(\" b: %14s %10d\", b, from_bt(b)))\n print(string.format(\" c: %14s %10d\", c, from_bt(c)))\n print(string.format(\"a*(b-c): %14s %10d\", d, from_bt(d)))\nend\n\nmain()"} {"title": "Barnsley fern", "language": "Lua", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "g = love.graphics\nwid, hei = g.getWidth(), g.getHeight()\n\nfunction choose( i, j ) \n local r = math.random()\n if r < .01 then return 0, .16 * j \n elseif r < .07 then return .2 * i - .26 * j, .23 * i + .22 * j + 1.6\n elseif r < .14 then return -.15 * i + .28 * j, .26 * i + .24 * j + .44\n else return .85 * i + .04 * j, -.04 * i + .85 * j + 1.6\n end\nend\nfunction createFern( iterations )\n local hw, x, y, scale = wid / 2, 0, 0, 45\n local pts = {}\n for k = 1, iterations do\n pts[1] = { hw + x * scale, hei - 15 - y * scale, \n 20 + math.random( 80 ), \n 128 + math.random( 128 ), \n 20 + math.random( 80 ), 150 }\n g.points( pts )\n x, y = choose( x, y )\n end\nend\nfunction love.load()\n math.randomseed( os.time() )\n canvas = g.newCanvas( wid, hei )\n g.setCanvas( canvas )\n createFern( 15e4 )\n g.setCanvas()\nend\nfunction love.draw()\n g.draw( canvas )\nend\n"} {"title": "Base64 decode data", "language": "Lua", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "-- Start taken from https://stackoverflow.com/a/35303321\nlocal b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- You will need this for encoding/decoding\n\n-- decoding\nfunction dec(data)\n data = string.gsub(data, '[^'..b..'=]', '')\n return (data:gsub('.', function(x)\n if (x == '=') then return '' end\n local r,f='',(b:find(x)-1)\n for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end\n return r;\n end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)\n if (#x ~= 8) then return '' end\n local c=0\n for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end\n return string.char(c)\n end))\nend\n-- end of copy\n\nlocal data = \"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo\"\nprint(data)\nprint()\n\nlocal decoded = dec(data)\nprint(decoded)"} {"title": "Bell numbers", "language": "Lua", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "-- Bell numbers in Lua\n-- db 6/11/2020 (to replace missing original)\n\nlocal function bellTriangle(n)\n local tri = { {1} }\n for i = 2, n do\n tri[i] = { tri[i-1][i-1] }\n for j = 2, i do\n tri[i][j] = tri[i][j-1] + tri[i-1][j-1]\n end\n end\n return tri\nend\n\nlocal N = 25 -- in lieu of 50, practical limit with double precision floats\nlocal tri = bellTriangle(N)\n\nprint(\"First 15 and \"..N..\"th Bell numbers:\")\nfor i = 1, 15 do\n print(i, tri[i][1])\nend\nprint(N, tri[N][1])\n\nprint()\n\nprint(\"First 10 rows of Bell triangle:\")\nfor i = 1, 10 do\n print(\"[ \" .. table.concat(tri[i],\", \") .. \" ]\")\nend"} {"title": "Benford's law", "language": "Lua", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "actual = {}\nexpected = {}\nfor i = 1, 9 do\n actual[i] = 0\n expected[i] = math.log10(1 + 1 / i)\nend\n\nn = 0\nfile = io.open(\"fibs1000.txt\", \"r\")\nfor line in file:lines() do\n digit = string.byte(line, 1) - 48\n actual[digit] = actual[digit] + 1\n n = n + 1\nend\nfile:close()\n\nprint(\"digit actual expected\")\nfor i = 1, 9 do\n print(i, actual[i] / n, expected[i])\nend"} {"title": "Best shuffle", "language": "Lua", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "math.randomseed(os.time())\n\nlocal function shuffle(t)\n for i = #t, 2, -1 do\n local j = math.random(i)\n t[i], t[j] = t[j], t[i]\n end\nend\n\nlocal function bestshuffle(s, r)\n local order, shufl, count = {}, {}, 0\n for ch in s:gmatch(\".\") do order[#order+1], shufl[#shufl+1] = ch, ch end\n if r then shuffle(shufl) end\n for i = 1, #shufl do\n for j = 1, #shufl do\n if i ~= j and shufl[i] ~= order[j] and shufl[j] ~= order[i] then\n shufl[i], shufl[j] = shufl[j], shufl[i]\n end\n end\n end\n for i = 1, #shufl do\n if shufl[i] == order[i] then\n count = count + 1\n end\n end\n return table.concat(shufl), count\nend\n\nlocal words = { \"abracadabra\", \"seesaw\", \"elk\", \"grrrrrr\", \"up\", \"a\" }\n\nlocal function test(r)\n print(r and \"RANDOM:\" or \"DETERMINISTIC:\")\n for _, word in ipairs(words) do\n local shufl, count = bestshuffle(word, r)\n print(string.format(\"%s, %s, (%d)\", word, shufl, count))\n end\n print()\nend\n\ntest(true)\ntest(false)"} {"title": "Bin given limits", "language": "Lua", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "function binner(limits, data)\n local bins = setmetatable({}, {__index=function() return 0 end})\n local n, flr = #limits+1, math.floor\n for _, x in ipairs(data) do\n local lo, hi = 1, n\n while lo < hi do \n local mid = flr((lo + hi) / 2)\n if not limits[mid] or x < limits[mid] then hi=mid else lo=mid+1 end\n end\n bins[lo] = bins[lo] + 1\n end\n return bins\nend\n\nfunction printer(limits, bins)\n for i = 1, #limits+1 do\n print(string.format(\"[%3s,%3s) : %d\", limits[i-1] or \" -\u221e\", limits[i] or \" +\u221e\", bins[i]))\n end\nend\n\nprint(\"PART 1:\")\nlimits = {23, 37, 43, 53, 67, 83}\ndata = {95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55}\nbins = binner(limits, data)\nprinter(limits, bins)\n\nprint(\"\\nPART 2:\") \nlimits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}\ndata = {445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749}\nbins = binner(limits, data)\nprinter(limits, bins)\n"} {"title": "Bioinformatics/Sequence mutation", "language": "Lua", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "math.randomseed(os.time())\nbases = {\"A\",\"C\",\"T\",\"G\"}\nfunction randbase() return bases[math.random(#bases)] end\n\nfunction mutate(seq)\n local i,h = math.random(#seq), \"%-6s %3s at %3d\"\n local old,new = seq:sub(i,i), randbase()\n local ops = {\n function(s) h=h:format(\"Swap\", old..\">\"..new, i) return s:sub(1,i-1)..new..s:sub(i+1) end,\n function(s) h=h:format(\"Delete\", \" -\"..old, i) return s:sub(1,i-1)..s:sub(i+1) end,\n function(s) h=h:format(\"Insert\", \" +\"..new, i) return s:sub(1,i-1)..new..s:sub(i) end,\n }\n local weighted = { 1,1,2,3 }\n local n = weighted[math.random(#weighted)]\n return ops[n](seq), h\nend\n\nlocal seq,hist=\"\",{} for i = 1, 200 do seq=seq..randbase() end\nprint(\"ORIGINAL:\")\nprettyprint(seq)\nprint()\n\nfor i = 1, 10 do seq,h=mutate(seq) hist[#hist+1]=h end\nprint(\"MUTATIONS:\")\nfor i,h in ipairs(hist) do print(\" \"..h) end\nprint()\n\nprint(\"MUTATED:\")\nprettyprint(seq)"} {"title": "Bioinformatics/base count", "language": "Lua", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "function prettyprint(seq) -- approx DDBJ format\n seq = seq:gsub(\"%A\",\"\"):lower()\n local sums, n = { a=0, c=0, g=0, t=0 }, 1\n seq:gsub(\"(%a)\", function(c) sums[c]=sums[c]+1 end)\n local function printf(s,...) io.write(s:format(...)) end\n printf(\"LOCUS AB000000 %12d bp mRNA linear HUM 01-JAN-2001\\n\", #seq)\n printf(\" BASE COUNT %12d a %12d c %12d g %12d t\\n\", sums.a, sums.c, sums.g, sums.t)\n printf(\"ORIGIN\\n\")\n while n < #seq do\n local sub60 = seq:sub(n,n+59)\n printf(\"%9d %s\\n\", n, sub60:gsub(\"(..........)\",\"%1 \"))\n n = n + #sub60\n end\nend\n\nprettyprint[[\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n]]"} {"title": "Biorhythms", "language": "Lua from Phix", "task": "For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in \"Things to Do with your Pocket Calculator\" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.\n\nIt's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!\n\nTo compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. \n\nThe three cycles and their lengths are as follows:\n:::{| class=\"wikitable\"\n! Cycle \n! Length\n|- \n|Physical \n| 23 days\n|- \n|Emotional \n| 28 days\n|- \n|Mental \n| 33 days\n|}\n\nThe first half of each cycle is in \"plus\" territory, with a peak at the quarter-way point; the second half in \"minus\" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called \"critical\" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.\n\nThe task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. \"up and rising\", \"peak\", \"up but falling\", \"critical\", \"down and falling\", \"valley\", \"down but rising\"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.\n\nExample run of my Raku implementation:\nraku br.raku 1943-03-09 1972-07-11\n", "solution": "cycles = {\"Physical day \", \"Emotional day\", \"Mental day \"}\nlengths = {23, 28, 33}\nquadrants = {\n\t{\"up and rising\", \"peak\"},\n\t{\"up but falling\", \"transition\"},\n\t{\"down and falling\", \"valley\"},\n\t{\"down but rising\", \"transition\"},\n}\n \nfunction parse_date_string (birthDate)\n\tlocal year, month, day = birthDate:match(\"(%d+)-(%d+)-(%d+)\")\n\treturn {year=tonumber(year), month=tonumber(month), day=tonumber(day)}\nend\n \nfunction days_diffeternce (d1, d2)\n\tif d1.year >= 1970 and d2.year >= 1970 then\n\t\treturn math.floor(os.difftime(os.time(d2), os.time(d1))/(60*60*24))\n\telse\n\t\tlocal t1 = math.max (1970-d1.year, 1970-d2.year)\n\t\tt1 = math.ceil(t1/4)*4\n\t\td1.year = d1.year + t1\n\t\td2.year = d2.year + t1\n\t\treturn math.floor(os.difftime(os.time(d2), os.time(d1))/(60*60*24))\n\tend\nend\n \nfunction biorhythms (birthDate, targetDate)\n\tlocal bd = parse_date_string(birthDate)\n\tlocal td = parse_date_string(targetDate)\n\tlocal days = days_diffeternce (bd, td)\n \n\tprint('Born: '.. birthDate .. ', Target: ' .. targetDate)\n\tprint(\"Day: \", days)\n\tfor i=1, #lengths do\n\t\tlocal len = lengths[i]\n\t\tlocal posn = days%len\n\t\tlocal quadrant = math.floor(posn/len*4)+1\n\t\tlocal percent = math.floor(math.sin(2*math.pi*posn/len)*1000)/10\n\t\tlocal cycle = cycles[i]\n\t\tlocal desc = percent > 95 and \"peak\" or\n\t\t\tpercent < -95 and \"valley\" or\n\t\t\tmath.abs(percent) < 5 and \"critical transition\" or \"other\"\n\t\tif desc == \"other\" then\n\t\t\tlocal t = math.floor(quadrant/4*len)-posn\n\t\t\tlocal qtrend, qnext = quadrants[quadrant][1], quadrants[quadrant][2]\n\t\t\tdesc = percent .. '% (' .. qtrend .. ', next transition in ' .. t ..' days)'\n\t\tend\n\t\tprint(cycle, posn..'/'..len, ': '.. desc)\n\tend\n\tprint(' ')\nend\n \ndatePairs = {\n\t{\"1943-03-09\", \"1972-07-11\"},\n\t{\"1809-01-12\", \"1863-11-19\"},\n\t{\"1809-02-12\", \"1863-11-19\"},\n\t{\"2021-02-25\", \"2022-04-18\"},\n}\n \nfor i=1, #datePairs do \n\tbiorhythms(datePairs[i][1], datePairs[i][2]) \nend"} {"title": "Bitwise IO", "language": "Lua 5.1 and later, including LuaJIT", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "local function BitWriter() return {\n accumulator = 0, -- For current byte.\n bitCount = 0, -- Bits set in current byte.\n outChars = {},\n\n -- writer:writeBit( bit )\n writeBit = function(writer, bit)\n writer.bitCount = writer.bitCount + 1\n if bit > 0 then\n writer.accumulator = writer.accumulator + 2^(8-writer.bitCount)\n end\n if writer.bitCount == 8 then\n writer:_flush()\n end\n end,\n\n -- writer:writeLsb( value, width )\n writeLsb = function(writer, value, width)\n for i = 1, width do\n writer:writeBit(value%2)\n value = math.floor(value/2)\n end\n end,\n\n -- dataString = writer:getOutput( )\n getOutput = function(writer)\n writer:_flush()\n return table.concat(writer.outChars)\n end,\n\n _flush = function(writer)\n if writer.bitCount == 0 then return end\n\n table.insert(writer.outChars, string.char(writer.accumulator))\n writer.accumulator = 0\n writer.bitCount = 0\n end,\n} end\n\nlocal function BitReader(data) return {\n bitPosition = 0, -- Absolute position in 'data'.\n\n -- bit = reader:readBit( ) -- Returns nil at end-of-data.\n readBit = function(reader)\n reader.bitPosition = reader.bitPosition + 1\n local bytePosition = math.floor((reader.bitPosition-1)/8) + 1\n\n local byte = data:byte(bytePosition)\n if not byte then return nil end\n\n local bitIndex = ((reader.bitPosition-1)%8) + 1\n return math.floor(byte / 2^(8-bitIndex)) % 2\n end,\n\n -- value = reader:readLsb( width ) -- Returns nil at end-of-data.\n readLsb = function(reader, width)\n local accumulator = 0\n\n for i = 1, width do\n local bit = reader:readBit()\n if not bit then return nil end\n\n if bit > 0 then\n accumulator = accumulator + 2^(i-1)\n end\n end\n\n return accumulator\n end,\n} end"} {"title": "Box the compass", "language": "Lua from Logo", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "-- List of abbreviated compass point labels\ncompass_points = { \"N\", \"NbE\", \"N-NE\", \"NEbN\", \"NE\", \"NEbE\", \"E-NE\", \"EbN\",\n \"E\", \"EbS\", \"E-SE\", \"SEbE\", \"SE\", \"SEbS\", \"S-SE\", \"SbE\",\n \"S\", \"SbW\", \"S-SW\", \"SWbS\", \"SW\", \"SWbW\", \"W-SW\", \"WbS\",\n \"W\", \"WbN\", \"W-NW\", \"NWbW\", \"NW\", \"NWbN\", \"N-NW\", \"NbW\" }\n\n-- List of angles to test\ntest_angles = { 0.00, 16.87, 16.88, 33.75, 50.62, 50.63, 67.50,\n 84.37, 84.38, 101.25, 118.12, 118.13, 135.00, 151.87,\n 151.88, 168.75, 185.62, 185.63, 202.50, 219.37, 219.38,\n 236.25, 253.12, 253.13, 270.00, 286.87, 286.88, 303.75,\n 320.62, 320.63, 337.50, 354.37, 354.38 }\n\n\n-- capitalize a string\nfunction capitalize(s)\n return s:sub(1,1):upper() .. s:sub(2)\nend\n\n-- convert compass point abbreviation to full text of label\nfunction expand_point(abbr)\n for from, to in pairs( { N=\"north\", E=\"east\", S=\"south\", W=\"west\",\n b=\" by \" }) do\n abbr = abbr:gsub(from, to)\n end\n return capitalize(abbr)\nend\n\n-- modulus function that returns 1..N instead of 0..N-1\nfunction adjusted_modulo(n, d)\n return 1 + (n - 1) % d\nend\n\n-- convert a compass angle from degrees into a box index (1..32)\nfunction compass_point(degrees)\n degrees = degrees % 360\n return adjusted_modulo(1 + math.floor( (degrees+5.625) / 11.25), 32)\nend\n\n-- Now output the table of test data\nheader_format = \"%-7s | %-18s | %s\"\nrow_format = \"%7.2f | %-18s | %2d\"\nprint(header_format:format(\"Degrees\", \"Closest Point\", \"Index\"))\nfor i, angle in ipairs(test_angles) do\n index = compass_point(angle)\n abbr = compass_points[index]\n label = expand_point(abbr)\n print(row_format:format(angle, label, index))\nend"} {"title": "Brazilian numbers", "language": "Lua from C", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "function sameDigits(n,b)\n local f = n % b\n n = math.floor(n / b)\n while n > 0 do\n if n % b ~= f then\n return false\n end\n n = math.floor(n / b)\n end\n return true\nend\n\nfunction isBrazilian(n)\n if n < 7 then\n return false\n end\n if (n % 2 == 0) and (n >= 8) then\n return true\n end\n for b=2,n-2 do\n if sameDigits(n,b) then\n return true\n end\n end\n return false\nend\n\nfunction isPrime(n)\n if n < 2 then\n return false\n end\n if n % 2 == 0 then\n return n == 2\n end\n if n % 3 == 0 then\n return n == 3\n end\n\n local d = 5\n while d * d <= n do\n if n % d == 0 then\n return false\n end\n d = d + 2\n\n if n % d == 0 then\n return false\n end\n d = d + 4\n end\n\n return true\nend\n\nfunction main()\n local kinds = {\" \", \" odd \", \" prime \"}\n\n for i=1,3 do\n print(\"First 20\" .. kinds[i] .. \"Brazillion numbers:\")\n local c = 0\n local n = 7\n while true do\n if isBrazilian(n) then\n io.write(n .. \" \")\n c = c + 1\n if c == 20 then\n print()\n print()\n break\n end\n end\n if i == 1 then\n n = n + 1\n elseif i == 2 then\n n = n + 2\n elseif i == 3 then\n repeat\n n = n + 2\n until isPrime(n)\n end\n end\n end\nend\n\nmain()"} {"title": "Break OO privacy", "language": "Lua", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": "local function Counter()\n\t-- These two variables are \"private\" to this function and can normally\n\t-- only be accessed from within this scope, including by any function\n\t-- created inside here.\n\tlocal counter = {}\n\tlocal count = 0\n\n\tfunction counter:increment()\n\t\t-- 'count' is an upvalue here and can thus be accessed through the\n\t\t-- debug library, as long as we have a reference to this function.\n\t\tcount = count + 1\n\tend\n\n\treturn counter\nend\n\n-- Create a counter object and try to access the local 'count' variable.\nlocal counter = Counter()\n\nfor i = 1, math.huge do\n\tlocal name, value = debug.getupvalue(counter.increment, i)\n\tif not name then break end -- No more upvalues.\n\n\tif name == \"count\" then\n\t\tprint(\"Found 'count', which is \"..tostring(value))\n\t\t-- If the 'counter.increment' function didn't access 'count'\n\t\t-- directly then we would never get here.\n\t\tbreak\n\tend\nend"} {"title": "Burrows\u2013Wheeler transform", "language": "Lua from Java", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "STX = string.char(tonumber(2,16))\nETX = string.char(tonumber(3,16))\n\nfunction bwt(s)\n if s:find(STX, 1, true) then\n error(\"String cannot contain STX\")\n end\n if s:find(ETX, 1, true) then\n error(\"String cannot contain ETX\")\n end\n\n local ss = STX .. s .. ETX\n local tbl = {}\n for i=1,#ss do\n local before = ss:sub(i + 1)\n local after = ss:sub(1, i)\n table.insert(tbl, before .. after)\n end\n\n table.sort(tbl)\n\n local sb = \"\"\n for _,v in pairs(tbl) do\n sb = sb .. string.sub(v, #v, #v)\n end\n\n return sb\nend\n\nfunction ibwt(r)\n local le = #r\n local tbl = {}\n\n for i=1,le do\n table.insert(tbl, \"\")\n end\n for j=1,le do\n for i=1,le do\n tbl[i] = r:sub(i,i) .. tbl[i]\n end\n table.sort(tbl)\n end\n\n for _,row in pairs(tbl) do\n if row:sub(le,le) == ETX then\n return row:sub(2, le - 1)\n end\n end\n\n return \"\"\nend\n\nfunction makePrintable(s)\n local a = s:gsub(STX, '^')\n local b = a:gsub(ETX, '|')\n return b\nend\n\nfunction main()\n local tests = {\n \"banana\",\n \"appellee\",\n \"dogwood\",\n \"TO BE OR NOT TO BE OR WANT TO BE OR NOT?\",\n \"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\",\n STX .. \"ABC\" .. ETX\n }\n\n for _,test in pairs(tests) do\n print(makePrintable(test))\n io.write(\" --> \")\n local t = \"\"\n if xpcall(\n function () t = bwt(test) end,\n function (err) print(\"ERROR: \" .. err) end\n ) then\n print(makePrintable(t))\n end\n local r = ibwt(t)\n print(\" --> \" .. r)\n print()\n end\nend\n\nmain()"} {"title": "CSV data manipulation", "language": "Lua", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "local csv={}\nfor line in io.lines('file.csv') do\n table.insert(csv, {})\n local i=1\n for j=1,#line do\n if line:sub(j,j) == ',' then\n table.insert(csv[#csv], line:sub(i,j-1))\n i=j+1\n end\n end\n table.insert(csv[#csv], line:sub(i,j))\nend\n\ntable.insert(csv[1], 'SUM')\nfor i=2,#csv do\n local sum=0\n for j=1,#csv[i] do\n sum=sum + tonumber(csv[i][j])\n end\n if sum>0 then\n table.insert(csv[i], sum)\n end\nend\n\nlocal newFileData = ''\nfor i=1,#csv do\n newFileData=newFileData .. table.concat(csv[i], ',') .. '\\n'\nend\n\nlocal file=io.open('file.csv', 'w')\nfile:write(newFileData)\n"} {"title": "CSV to HTML translation", "language": "Lua", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "FS = \",\" -- field separator\n\ncsv = [[\nCharacter,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\n]] \n\ncsv = csv:gsub( \"<\", \"<\" )\ncsv = csv:gsub( \">\", \"&gr;\" )\n\nhtml = { \"\" } \nfor line in string.gmatch( csv, \"(.-\\n)\" ) do\n str = \"\"\n for field in string.gmatch( line, \"(.-)[\"..FS..\"?\\n?]\" ) do\n str = str .. \"\" \n end\n str = str .. \"\"\n html[#html+1] = str;\nend\nhtml[#html+1] = \"
\" .. field .. \"
\"\n\nfor _, line in pairs(html) do\n print(line)\nend"} {"title": "Calculating the value of e", "language": "Lua", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "EPSILON = 1.0e-15;\n\nfact = 1\ne = 2.0\ne0 = 0.0\nn = 2\n\nrepeat\n e0 = e\n fact = fact * n\n n = n + 1\n e = e + 1.0 / fact\nuntil (math.abs(e - e0) < EPSILON)\n\nio.write(string.format(\"e = %.15f\\n\", e))"} {"title": "Call a function", "language": "Lua", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped.\nfunction fixed (a, b, c) print(a, b, c) end\nfixed() --> nil nil nil\nfixed(1, 2, 3, 4, 5) --> 1 2 3\n\n-- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of values.\nfunction vararg (...) print(...) end\nvararg(1, 2, 3, 4, 5) -- 1 2 3 4 5\n\n-- Lua also allows dropping the parentheses if table or string literals are used as the sole argument\nprint \"some string\"\nprint { foo = \"bar\" } -- also serves as a form of named arguments\n\n-- First-class functions in expression context\nprint((\"this is backwards uppercase\"):gsub(\"%w+\", function (s) return s:upper():reverse() end))\n\n-- Functions can return multiple values (including none), which can be counted via select()\nlocal iter, obj, start = ipairs { 1, 2, 3 } \nprint(select(\"#\", (function () end)())) --> 0\nprint(select(\"#\", unpack { 1, 2, 3, 4 })) --> 4\n\n-- Partial application\nfunction prefix (pre)\n return function (suf) return pre .. suf end\nend\n\nlocal prefixed = prefix \"foo\"\nprint(prefixed \"bar\", prefixed \"baz\", prefixed \"quux\")\n\n-- nil, booleans, and numbers are always passed by value. Everything else is always passed by reference.\n-- There is no separate notion of subroutines\n-- Built-in functions are not easily distinguishable from user-defined functions\n"} {"title": "Cantor set", "language": "Lua from python", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "local WIDTH = 81\nlocal HEIGHT = 5\nlocal lines = {}\n\nfunction cantor(start, length, index)\n -- must be local, or only one side will get calculated\n local seg = math.floor(length / 3)\n if 0 == seg then\n return nil\n end\n\n -- remove elements that are not in the set\n for it=0, HEIGHT - index do\n i = index + it\n for jt=0, seg - 1 do\n j = start + seg + jt\n pos = WIDTH * i + j\n lines[pos] = ' '\n end\n end\n\n -- left side\n cantor(start, seg, index + 1)\n -- right side\n cantor(start + seg * 2, seg, index + 1)\n return nil\nend\n\n-- initialize the lines\nfor i=0, WIDTH * HEIGHT do\n lines[i] = '*'\nend\n\n-- calculate\ncantor(0, WIDTH, 1)\n\n-- print the result sets\nfor i=0, HEIGHT-1 do\n beg = WIDTH * i\n for j=beg, beg+WIDTH-1 do\n if j <= WIDTH * HEIGHT then\n io.write(lines[j])\n end\n end\n print()\nend"} {"title": "Cartesian product of two or more lists", "language": "Lua", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "local pk,upk = table.pack, table.unpack\n local getn = function(t)return #t end\n local const = function(k)return function(e) return k end end\n local function attachIdx(f)-- one-time-off function modifier\n local idx = 0\n return function(e)idx=idx+1 ; return f(e,idx)end\n end \n \n local function reduce(t,acc,f)\n for i=1,t.n or #t do acc=f(acc,t[i])end\n return acc\n end\n local function imap(t,f)\n local r = {n=t.n or #t, r=reduce, u=upk, m=imap}\n for i=1,r.n do r[i]=f(t[i])end\n return r\n end\n\n local function prod(...)\n local ts = pk(...)\n local limit = imap(ts,getn)\n local idx, cnt = imap(limit,const(1)), 0\n local max = reduce(limit,1,function(a,b)return a*b end)\n local function ret(t,i)return t[idx[i]] end\n return function()\n if cnt>=max then return end -- no more output\n if cnt==0 then -- skip for 1st\n cnt = cnt + 1 \n else\n cnt, idx[#idx] = cnt + 1, idx[#idx] + 1 \n for i=#idx,2,-1 do -- update index list\n if idx[i]<=limit[i] then \n break -- no further update need\n else -- propagate limit overflow\n idx[i],idx[i-1] = 1, idx[i-1]+1\n end \n end \n end\n return cnt,imap(ts,attachIdx(ret)):u()\n end \n end\n--- test\n for i,a,b in prod({1,2},{3,4}) do\n print(i,a,b)\n end\n print()\n for i,a,b in prod({3,4},{1,2}) do\n print(i,a,b)\n end\n"} {"title": "Casting out nines", "language": "Lua from C", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "local N = 2\nlocal base = 10\nlocal c1 = 0\nlocal c2 = 0\n\nfor k = 1, math.pow(base, N) - 1 do\n c1 = c1 + 1\n if k % (base - 1) == (k * k) % (base - 1) then\n c2 = c2 + 1\n io.write(k .. ' ')\n end\nend\n\nprint()\nprint(string.format(\"Trying %d numbers instead of %d numbers saves %f%%\", c2, c1, 100.0 - 100.0 * c2 / c1))"} {"title": "Catalan numbers/Pascal's triangle", "language": "Lua", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "function nextrow (t)\n local ret = {}\n t[0], t[#t + 1] = 0, 0\n for i = 1, #t do ret[i] = t[i - 1] + t[i] end\n return ret\nend\n \nfunction catalans (n)\n local t, middle = {1}\n for i = 1, n do\n middle = math.ceil(#t / 2)\n io.write(t[middle] - (t[middle + 1] or 0) .. \" \")\n t = nextrow(nextrow(t))\n end\nend\n\ncatalans(15)"} {"title": "Catamorphism", "language": "Lua", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "table.unpack = table.unpack or unpack -- 5.1 compatibility\nlocal nums = {1,2,3,4,5,6,7,8,9}\n\nfunction add(a,b)\n return a+b\nend\n\nfunction mult(a,b)\n return a*b\nend\n\nfunction cat(a,b)\n return tostring(a)..tostring(b)\nend\n\nlocal function reduce(fun,a,b,...)\n if ... then\n return reduce(fun,fun(a,b),...)\n else\n return fun(a,b)\n end\nend\n\nlocal arithmetic_sum = function (...) return reduce(add,...) end\nlocal factorial5 = reduce(mult,5,4,3,2,1)\n\nprint(\"\u03a3(1..9) : \",arithmetic_sum(table.unpack(nums)))\nprint(\"5! : \",factorial5)\nprint(\"cat {1..9}: \",reduce(cat,table.unpack(nums)))\n\n"} {"title": "Chaocipher", "language": "Lua", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "-- Chaocipher, in Lua, 6/19/2020 db\nlocal Chaocipher = {\n ct = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\",\n pt = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\",\n encrypt = function(self, text) return self:_encdec(text, true) end,\n decrypt = function(self, text) return self:_encdec(text, false) end,\n _encdec = function(self, text, encflag)\n local ct, pt, s = self.ct, self.pt, \"\"\n local cshl = function(s,i) return s:sub(i) .. s:sub(1,i-1) end\n local sshl = function(s,i) return s:sub(1,i-1) .. s:sub(i+1,14) .. s:sub(i,i) .. s:sub(15) end\n for ch in text:gmatch(\".\") do\n local i = (encflag and pt or ct):find(ch)\n s = s .. (encflag and ct or pt):sub(i,i)\n if encflag then print(ct, pt, ct:sub(i,i), pt:sub(i,i)) end\n ct, pt = sshl(cshl(ct, i), 2), sshl(cshl(pt, i+1), 3)\n end\n return s\n end,\n}\nlocal plainText = \"WELLDONEISBETTERTHANWELLSAID\"\nlocal encryptText = Chaocipher:encrypt(plainText)\nlocal decryptText = Chaocipher:decrypt(encryptText)\nprint()\nprint(\"The original text was: \" .. plainText)\nprint(\"The encrypted text is: \" .. encryptText)\nprint(\"The decrypted text is: \" .. decryptText)"} {"title": "Chaos game", "language": "Lua", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "math.randomseed( os.time() )\ncolors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}\n\nfunction love.load()\n wid, hei = love.graphics.getWidth(), love.graphics.getHeight()\n \n orig[1] = { wid / 2, 3 }\n orig[2] = { 3, hei - 3 }\n orig[3] = { wid - 3, hei - 3 }\n local w, h = math.random( 10, 40 ), math.random( 10, 40 )\n if math.random() < .5 then w = -w end\n if math.random() < .5 then h = -h end\n orig[4] = { wid / 2 + w, hei / 2 + h }\n \n canvas = love.graphics.newCanvas( wid, hei )\n love.graphics.setCanvas( canvas ); love.graphics.clear()\n love.graphics.setColor( 255, 255, 255 )\n love.graphics.points( orig )\n love.graphics.setCanvas()\nend\nfunction love.draw()\n local iter = 100 --> make this number bigger to speed up rendering\n for rp = 1, iter do\n local r, pts = math.random( 6 ), {}\n if r == 1 or r == 4 then\n pt = 1\n elseif r == 2 or r == 5 then\n pt = 2\n else \n pt = 3\n end\n local x, y = ( orig[4][1] + orig[pt][1] ) / 2, ( orig[4][2] + orig[pt][2] ) / 2\n orig[4][1] = x; orig[4][2] = y\n pts[1] = { x, y, colors[pt][1], colors[pt][2], colors[pt][3], 255 }\n love.graphics.setCanvas( canvas )\n love.graphics.points( pts )\n end\n love.graphics.setCanvas()\n love.graphics.draw( canvas )\nend\n"} {"title": "Cheryl's birthday", "language": "Lua", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "-- Cheryl's Birthday in Lua 6/15/2020 db\n\nlocal function Date(mon,day)\n return { mon=mon, day=day, valid=true }\nend\n\nlocal choices = {\n Date(\"May\", 15), Date(\"May\", 16), Date(\"May\", 19),\n Date(\"June\", 17), Date(\"June\", 18),\n Date(\"July\", 14), Date(\"July\", 16),\n Date(\"August\", 14), Date(\"August\", 15), Date(\"August\", 17)\n}\n\nlocal function apply(t, f)\n for k, v in ipairs(t) do\n f(k, v)\n end\nend\n\nlocal function filter(t, f)\n local result = {}\n for k, v in ipairs(t) do\n if f(k, v) then\n result[#result+1] = v\n end\n end\n return result\nend\n\nlocal function map(t, f)\n local result = {}\n for k, v in ipairs(t) do\n result[#result+1] = f(k, v)\n end\n return result\nend\n\nlocal function count(t) return #t end\nlocal function isvalid(k, v) return v.valid end\nlocal function invalidate(k, v) v.valid = false end\nlocal function remaining() return filter(choices, isvalid) end\n\nlocal function listValidChoices()\n print(\" \" .. table.concat(map(remaining(), function(k, v) return v.mon .. \" \" .. v.day end), \", \"))\n print()\nend\n\nprint(\"Cheryl offers these ten choices:\")\nlistValidChoices()\n\nprint(\"1) Albert knows that Bernard also cannot yet know, so cannot be a month with a unique day, leaving:\")\napply(remaining(), function(k, v)\n if count(filter(choices, function(k2, v2) return v.day==v2.day end)) == 1 then\n apply(filter(remaining(), function(k2, v2) return v.mon==v2.mon end), invalidate)\n end\nend)\nlistValidChoices()\n\nprint(\"2) After Albert's revelation, Bernard now knows, so day must be unique, leaving:\")\napply(remaining(), function(k, v)\n local subset = filter(remaining(), function(k2, v2) return v.day==v2.day end)\n if count(subset) > 1 then apply(subset, invalidate) end\nend)\nlistValidChoices()\n\nprint(\"3) After Bernard's revelation, Albert now knows, so month must be unique, leaving only:\")\napply(remaining(), function(k, v)\n local subset = filter(remaining(), function(k2, v2) return v.mon==v2.mon end)\n if count(subset) > 1 then apply(subset, invalidate) end\nend)\nlistValidChoices()"} {"title": "Chinese remainder theorem", "language": "Lua", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "-- Taken from https://www.rosettacode.org/wiki/Sum_and_product_of_an_array#Lua\nfunction prodf(a, ...) return a and a * prodf(...) or 1 end\nfunction prodt(t) return prodf(unpack(t)) end\n\nfunction mulInv(a, b)\n local b0 = b\n local x0 = 0\n local x1 = 1\n\n if b == 1 then\n return 1\n end\n\n while a > 1 do\n local q = math.floor(a / b)\n local amb = math.fmod(a, b)\n a = b\n b = amb\n local xqx = x1 - q * x0\n x1 = x0\n x0 = xqx\n end\n\n if x1 < 0 then\n x1 = x1 + b0\n end\n\n return x1\nend\n\nfunction chineseRemainder(n, a)\n local prod = prodt(n)\n\n local p\n local sm = 0\n for i=1,#n do\n p = prod / n[i]\n sm = sm + a[i] * mulInv(p, n[i]) * p\n end\n\n return math.fmod(sm, prod)\nend\n\nn = {3, 5, 7}\na = {2, 3, 2}\nio.write(chineseRemainder(n, a))"} {"title": "Chinese zodiac", "language": "Lua from C", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "local ANIMALS = {\"Rat\",\"Ox\",\"Tiger\",\"Rabbit\",\"Dragon\",\"Snake\",\"Horse\",\"Goat\",\"Monkey\",\"Rooster\",\"Dog\",\"Pig\"}\nlocal ELEMENTS = {\"Wood\",\"Fire\",\"Earth\",\"Metal\",\"Water\"}\n\nfunction element(year)\n local idx = math.floor(((year - 4) % 10) / 2)\n return ELEMENTS[idx + 1]\nend\n\nfunction animal(year)\n local idx = (year - 4) % 12\n return ANIMALS[idx + 1]\nend\n\nfunction yy(year)\n if year % 2 == 0 then\n return \"yang\"\n else\n return \"yin\"\n end\nend\n\nfunction zodiac(year)\n local e = element(year)\n local a = animal(year)\n local y = yy(year)\n print(year..\" is the year of the \"..e..\" \"..a..\" (\"..y..\")\")\nend\n\nzodiac(1935)\nzodiac(1938)\nzodiac(1968)\nzodiac(1972)\nzodiac(1976)\nzodiac(2017)"} {"title": "Church numerals", "language": "Lua", "task": "In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n\n", "solution": "function churchZero()\n return function(x) return x end \nend \n\nfunction churchSucc(c)\n return function(f) \n return function(x)\n return f(c(f)(x))\n end \n end \nend \n\nfunction churchAdd(c, d)\n return function(f) \n return function(x) \n return c(f)(d(f)(x))\n end \n end \nend \n\nfunction churchMul(c, d)\n return function(f) \n return c(d(f))\n end \nend \n\nfunction churchExp(c, e) \n return e(c)\nend \n\nfunction numToChurch(n) \n local ret = churchZero\n for i = 1, n do \n ret = succ(ret) \n end \n return ret \nend \n\nfunction churchToNum(c)\n return c(function(x) return x + 1 end)(0) \nend \n\nthree = churchSucc(churchSucc(churchSucc(churchZero)))\nfour = churchSucc(churchSucc(churchSucc(churchSucc(churchZero))))\n\nprint(\"'three'\\t=\", churchToNum(three))\nprint(\"'four' \\t=\", churchToNum(four))\nprint(\"'three' * 'four' =\", churchToNum(churchMul(three, four)))\nprint(\"'three' + 'four' =\", churchToNum(churchAdd(three, four)))\nprint(\"'three' ^ 'four' =\", churchToNum(churchExp(three, four)))\nprint(\"'four' ^ 'three' =\", churchToNum(churchExp(four, three)))"} {"title": "Circles of given radius through two points", "language": "Lua from C", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "function distance(p1, p2)\n local dx = (p1.x-p2.x)\n local dy = (p1.y-p2.y)\n return math.sqrt(dx*dx + dy*dy)\nend\n\nfunction findCircles(p1, p2, radius)\n local seperation = distance(p1, p2)\n if seperation == 0.0 then\n if radius == 0.0 then\n print(\"No circles can be drawn through (\"..p1.x..\", \"..p1.y..\")\")\n else\n print(\"Infinitely many circles can be drawn through (\"..p1.x..\", \"..p1.y..\")\")\n end\n elseif seperation == 2*radius then\n local cx = (p1.x+p2.x)/2\n local cy = (p1.y+p2.y)/2\n print(\"Given points are opposite ends of a diameter of the circle with center (\"..cx..\", \"..cy..\") and radius \"..radius)\n elseif seperation > 2*radius then\n print(\"Given points are further away from each other than a diameter of a circle with radius \"..radius)\n else\n local mirrorDistance = math.sqrt(math.pow(radius,2) - math.pow(seperation/2,2))\n local dx = p2.x - p1.x\n local dy = p1.y - p2.y\n local ax = (p1.x + p2.x) / 2\n local ay = (p1.y + p2.y) / 2\n local mx = mirrorDistance * dx / seperation\n local my = mirrorDistance * dy / seperation\n c1 = {x=ax+my, y=ay+mx}\n c2 = {x=ax-my, y=ay-mx}\n\n print(\"Two circles are possible.\")\n print(\"Circle C1 with center (\"..c1.x..\", \"..c1.y..\"), radius \"..radius)\n print(\"Circle C2 with center (\"..c2.x..\", \"..c2.y..\"), radius \"..radius)\n end\n print()\nend\n\ncases = {\n {x=0.1234, y=0.9876}, {x=0.8765, y=0.2345},\n {x=0.0000, y=2.0000}, {x=0.0000, y=0.0000},\n {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876},\n {x=0.1234, y=0.9876}, {x=0.8765, y=0.2345},\n {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876}\n}\nradii = { 2.0, 1.0, 2.0, 0.5, 0.0 }\nfor i=1, #radii do\n print(\"Case \"..i)\n findCircles(cases[i*2-1], cases[i*2], radii[i])\nend"} {"title": "Cistercian numerals", "language": "Lua from Go", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "function initN()\n local n = {}\n for i=1,15 do\n n[i] = {}\n for j=1,11 do\n n[i][j] = \" \"\n end\n n[i][6] = \"x\"\n end\n return n\nend\n\nfunction horiz(n, c1, c2, r)\n for c=c1,c2 do\n n[r+1][c+1] = \"x\"\n end\nend\n\nfunction verti(n, r1, r2, c)\n for r=r1,r2 do\n n[r+1][c+1] = \"x\"\n end\nend\n\nfunction diagd(n, c1, c2, r)\n for c=c1,c2 do\n n[r+c-c1+1][c+1] = \"x\"\n end\nend\n\nfunction diagu(n, c1, c2, r)\n for c=c1,c2 do\n n[r-c+c1+1][c+1] = \"x\"\n end\nend\n\nfunction initDraw()\n local draw = {}\n\n draw[1] = function(n) horiz(n, 6, 10, 0) end\n draw[2] = function(n) horiz(n, 6, 10, 4) end\n draw[3] = function(n) diagd(n, 6, 10, 0) end\n draw[4] = function(n) diagu(n, 6, 10, 4) end\n draw[5] = function(n) draw[1](n) draw[4](n) end\n draw[6] = function(n) verti(n, 0, 4, 10) end\n draw[7] = function(n) draw[1](n) draw[6](n) end\n draw[8] = function(n) draw[2](n) draw[6](n) end\n draw[9] = function(n) draw[1](n) draw[8](n) end\n\n draw[10] = function(n) horiz(n, 0, 4, 0) end\n draw[20] = function(n) horiz(n, 0, 4, 4) end\n draw[30] = function(n) diagu(n, 0, 4, 4) end\n draw[40] = function(n) diagd(n, 0, 4, 0) end\n draw[50] = function(n) draw[10](n) draw[40](n) end\n draw[60] = function(n) verti(n, 0, 4, 0) end\n draw[70] = function(n) draw[10](n) draw[60](n) end\n draw[80] = function(n) draw[20](n) draw[60](n) end\n draw[90] = function(n) draw[10](n) draw[80](n) end\n\n draw[100] = function(n) horiz(n, 6, 10, 14) end\n draw[200] = function(n) horiz(n, 6, 10, 10) end\n draw[300] = function(n) diagu(n, 6, 10, 14) end\n draw[400] = function(n) diagd(n, 6, 10, 10) end\n draw[500] = function(n) draw[100](n) draw[400](n) end\n draw[600] = function(n) verti(n, 10, 14, 10) end\n draw[700] = function(n) draw[100](n) draw[600](n) end\n draw[800] = function(n) draw[200](n) draw[600](n) end\n draw[900] = function(n) draw[100](n) draw[800](n) end\n\n draw[1000] = function(n) horiz(n, 0, 4, 14) end\n draw[2000] = function(n) horiz(n, 0, 4, 10) end\n draw[3000] = function(n) diagd(n, 0, 4, 10) end\n draw[4000] = function(n) diagu(n, 0, 4, 14) end\n draw[5000] = function(n) draw[1000](n) draw[4000](n) end\n draw[6000] = function(n) verti(n, 10, 14, 0) end\n draw[7000] = function(n) draw[1000](n) draw[6000](n) end\n draw[8000] = function(n) draw[2000](n) draw[6000](n) end\n draw[9000] = function(n) draw[1000](n) draw[8000](n) end\n\n return draw\nend\n\nfunction printNumeral(n)\n for i,v in pairs(n) do\n for j,w in pairs(v) do\n io.write(w .. \" \")\n end\n print()\n end\n print()\nend\n\nfunction main()\n local draw = initDraw()\n for i,number in pairs({0, 1, 20, 300, 4000, 5555, 6789, 9999}) do\n local n = initN()\n print(number..\":\")\n local thousands = math.floor(number / 1000)\n number = number % 1000\n local hundreds = math.floor(number / 100)\n number = number % 100\n local tens = math.floor(number / 10)\n local ones = number % 10\n if thousands > 0 then\n draw[thousands * 1000](n)\n end\n if hundreds > 0 then\n draw[hundreds * 100](n)\n end\n if tens > 0 then\n draw[tens * 10](n)\n end\n if ones > 0 then\n draw[ones](n)\n end\n printNumeral(n)\n end\nend\n\nmain()"} {"title": "Closures/Value capture", "language": "Lua", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "funcs={}\nfor i=1,10 do\n table.insert(funcs, function() return i*i end)\nend\nfuncs[2]()\nfuncs[3]()\n"} {"title": "Comma quibbling", "language": "Lua", "task": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "function quibble (strTab)\n local outString, join = \"{\"\n for strNum = 1, #strTab do\n if strNum == #strTab then\n join = \"\"\n elseif strNum == #strTab - 1 then\n join = \" and \" \n else\n join = \", \"\n end\n outString = outString .. strTab[strNum] .. join\n end\n return outString .. '}'\nend\n\nlocal testCases = {\n {},\n {\"ABC\"},\n {\"ABC\", \"DEF\"},\n {\"ABC\", \"DEF\", \"G\", \"H\"}\n}\nfor _, input in pairs(testCases) do print(quibble(input)) end"} {"title": "Command-line arguments", "language": "Lua", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "print( \"Program name:\", arg[0] )\n\nprint \"Arguments:\"\nfor i = 1, #arg do\n print( i,\" \", arg[i] )\nend"} {"title": "Compare a list of strings", "language": "Lua", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "function identical(t_str)\n _, fst = next(t_str)\n if fst then\n for _, i in pairs(t_str) do\n if i ~= fst then return false end\n end\n end\n return true\nend\n\nfunction ascending(t_str)\n prev = false\n for _, i in ipairs(t_str) do\n if prev and prev >= i then return false end\n prev = i\n end\n return true\nend\n\nfunction check(str)\n t_str = {}\n for i in string.gmatch(str, \"[%a_]+\") do\n table.insert(t_str, i)\n end\n str = str .. \": \"\n if not identical(t_str) then str = str .. \"not \" end\n str = str .. \"identical and \"\n if not ascending(t_str) then str = str .. \"not \" end\n print(str .. \"ascending.\")\nend\n\ncheck(\"ayu dab dog gar panda tui yak\")\ncheck(\"oy oy oy oy oy oy oy oy oy oy\")\ncheck(\"somehow somewhere sometime\")\ncheck(\"Hoosiers\")\ncheck(\"AA,BB,CC\")\ncheck(\"AA,AA,AA\")\ncheck(\"AA,CC,BB\")\ncheck(\"AA,ACB,BB,CC\")\ncheck(\"single_element\")"} {"title": "Compiler/lexical analyzer", "language": "Lua", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "-- module basic_token_finder\nlocal M = {} -- only items added to M will be public (via 'return M' at end)\nlocal table, string = table, string\nlocal error, tonumber, select, assert = error, tonumber, select, assert\n\nlocal token_name = require 'token_name'\n_ENV = {}\n\nfunction next_token(line, pos, line_num) -- match a token at line,pos\n local function m(pat)\n from, to, capture = line:find(pat, pos)\n if from then \n pos = to + 1\n return capture \n end\n end\n \n local function ptok(str) \n return {name=token_name[str]}\n end\n \n local function op2c()\n local text = m'^([<>=!]=)' or m'^(&&)' or m'^(||)'\n if text then return ptok(text) end\n end\n\n local function op1c_or_symbol()\n local char = m'^([%*/%%%+%-<>!=%(%){};,])'\n if char then return ptok(char) end\n end\n \n local function keyword_or_identifier()\n local text = m'^([%a_][%w_]*)'\n if text then\n local name = token_name[text]\n return name and {name=name} or {name='Identifier', value=text}\n end\n end\n \n local function integer()\n local text = m'^(%d+)%f[^%w_]'\n if text then return {name='Integer', value=tonumber(text)} end\n end\n \n local subst = {['\\\\\\\\'] = '\\\\', ['\\\\n'] = '\\n'}\n \n local function qchar()\n local text = m\"^'([^\\\\])'\" or m\"^'(\\\\[\\\\n])'\"\n if text then\n local value = #text==1 and text:byte() or subst[text]:byte()\n return {name='Integer', value=value}\n end\n end\n \n local function qstr()\n local text = m'^\"([^\"\\n]*\\\\?)\"'\n if text then\n local value = text:gsub('()(\\\\.?)', function(at, esc)\n local replace = subst[esc]\n if replace then \n return replace \n else\n error{err='bad_escseq', line=line_num, column=pos+at-1}\n end \n end)\n return {name='String', value=value}\n end\n end\n \n local found = (op2c() or op1c_or_symbol() or \n keyword_or_identifier() or integer() or qchar() or qstr()) \n if found then\n return found, pos\n end \nend\n\nfunction find_commentrest(line, pos, line_num, socpos)\n local sfrom, sto = line:find('%*%/', pos)\n if sfrom then\n return socpos, sto\n else\n error{err='unfinished_comment', line=line_num, column=socpos}\n end\nend \n\nfunction find_comment(line, pos, line_num)\n local sfrom, sto = line:find('^%/%*', pos)\n if sfrom then\n local efrom, eto = find_commentrest(line, sto+1, line_num, sfrom)\n return sfrom, eto\n end\nend\n\nfunction find_morecomment(line, pos, line_num)\n assert(pos==1)\n return find_commentrest(line, pos, line_num, pos)\nend\n\nfunction find_whitespace(line, pos, line_num)\n local spos = pos\n repeat\n local eto = select(2, line:find('^%s+', pos))\n if not eto then\n eto = select(2, find_comment(line, pos, line_num))\n end\n if eto then pos = eto + 1 end\n until not eto\n return spos, pos - 1\nend\n\nfunction M.find_token(line, pos, line_num, in_comment)\n local spos = pos\n if in_comment then\n pos = 1 + select(2, find_morecomment(line, pos, line_num))\n end\n pos = 1 + select(2, find_whitespace(line, pos, line_num))\n if pos > #line then\n return nil\n else\n local token, nextpos = next_token(line, pos, line_num)\n if token then\n token.line, token.column = line_num, pos\n return token, nextpos\n else\n error{err='invalid_token', line=line_num, column=pos}\n end\n end \nend\n\n-- M._ENV = _ENV\nreturn M"} {"title": "Continued fraction", "language": "Lua from C", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "function calc(fa, fb, expansions)\n local a = 0.0\n local b = 0.0\n local r = 0.0\n local i = expansions\n while i > 0 do\n a = fa(i)\n b = fb(i)\n r = b / (a + r)\n i = i - 1\n end\n a = fa(0)\n return a + r\nend\n\nfunction sqrt2a(n)\n if n ~= 0 then\n return 2.0\n else\n return 1.0\n end\nend\n\nfunction sqrt2b(n)\n return 1.0\nend\n\nfunction napiera(n)\n if n ~= 0 then\n return n\n else\n return 2.0\n end\nend\n\nfunction napierb(n)\n if n > 1.0 then\n return n - 1.0\n else\n return 1.0\n end\nend\n\nfunction pia(n)\n if n ~= 0 then\n return 6.0\n else\n return 3.0\n end\nend\n\nfunction pib(n)\n local c = 2.0 * n - 1.0\n return c * c\nend\n\nfunction main()\n local sqrt2 = calc(sqrt2a, sqrt2b, 1000)\n local napier = calc(napiera, napierb, 1000)\n local pi = calc(pia, pib, 1000)\n print(sqrt2)\n print(napier)\n print(pi)\nend\n\nmain()"} {"title": "Convert decimal number to rational", "language": "Lua", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": "for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do\n local n, d, dmax, eps = 1, 1, 1e7, 1e-15\n while math.abs(n/d-v)>eps and d %d / %d\", v, n, d))\nend"} {"title": "Convert seconds to compound duration", "language": "Lua", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "function duration (secs)\n local units, dur = {\"wk\", \"d\", \"hr\", \"min\"}, \"\"\n for i, v in ipairs({604800, 86400, 3600, 60}) do\n if secs >= v then\n dur = dur .. math.floor(secs / v) .. \" \" .. units[i] .. \", \"\n secs = secs % v\n end\n end\n if secs == 0 then \n return dur:sub(1, -3)\n else\n return dur .. secs .. \" sec\"\n end\nend\n\nprint(duration(7259))\nprint(duration(86400))\nprint(duration(6000000))"} {"title": "Count the coins", "language": "Lua", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "function countSums (amount, values)\n local t = {}\n for i = 1, amount do t[i] = 0 end\n t[0] = 1\n for k, val in pairs(values) do\n for i = val, amount do t[i] = t[i] + t[i - val] end\n end\n return t[amount]\nend\n\nprint(countSums(100, {1, 5, 10, 25}))\nprint(countSums(100000, {1, 5, 10, 25, 50, 100}))"} {"title": "Create an HTML table", "language": "Lua", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "function htmlTable (data)\n local html = \"\\n\\n\\n\"\n for _, heading in pairs(data[1]) do\n html = html .. \"\" .. \"\\n\"\n end\n html = html .. \"\\n\"\n for row = 2, #data do\n html = html .. \"\\n\\n\"\n for _, field in pairs(data[row]) do\n html = html .. \"\\n\"\n end\n html = html .. \"\\n\"\n end\n return html .. \"
\" .. heading .. \"
\" .. row - 1 .. \"\" .. field .. \"
\"\nend\n\nlocal tableData = {\n {\"X\", \"Y\", \"Z\"},\n {\"1\", \"2\", \"3\"},\n {\"4\", \"5\", \"6\"},\n {\"7\", \"8\", \"9\"}\n}\n\nprint(htmlTable(tableData))"} {"title": "Cullen and Woodall numbers", "language": "Lua", "task": "A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number.\n\nSo for each '''n''' the associated Cullen number and Woodall number differ by 2.\n\n''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''\n\n\n'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.\n\n\n;Task\n\n* Write procedures to find Cullen numbers and Woodall numbers. \n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\n\n;Stretch\n\n* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.\n\n* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.\n\n\n;See also\n\n* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1\n\n* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1\n\n* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime\n\n* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime\n\n\n", "solution": "function T(t) return setmetatable(t, {__index=table}) end\ntable.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end\ntable.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end\n\nfunction cullen(n) return (n< .nnnnnn, follow with trunc(2) to trim trailing zeroes\n\nsubtot = (C\"4000000000000000\" * C\"5.50\" + C\"2\" * C\"2.86\"):trunc(2) -- cosmetic trunc\ntax = (subtot * C\"0.0765\" + C\"0.005\"):trunc(2) -- rounding trunc\ntotal = (subtot + tax):trunc(2) -- cosmetic trunc\n\nprint((\"Before tax: %20s\"):format(subtot:tostring()))\nprint((\"Tax : %20s\"):format(tax:tostring()))\nprint((\"With tax : %20s\"):format(total:tostring()))"} {"title": "Currying", "language": "Lua", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "local curry do\n local call,env = function(fn,...)return fn(...)end\n local fmt,cat,rawset,rawget,floor = string.format,table.concat,rawset,rawget,math.floor\n local curryHelper = setmetatable({},{\n __call = function(me, n, m, ...)return me[n*256+m](...)end,\n __index = function(me,k)\n local n,m = floor(k / 256), k % 256\n local r,s = {},{} for i=1,m do r[i],s[i]='_'..i,'_'..i end s[1+#s]='...'\n r,s=cat(r,','),cat(s,',')\n s = n 1 then\n io.write(\", \")\n end\n io.write(v)\n end\n print(\"]\")\n end\nend\n\nfunction cutRectangle(w, h)\n if w % 2 == 1 and h % 2 == 1 then\n return nil\n end\n\n local grid = array2D(h, w, 0)\n local stack = {}\n\n local half = math.floor((w * h) / 2)\n local bits = 2 ^ half - 1\n\n while bits > 0 do\n for i=1,half do\n local r = math.floor((i - 1) / w)\n local c = (i - 1) % w\n if (bits & (1 << (i - 1))) ~= 0 then\n grid[r + 1][c + 1] = 1\n else\n grid[r + 1][c + 1] = 0\n end\n grid[h - r][w - c] = 1 - grid[r + 1][c + 1]\n end\n\n push(stack, 0)\n grid[1][1] = 2\n local count = 1\n while not empty(stack) do\n local pos = pop(stack)\n\n local r = math.floor(pos / w)\n local c = pos % w\n\n for i,dir in pairs(DIRS) do\n local nextR = r + dir[1]\n local nextC = c + dir[2]\n\n if nextR >= 0 and nextR < h and nextC >= 0 and nextC < w then\n if grid[nextR + 1][nextC + 1] == 1 then\n push(stack, nextR * w + nextC)\n grid[nextR + 1][nextC + 1] = 2\n count = count + 1\n end\n end\n end\n end\n if count == half then\n printResult(grid)\n print()\n end\n\n -- loop end\n bits = bits - 2\n end\nend\n\ncutRectangle(2, 2)\ncutRectangle(4, 3)"} {"title": "Damm algorithm", "language": "Lua", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "local tab = {\n {0,3,1,7,5,9,8,6,4,2}, {7,0,9,2,1,5,4,8,6,3},\n {4,2,0,6,8,7,1,3,5,9}, {1,7,5,0,9,8,3,4,2,6},\n {6,1,2,3,0,4,5,9,7,8}, {3,6,7,4,2,0,9,5,8,1},\n {5,8,6,9,7,2,0,1,3,4}, {8,9,4,5,3,6,2,0,1,7},\n {9,4,3,8,6,1,7,2,0,5}, {2,5,8,1,4,3,6,7,9,0}\n}\nfunction check( n )\n local idx, a = 0, tonumber( n:sub( 1, 1 ) )\n for i = 1, #n do\n a = tonumber( n:sub( i, i ) )\n if a == nil then return false end\n idx = tab[idx + 1][a + 1]\n end\n return idx == 0\nend\nlocal n, r\nwhile( true ) do\n io.write( \"Enter the number to check: \" )\n n = io.read(); if n == \"0\" then break end\n r = check( n ); io.write( n, \" is \" )\n if not r then io.write( \"in\" ) end\n io.write( \"valid!\\n\" )\nend"} {"title": "De Bruijn sequences", "language": "Lua from C++", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "function tprint(tbl)\n for i,v in pairs(tbl) do\n print(v)\n end\nend\n\nfunction deBruijn(k, n)\n local a = {}\n for i=1, k*n do\n table.insert(a, 0)\n end\n\n local seq = {}\n function db(t, p)\n if t > n then\n if n % p == 0 then\n for i=1, p do\n table.insert(seq, a[i + 1])\n end\n end\n else\n a[t + 1] = a[t - p + 1]\n db(t + 1, p)\n\n local j = a[t - p + 1] + 1\n while j < k do\n a[t + 1] = j % 256\n db(t + 1, t)\n j = j + 1\n end\n end\n end\n\n db(1, 1)\n\n local buf = \"\"\n for i,v in pairs(seq) do\n buf = buf .. tostring(v)\n end\n return buf .. buf:sub(1, n - 1)\nend\n\nfunction allDigits(s)\n return s:match('[0-9]+') == s\nend\n\nfunction validate(db)\n local le = string.len(db)\n local found = {}\n local errs = {}\n\n for i=1, 10000 do\n table.insert(found, 0)\n end\n\n -- Check all strings of 4 consecutive digits within 'db'\n -- to see if all 10,000 combinations occur without duplication.\n for i=1, le - 3 do\n local s = db:sub(i, i + 3)\n if allDigits(s) then\n local n = tonumber(s)\n found[n + 1] = found[n + 1] + 1\n end\n end\n\n local count = 0\n for i=1, 10000 do\n if found[i] == 0 then\n table.insert(errs, \" PIN number \" .. (i - 1) .. \" missing\")\n count = count + 1\n elseif found[i] > 1 then\n table.insert(errs, \" PIN number \" .. (i - 1) .. \" occurs \" .. found[i] .. \" times\")\n count = count + 1\n end\n end\n\n if count == 0 then\n print(\" No errors found\")\n else\n tprint(errs)\n end\nend\n\nfunction main()\n local db = deBruijn(10,4)\n\n print(\"The length of the de Bruijn sequence is \" .. string.len(db))\n print()\n\n io.write(\"The first 130 digits of the de Bruijn sequence are: \")\n print(db:sub(0, 130))\n print()\n\n io.write(\"The last 130 digits of the de Bruijn sequence are: \")\n print(db:sub(-130))\n print()\n\n print(\"Validating the de Bruijn sequence:\")\n validate(db)\n print()\n\n print(\"Validating the reversed de Bruijn sequence:\")\n validate(db:reverse())\n print()\n\n db = db:sub(1,4443) .. \".\" .. db:sub(4445)\n print(\"Validating the overlaid de Bruijn sequence:\")\n validate(db)\n print()\nend\n\nmain()"} {"title": "Deepcopy", "language": "Lua", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "function _deepcopy(o, tables)\n \n if type(o) ~= 'table' then\n return o\n end\n \n if tables[o] ~= nil then\n return tables[o]\n end\n \n local new_o = {}\n tables[o] = new_o\n \n for k, v in next, o, nil do\n local new_k = _deepcopy(k, tables)\n local new_v = _deepcopy(v, tables)\n new_o[new_k] = new_v\n end\n \n return new_o\nend\n \nfunction deepcopy(o)\n return _deepcopy(o, {})\nend"} {"title": "Department numbers", "language": "Lua", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "print( \"Fire\", \"Police\", \"Sanitation\" )\nsol = 0\nfor f = 1, 7 do\n for p = 1, 7 do\n for s = 1, 7 do\n if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then\n print( f, p, s ); sol = sol + 1\n end\n end\n end\nend\nprint( string.format( \"\\n%d solutions found\", sol ) )\n"} {"title": "Descending primes", "language": "Lua", "task": "Generate and show all primes with strictly descending decimal digits.\n\n;See also\n;* OEIS:A052014 - Primes with distinct digits in descending order\n\n;Related:\n*[[Ascending primes]]\n\n\n", "solution": "local function is_prime(n)\n if n < 2 then return false end\n if n % 2 == 0 then return n==2 end\n if n % 3 == 0 then return n==3 end\n for f = 5, n^0.5, 6 do\n if n%f==0 or n%(f+2)==0 then return false end\n end\n return true\nend\n\nlocal function descending_primes()\n local digits, candidates, primes = {9,8,7,6,5,4,3,2,1}, {0}, {}\n for i = 1, #digits do\n for j = 1, #candidates do\n local value = candidates[j] * 10 + digits[i]\n if is_prime(value) then primes[#primes+1] = value end\n candidates[#candidates+1] = value\n end\n end\n table.sort(primes)\n return primes\nend\n\nprint(table.concat(descending_primes(), \", \"))"} {"title": "Detect division by zero", "language": "Lua", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "local function div(a,b)\n if b == 0 then error() end\n return a/b\nend"} {"title": "Determinant and permanent", "language": "Lua", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "-- Johnson\u2013Trotter permutations generator\n_JT={}\nfunction JT(dim)\n local n={ values={}, positions={}, directions={}, sign=1 }\n setmetatable(n,{__index=_JT})\n for i=1,dim do\n n.values[i]=i\n n.positions[i]=i\n n.directions[i]=-1\n end\n return n\nend\n\nfunction _JT:largestMobile()\n for i=#self.values,1,-1 do\n local loc=self.positions[i]+self.directions[i]\n if loc >= 1 and loc <= #self.values and self.values[loc] < i then\n return i\n end\n end\n return 0\nend\n\nfunction _JT:next()\n local r=self:largestMobile()\n if r==0 then return false end\n local rloc=self.positions[r]\n local lloc=rloc+self.directions[r]\n local l=self.values[lloc]\n self.values[lloc],self.values[rloc] = self.values[rloc],self.values[lloc]\n self.positions[l],self.positions[r] = self.positions[r],self.positions[l]\n self.sign=-self.sign\n for i=r+1,#self.directions do self.directions[i]=-self.directions[i] end\n return true\nend \n\n-- matrix class\n\n_MTX={}\nfunction MTX(matrix)\n setmetatable(matrix,{__index=_MTX})\n matrix.rows=#matrix\n matrix.cols=#matrix[1]\n return matrix\nend\n\nfunction _MTX:dump()\n for _,r in ipairs(self) do\n print(unpack(r))\n end\nend\n\nfunction _MTX:perm() return self:det(1) end\nfunction _MTX:det(perm)\n local det=0\n local jt=JT(self.cols)\n repeat\n local pi=perm or jt.sign\n for i,v in ipairs(jt.values) do\n pi=pi*self[i][v]\n end\n det=det+pi\n until not jt:next()\n return det\nend\n\n-- test\n\nmatrix=MTX\n{\n { 7, 2, -2, 4},\n { 4, 4, 1, 7},\n {11, -8, 9, 10},\n {10, 5, 12, 13}\n}\nmatrix:dump();\nprint(\"det:\",matrix:det(), \"permanent:\",matrix:perm(),\"\\n\")\n\nmatrix2=MTX\n{\n {-2, 2,-3},\n {-1, 1, 3},\n { 2, 0,-1}\n}\nmatrix2:dump();\nprint(\"det:\",matrix2:det(), \"permanent:\",matrix2:perm())\n"} {"title": "Determine if a string has all the same characters", "language": "Lua", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "function analyze(s)\n print(string.format(\"Examining [%s] which has a length of %d:\", s, string.len(s)))\n if string.len(s) > 1 then\n local last = string.byte(string.sub(s,1,1))\n for i=1,string.len(s) do\n local c = string.byte(string.sub(s,i,i))\n if last ~= c then\n print(\" Not all characters in the string are the same.\")\n print(string.format(\" '%s' (0x%x) is different at position %d\", string.sub(s,i,i), c, i - 1))\n return\n end\n end\n end\n print(\" All characters in the string are the same.\")\nend\n\nfunction main()\n analyze(\"\")\n analyze(\" \")\n analyze(\"2\")\n analyze(\"333\")\n analyze(\".55\")\n analyze(\"tttTTT\")\n analyze(\"4444 444k\")\nend\n\nmain()"} {"title": "Determine if a string has all unique characters", "language": "Lua", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "local find, format = string.find, string.format\nlocal function printf(fmt, ...) print(format(fmt,...)) end\n\nlocal pattern = '(.).-%1' -- '(.)' .. '.-' .. '%1'\n\nfunction report_dup_char(subject)\n local pos1, pos2, char = find(subject, pattern)\n\n local prefix = format('\"%s\" (%d)', subject, #subject)\n if pos1 then\n local byte = char:byte()\n printf(\"%s: '%s' (0x%02x) duplicates at %d, %d\", prefix, char, byte, pos1, pos2)\n else\n printf(\"%s: no duplicates\", prefix)\n end\nend\n\nlocal show = report_dup_char\nshow('coccyx')\nshow('')\nshow('.')\nshow('abcABC')\nshow('XYZ ZYX')\nshow('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')\n"} {"title": "Determine if a string is collapsible", "language": "Lua from C#", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "function collapse(s)\n local ns = \"\"\n local last = nil\n for c in s:gmatch\".\" do\n if last then\n if last ~= c then\n ns = ns .. c\n end\n last = c\n else\n ns = ns .. c\n last = c\n end\n end\n return ns\nend\n\nfunction test(s)\n print(\"old: \" .. s:len() .. \" <<<\" .. s .. \">>>\")\n local a = collapse(s)\n print(\"new: \" .. a:len() .. \" <<<\" .. a .. \">>>\")\nend\n\nfunction main()\n test(\"\")\n test(\"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\")\n test(\"headmistressship\")\n test(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \")\n test(\"..1111111111111111111111111111111111111111111111111111111111111117777888\")\n test(\"I never give 'em hell, I just tell the truth, and they think it's hell. \")\n test(\" --- Harry S Truman \")\nend\n\nmain()"} {"title": "Determine if a string is squeezable", "language": "Lua from D", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "function squeezable(s, rune)\n print(\"squeeze: `\" .. rune .. \"`\")\n print(\"old: <<<\" .. s .. \">>>, length = \" .. string.len(s))\n\n local last = nil\n local le = 0\n io.write(\"new: <<<\")\n for c in s:gmatch\".\" do\n if c ~= last or c ~= rune then\n io.write(c)\n le = le + 1\n end\n last = c\n end\n print(\">>>, length = \" .. le)\n\n print()\nend\n\nfunction main()\n squeezable(\"\", ' ');\n squeezable(\"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \", '-')\n squeezable(\"..1111111111111111111111111111111111111111111111111111111111111117777888\", '7')\n squeezable(\"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.')\n \n local s = \" --- Harry S Truman \"\n squeezable(s, ' ')\n squeezable(s, '-')\n squeezable(s, 'r')\nend\n\nmain()"} {"title": "Determine if two triangles overlap", "language": "Lua from C++", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\n", "solution": "function det2D(p1,p2,p3)\n return p1.x * (p2.y - p3.y)\n + p2.x * (p3.y - p1.y)\n + p3.x * (p1.y - p2.y)\nend\n\nfunction checkTriWinding(p1,p2,p3,allowReversed)\n local detTri = det2D(p1,p2,p3)\n if detTri < 0.0 then\n if allowReversed then\n local t = p3\n p3 = p2\n p2 = t\n else\n error(\"triangle has wrong winding direction\")\n end\n end\n return nil\nend\n\nfunction boundaryCollideChk(p1,p2,p3,eps)\n return det2D(p1,p2,p3) < eps\nend\n\nfunction boundaryDoesntCollideChk(p1,p2,p3,eps)\n return det2D(p1,p2,p3) <= eps\nend\n\nfunction triTri2D(t1,t2,eps,allowReversed,onBoundary)\n eps = eps or 0.0\n allowReversed = allowReversed or false\n onBoundary = onBoundary or true\n\n -- triangles must be expressed anti-clockwise\n checkTriWinding(t1[1], t1[2], t1[3], allowReversed)\n checkTriWinding(t2[1], t2[2], t2[3], allowReversed)\n\n local chkEdge\n if onBoundary then\n -- points on the boundary are considered as colliding\n chkEdge = boundaryCollideChk\n else\n -- points on the boundary are not considered as colliding\n chkEdge = boundaryDoesntCollideChk\n end\n\n -- for edge E of triangle 1\n for i=0,2 do\n local j = (i+1)%3\n\n -- check all points of triangle 2 lay on the external side of the edge E.\n -- If they do, the triangles do not collide\n if chkEdge(t1[i+1], t1[j+1], t2[1], eps) and\n chkEdge(t1[i+1], t1[j+1], t2[2], eps) and\n chkEdge(t1[i+1], t1[j+1], t2[3], eps) then\n return false\n end\n end\n\n -- for edge E of triangle 2\n for i=0,2 do\n local j = (i+1)%3\n\n -- check all points of triangle 1 lay on the external side of the edge E.\n -- If they do, the triangles do not collide\n if chkEdge(t2[i+1], t2[j+1], t1[1], eps) and\n chkEdge(t2[i+1], t2[j+1], t1[2], eps) and\n chkEdge(t2[i+1], t2[j+1], t1[3], eps) then\n return false\n end\n end\n\n -- the triangles collide\n return true\nend\n\nfunction formatTri(t)\n return \"Triangle: (\"..t[1].x..\", \"..t[1].y\n ..\"), (\"..t[2].x..\", \"..t[2].y\n ..\"), (\"..t[3].x..\", \"..t[3].y..\")\"\nend\n\nfunction overlap(t1,t2,eps,allowReversed,onBoundary)\n if triTri2D(t1,t2,eps,allowReversed,onBoundary) then\n return \"overlap\\n\"\n else\n return \"do not overlap\\n\"\n end\nend\n\n-- Main\nlocal t1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}}\nlocal t2 = {{x=0,y=0},{x=5,y=0},{x=0,y=6}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}}\nt2 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2,0.0,true))\n\nt1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}}\nt2 = {{x=-10,y=0},{x=-5,y=0},{x=-1,y=6}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=5,y=0},{x=2.5,y=5}}\nt2 = {{x=0,y=4},{x=2.5,y=-1},{x=5,y=4}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}}\nt2 = {{x=2,y=1},{x=3,y=0},{x=3,y=2}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\nt1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}}\nt2 = {{x=2,y=1},{x=3,y=-2},{x=3,y=4}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2))\n\n-- Barely touching\nt1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}}\nt2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2,0.0,false,true))\n\n-- Barely touching\nlocal t1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}}\nlocal t2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}}\nprint(formatTri(t1)..\" and\")\nprint(formatTri(t2))\nprint(overlap(t1,t2,0.0,false,false))"} {"title": "Dice game probabilities", "language": "Lua", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "local function simu(ndice1, nsides1, ndice2, nsides2)\n local function roll(ndice, nsides)\n local result = 0;\n for i = 1, ndice do\n result = result + math.random(nsides)\n end\n return result\n end\n local wins, coms = 0, 1000000\n for i = 1, coms do\n local roll1 = roll(ndice1, nsides1)\n local roll2 = roll(ndice2, nsides2)\n if (roll1 > roll2) then\n wins = wins + 1\n end\n end\n print(\"simulated: p1 = \"..ndice1..\"d\"..nsides1..\", p2 = \"..ndice2..\"d\"..nsides2..\", prob = \"..wins..\" / \"..coms..\" = \"..(wins/coms))\nend\n\nsimu(9, 4, 6, 6)\nsimu(5, 10, 6, 7)\n"} {"title": "Digital root", "language": "Lua", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "function digital_root(n, base)\n p = 0\n while n > 9.5 do\n n = sum_digits(n, base)\n p = p + 1\n end\n return n, p\nend\n\nprint(digital_root(627615, 10))\nprint(digital_root(39390, 10))\nprint(digital_root(588225, 10))\nprint(digital_root(393900588225, 10))"} {"title": "Disarium numbers", "language": "Lua", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "function isDisarium (x)\n local str, sum, digit = tostring(x), 0\n for pos = 1, #str do\n digit = tonumber(str:sub(pos, pos))\n sum = sum + (digit ^ pos)\n end\n return sum == x\nend\n\nlocal count, n = 0, 0\nwhile count < 19 do\n if isDisarium(n) then\n count = count + 1\n io.write(n .. \" \")\n end\n n = n + 1\nend"} {"title": "Display a linear combination", "language": "Lua from C#", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "function t2s(t)\n local s = \"[\"\n for i,v in pairs(t) do\n if i > 1 then\n s = s .. \", \" .. v\n else\n s = s .. v\n end\n end\n return s .. \"]\"\nend\n\nfunction linearCombo(c)\n local sb = \"\"\n for i,n in pairs(c) do\n local skip = false\n\n if n < 0 then\n if sb:len() == 0 then\n sb = sb .. \"-\"\n else\n sb = sb .. \" - \"\n end\n elseif n > 0 then\n if sb:len() ~= 0 then\n sb = sb .. \" + \"\n end\n else\n skip = true\n end\n\n if not skip then\n local av = math.abs(n)\n if av ~= 1 then\n sb = sb .. av .. \"*\"\n end\n sb = sb .. \"e(\" .. i .. \")\"\n end\n end\n if sb:len() == 0 then\n sb = \"0\"\n end\n return sb\nend\n\nfunction main()\n local combos = {\n { 1, 2, 3},\n { 0, 1, 2, 3 },\n { 1, 0, 3, 4 },\n { 1, 2, 0 },\n { 0, 0, 0 },\n { 0 },\n { 1, 1, 1 },\n { -1, -1, -1 },\n { -1, -2, 0, -3 },\n { -1 }\n }\n\n for i,c in pairs(combos) do\n local arr = t2s(c)\n print(string.format(\"%15s -> %s\", arr, linearCombo(c)))\n end\nend\n\nmain()"} {"title": "Diversity prediction theorem", "language": "Lua from C++", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "function square(x)\n return x * x\nend\n\nfunction mean(a)\n local s = 0\n local c = 0\n for i,v in pairs(a) do\n s = s + v\n c = c + 1\n end\n return s / c\nend\n\nfunction averageSquareDiff(a, predictions)\n local results = {}\n for i,x in pairs(predictions) do\n table.insert(results, square(x - a))\n end\n return mean(results)\nend\n\nfunction diversityTheorem(truth, predictions)\n local average = mean(predictions)\n print(\"average-error: \" .. averageSquareDiff(truth, predictions))\n print(\"crowd-error: \" .. square(truth - average))\n print(\"diversity: \" .. averageSquareDiff(average, predictions))\nend\n\nfunction main()\n diversityTheorem(49, {48, 47, 51})\n diversityTheorem(49, {48, 47, 51, 42})\nend\n\nmain()"} {"title": "Dot product", "language": "Lua", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "function dotprod(a, b)\n local ret = 0\n for i = 1, #a do\n ret = ret + a[i] * b[i]\n end\n return ret\nend\n\nprint(dotprod({1, 3, -5}, {4, -2, 1}))"} {"title": "Draw a clock", "language": "Lua", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "==={{libheader|L\u00d6VE}}===\nSeveral nice clocks in the [http://love2d.org/forums/viewtopic.php?f=5&t=77346 L\u00d6VE-forum]\n\n\n"} {"title": "Draw a rotating cube", "language": "Lua", "task": "Task\nDraw a rotating cube. \n\nIt should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.\n\n\n;Related tasks\n* Draw a cuboid\n* write language name in 3D ASCII\n\n", "solution": "local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt\nlocal bitmap = {\n init = function(self, w, h, value)\n self.w, self.h, self.pixels = w, h, {}\n for y=1,h do self.pixels[y]={} end\n self:clear(value)\n end,\n clear = function(self, value)\n for y=1,self.h do\n for x=1,self.w do\n self.pixels[y][x] = value or \" \"\n end\n end\n end,\n set = function(self, x, y, value)\n x,y = floor(x),floor(y)\n if x>0 and y>0 and x<=self.w and y<=self.h then\n self.pixels[y][x] = value or \"#\"\n end\n end,\n line = function(self, x1, y1, x2, y2, c)\n x1,y1,x2,y2 = floor(x1),floor(y1),floor(x2),floor(y2)\n local dx, sx = abs(x2-x1), x1dy and dx or -dy)/2)\n while(true) do\n self:set(x1, y1, c)\n if (x1==x2 and y1==y2) then break end\n if (err > -dx) then\n err, x1 = err-dy, x1+sx\n if (x1==x2 and y1==y2) then\n self:set(x1, y1, c)\n break\n end\n end\n if (err < dy) then\n err, y1 = err+dx, y1+sy\n end\n end\n end, \n render = function(self)\n for y=1,self.h do\n print(table.concat(self.pixels[y]))\n end\n end,\n}\nscreen = {\n clear = function()\n os.execute(\"cls\") -- or? os.execute(\"clear\"), or? io.write(\"\\027[2J\\027[H\"), or etc?\n end,\n}\nlocal camera = { fl = 2.5 }\nlocal L = 0.5\nlocal cube = {\n verts = { {L,L,L}, {L,-L,L}, {-L,-L,L}, {-L,L,L}, {L,L,-L}, {L,-L,-L}, {-L,-L,-L}, {-L,L,-L} },\n edges = { {1,2}, {2,3}, {3,4}, {4,1}, {5,6}, {6,7}, {7,8}, {8,5}, {1,5}, {2,6}, {3,7}, {4,8} },\n rotate = function(self, rx, ry)\n local cx,sx = cos(rx),sin(rx)\n local cy,sy = cos(ry),sin(ry)\n for i,v in ipairs(self.verts) do\n local x,y,z = v[1],v[2],v[3]\n v[1], v[2], v[3] = x*cx-z*sx, y*cy-x*sx*sy-z*cx*sy, x*sx*cy+y*sy+z*cx*cy\n end\n end,\n}\nlocal renderer = {\n render = function(self, shape, camera, bitmap)\n local fl = camera.fl\n local ox, oy = bitmap.w/2, bitmap.h/2\n local mx, my = bitmap.w/2, bitmap.h/2\n local rpverts = {}\n for i,v in ipairs(shape.verts) do\n local x,y,z = v[1],v[2],v[3]\n local px = ox + mx * (fl*x)/(fl-z)\n local py = oy + my * (fl*y)/(fl-z)\n rpverts[i] = { px,py }\n end\n for i,e in ipairs(shape.edges) do\n local v1, v2 = rpverts[e[1]], rpverts[e[2]]\n bitmap:line( v1[1], v1[2], v2[1], v2[2], \"\u2588\u2588\" )\n end\n end\n}\n--\nbitmap:init(40,40)\ncube:rotate(pi/4, atan(sqrt(2)))\nfor i=1,60 do\n cube:rotate(pi/60,0)\n bitmap:clear(\"\u00b7\u00b7\")\n renderer:render(cube, camera, bitmap)\n screen:clear()\n bitmap:render()\nend"} {"title": "Draw a sphere", "language": "Lua 5.1.4", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "require (\"math\")\n\nshades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}\n\nfunction normalize (vec)\n len = math.sqrt(vec[1]^2 + vec[2]^2 + vec[3]^2)\n return {vec[1]/len, vec[2]/len, vec[3]/len}\nend\n\nlight = normalize{30, 30, -50}\n\nfunction dot (vec1, vec2)\n d = vec1[1]*vec2[1] + vec1[2]*vec2[2] + vec1[3]*vec2[3]\n return d < 0 and -d or 0\nend\n\nfunction draw_sphere (radius, k, ambient)\n for i = math.floor(-radius),-math.floor(-radius) do\n x = i + .5\n local line = ''\n for j = math.floor(-2*radius),-math.floor(-2*radius) do\n y = j / 2 + .5\n if x^2 + y^2 <= radius^2 then\n vec = normalize{x, y, math.sqrt(radius^2 - x^2 - y^2)}\n b = dot(light,vec) ^ k + ambient\n intensity = math.floor ((1 - b) * #shades)\n line = line .. (shades[intensity] or shades[1])\n else\n line = line .. ' '\n end\n end\n print (line)\n end\nend\n\ndraw_sphere (20, 4, 0.1)\ndraw_sphere (10, 2, 0.4)"} {"title": "Dutch national flag problem", "language": "Lua", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "-- \"1. Generate a randomized order of balls..\"\nmath.randomseed(os.time())\nN, balls, colors = 10, {}, { \"red\", \"white\", \"blue\" }\nfor i = 1, N do balls[i] = colors[math.random(#colors)] end\n-- \"..ensuring that they are not in the order of the Dutch national flag.\"\norder = { red=1, white=2, blue=3 }\nfunction issorted(t)\n for i = 2, #t do\n if order[t[i]] < order[t[i-1]] then return false end\n end\n return true\nend\nlocal function shuffle(t)\n for i = #t, 2, -1 do\n local j = math.random(i)\n t[i], t[j] = t[j], t[i]\n end\nend\nwhile issorted(balls) do shuffle(balls) end\nprint(\"RANDOM: \"..table.concat(balls,\",\"))\n\n-- \"2. Sort the balls in a way idiomatic to your language.\"\ntable.sort(balls, function(a, b) return order[a] < order[b] end)\n\n-- \"3. Check the sorted balls are in the order of the Dutch national flag.\"\nprint(\"SORTED: \"..table.concat(balls,\",\"))\nprint(issorted(balls) and \"Properly sorted.\" or \"IMPROPERLY SORTED!!\")"} {"title": "Eban numbers", "language": "Lua from lang", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count\n:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count\n:::* show a count of all eban numbers up and including '''10,000'''\n:::* show a count of all eban numbers up and including '''100,000'''\n:::* show a count of all eban numbers up and including '''1,000,000'''\n:::* show a count of all eban numbers up and including '''10,000,000'''\n:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "function makeInterval(s,e,p)\n return {start=s, end_=e, print_=p}\nend\n\nfunction main()\n local intervals = {\n makeInterval( 2, 1000, true),\n makeInterval(1000, 4000, true),\n makeInterval( 2, 10000, false),\n makeInterval( 2, 1000000, false),\n makeInterval( 2, 10000000, false),\n makeInterval( 2, 100000000, false),\n makeInterval( 2, 1000000000, false)\n }\n for _,intv in pairs(intervals) do\n if intv.start == 2 then\n print(\"eban numbers up to and including \" .. intv.end_ .. \":\")\n else\n print(\"eban numbers between \" .. intv.start .. \" and \" .. intv.end_ .. \" (inclusive)\")\n end\n\n local count = 0\n for i=intv.start,intv.end_,2 do\n local b = math.floor(i / 1000000000)\n local r = i % 1000000000\n local m = math.floor(r / 1000000)\n r = i % 1000000\n local t = math.floor(r / 1000)\n r = r % 1000\n if m >= 30 and m <= 66 then m = m % 10 end\n if t >= 30 and t <= 66 then t = t % 10 end\n if r >= 30 and r <= 66 then r = r % 10 end\n if b == 0 or b == 2 or b == 4 or b == 6 then\n if m == 0 or m == 2 or m == 4 or m == 6 then\n if t == 0 or t == 2 or t == 4 or t == 6 then\n if r == 0 or r == 2 or r == 4 or r == 6 then\n if intv.print_ then io.write(i .. \" \") end\n count = count + 1\n end\n end\n end\n end\n end\n\n if intv.print_ then\n print()\n end\n print(\"count = \" .. count)\n print()\n end\nend\n\nmain()"} {"title": "Egyptian division", "language": "Lua from Python", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "function egyptian_divmod(dividend,divisor)\n local pwrs, dbls = {1}, {divisor}\n while dbls[#dbls] <= dividend do\n table.insert(pwrs, pwrs[#pwrs] * 2)\n table.insert(dbls, pwrs[#pwrs] * divisor)\n end\n local ans, accum = 0, 0\n\n for i=#pwrs-1,1,-1 do\n if accum + dbls[i] <= dividend then\n accum = accum + dbls[i]\n ans = ans + pwrs[i]\n end\n end\n\n return ans, math.abs(accum - dividend)\nend\n\nlocal i, j = 580, 34\nlocal d, m = egyptian_divmod(i, j)\nprint(i..\" divided by \"..j..\" using the Egyptian method is \"..d..\" remainder \"..m)"} {"title": "Elementary cellular automaton", "language": "Lua", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "local CA = {\n state = \"..............................#..............................\",\n bstr = { [0]=\"...\", \"..#\", \".#.\", \".##\", \"#..\", \"#.#\", \"##.\", \"###\" },\n new = function(self, rule)\n local inst = setmetatable({rule=rule}, self)\n for b = 0,7 do\n inst[inst.bstr[b]] = rule%2==0 and \".\" or \"#\"\n rule = math.floor(rule/2)\n end\n return inst\n end,\n evolve = function(self)\n local n, state, newstate = #self.state, self.state, \"\"\n for i = 1,n do\n local nbhd = state:sub((i+n-2)%n+1,(i+n-2)%n+1) .. state:sub(i,i) .. state:sub(i%n+1,i%n+1)\n newstate = newstate .. self[nbhd]\n end\n self.state = newstate\n end,\n}\nCA.__index = CA\nca = { CA:new(18), CA:new(30), CA:new(73), CA:new(129) }\nfor i = 1, 63 do\n print(string.format(\"%-66s%-66s%-66s%-61s\", ca[1].state, ca[2].state, ca[3].state, ca[4].state))\n for j = 1, 4 do ca[j]:evolve() end\nend"} {"title": "Empty directory", "language": "Lua", "task": "Starting with a path to some directory, determine whether the directory is empty.\n\nAn empty directory contains no files nor subdirectories. \nWith [[Unix]] or [[Windows]] systems, every directory contains an entry for \".\" and almost every directory contains \"..\" (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "function scandir(directory)\n\tlocal i, t, popen = 0, {}, io.popen\n\tlocal pfile = popen('ls -a \"'..directory..'\"')\n\tfor filename in pfile:lines() do\n\t\tif filename ~= '.' and filename ~= '..' then\n\t\t\ti = i + 1\n\t\t\tt[i] = filename\n\t\tend\n\tend\n\tpfile:close()\n\treturn t\nend\n\nfunction isemptydir(directory)\n\treturn #scandir(directory) == 0\nend\n"} {"title": "Empty string", "language": "Lua", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "-- create an empty string 3 different ways\nstr = \"\"\nstr = ''\nstr = [[]]\n\n-- test for empty string\nif str == \"\" then\n print \"The string is empty\"\nend\n\n-- test for nonempty string\nif str ~= \"\" then\n print \"The string is not empty\"\nend\n\n-- several different ways to check the string's length\nif string.len(str) == 0 then\n print \"The library function says the string is empty.\"\nend\nif str:len() == 0 then\n print \"The method call says the string is empty.\"\nend\nif #str == 0 then\n print \"The unary operator says the string is empty.\"\nend\n\n"} {"title": "Entropy/Narcissist", "language": "Lua", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "function getFile (filename)\n local inFile = io.open(filename, \"r\")\n local fileContent = inFile:read(\"*all\")\n inFile:close()\n return fileContent\nend\n\nfunction log2 (x) return math.log(x) / math.log(2) end\n \nfunction entropy (X)\n local N, count, sum, i = X:len(), {}, 0\n for char = 1, N do\n i = X:sub(char, char)\n if count[i] then\n count[i] = count[i] + 1\n else\n count[i] = 1\n end\n end\n for n_i, count_i in pairs(count) do\n sum = sum + count_i / N * log2(count_i / N)\n end\n return -sum\nend\n\nprint(entropy(getFile(arg[0])))"} {"title": "Equilibrium index", "language": "Lua", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "function array_sum(t)\n assert(type(t) == \"table\", \"t must be a table!\")\n local sum = 0\n for i=1, #t do sum = sum + t[i] end\n return sum\nend\n\nfunction equilibrium_index(t)\n assert(type(t) == \"table\", \"t must be a table!\")\n local left, right, ret = 0, array_sum(t), -1\n for i,j in pairs(t) do\n right = right - j\n if left == right then\n\t ret = i\n\t break\n end\n left = left + j\n end\n return ret\nend\n\nprint(equilibrium_index({-7, 1, 5, 2, -4, 3, 0}))\n\n"} {"title": "Esthetic numbers", "language": "Lua from C++", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "function to(n, b)\n local BASE = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n if n == 0 then\n return \"0\"\n end\n\n local ss = \"\"\n while n > 0 do\n local idx = (n % b) + 1\n n = math.floor(n / b)\n ss = ss .. BASE:sub(idx, idx)\n end\n return string.reverse(ss)\nend\n\nfunction isEsthetic(n, b)\n function uabs(a, b)\n if a < b then\n return b - a\n end\n return a - b\n end\n\n if n == 0 then\n return false\n end\n local i = n % b\n n = math.floor(n / b)\n while n > 0 do\n local j = n % b\n if uabs(i, j) ~= 1 then\n return false\n end\n n = math.floor(n / b)\n i = j\n end\n return true\nend\n\nfunction listEsths(n, n2, m, m2, perLine, all)\n local esths = {}\n function dfs(n, m, i)\n if i >= n and i <= m then\n table.insert(esths, i)\n end\n if i == 0 or i > m then\n return\n end\n local d = i % 10\n local i1 = 10 * i + d - 1\n local i2 = i1 + 2\n if d == 0 then\n dfs(n, m, i2)\n elseif d == 9 then\n dfs(n, m, i1)\n else\n dfs(n, m, i1)\n dfs(n, m, i2)\n end\n end\n\n for i=0,9 do\n dfs(n2, m2, i)\n end\n local le = #esths\n print(string.format(\"Base 10: %s esthetic numbers between %s and %s:\", le, math.floor(n), math.floor(m)))\n if all then\n for c,esth in pairs(esths) do\n io.write(esth..\" \")\n if c % perLine == 0 then\n print()\n end\n end\n print()\n else\n for i=1,perLine do\n io.write(esths[i] .. \" \")\n end\n print(\"\\n............\")\n for i = le - perLine + 1, le do\n io.write(esths[i] .. \" \")\n end\n print()\n end\n print()\nend\n\nfor b=2,16 do\n print(string.format(\"Base %d: %dth to %dth esthetic numbers:\", b, 4 * b, 6 * b))\n local n = 1\n local c = 0\n while c < 6 * b do\n if isEsthetic(n, b) then\n c = c + 1\n if c >= 4 * b then\n io.write(to(n, b)..\" \")\n end\n end\n n = n + 1\n end\n print()\nend\nprint()\n\n-- the following all use the obvious range limitations for the numbers in question\nlistEsths(1000, 1010, 9999, 9898, 16, true)\nlistEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true)\nlistEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false)\nlistEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false)\nlistEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false)"} {"title": "Euler's identity", "language": "Lua", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "local c = {\n new = function(s,r,i) s.__index=s return setmetatable({r=r, i=i}, s) end,\n add = function(s,o) return s:new(s.r+o.r, s.i+o.i) end,\n exp = function(s) local e=math.exp(s.r) return s:new(e*math.cos(s.i), e*math.sin(s.i)) end,\n mul = function(s,o) return s:new(s.r*o.r+s.i*o.i, s.r*o.i+s.i*o.r) end\n}\nlocal i = c:new(0, 1)\nlocal pi = c:new(math.pi, 0)\nlocal one = c:new(1, 0)\nlocal zero = i:mul(pi):exp():add(one)\nprint(string.format(\"e^(i*pi)+1 is approximately zero: %.18g%+.18gi\", zero.r, zero.i))"} {"title": "Euler's sum of powers conjecture", "language": "Lua", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "-- Fast table search (only works if table values are in order)\nfunction binarySearch (t, n)\n local start, stop, mid = 1, #t\n while start < stop do\n mid = math.floor((start + stop) / 2)\n if n == t[mid] then\n return mid\n elseif n < t[mid] then\n stop = mid - 1\n else\n start = mid + 1\n end\n end\n return nil\nend\n\n-- Test Euler's sum of powers conjecture\nfunction euler (limit)\n local pow5, sum = {}\n for i = 1, limit do pow5[i] = i^5 end\n for x0 = 1, limit do\n for x1 = 1, x0 do\n for x2 = 1, x1 do\n for x3 = 1, x2 do\n sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3]\n if binarySearch(pow5, sum) then\n print(x0 .. \"^5 + \" .. x1 .. \"^5 + \" .. x2 .. \"^5 + \" .. x3 .. \"^5 = \" .. sum^(1/5) .. \"^5\")\n return true\n end\n end\n end\n end\n end\n return false\nend\n\n-- Main procedure\nif euler(249) then\n print(\"Time taken: \" .. os.clock() .. \" seconds\")\nelse\n print(\"Looks like he was right after all...\")\nend"} {"title": "Even or odd", "language": "Lua", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "-- test for even number\nif n % 2 == 0 then\n print \"The number is even\"\nend\n\n-- test for odd number\nif not (n % 2 == 0) then\n print \"The number is odd\"\nend"} {"title": "Evolutionary algorithm", "language": "Lua 5.1+", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "local target = \"METHINKS IT IS LIKE A WEASEL\"\nlocal alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ \"\nlocal c, p = 100, 0.06\n\nlocal function fitness(s)\n\tlocal score = #target\n\tfor i = 1,#target do\n\t\tif s:sub(i,i) == target:sub(i,i) then score = score - 1 end\n\tend\n\treturn score\nend\n\nlocal function mutate(s, rate)\n\tlocal result, idx = \"\"\n\tfor i = 1,#s do\n\t\tif math.random() < rate then\n\t\t\tidx = math.random(#alphabet)\n\t\t\tresult = result .. alphabet:sub(idx,idx)\n\t\telse\n\t\t\tresult = result .. s:sub(i,i)\n\t\tend\n\tend\n\treturn result, fitness(result)\nend\n\nlocal function randomString(len)\n\tlocal result, idx = \"\"\n\tfor i = 1,len do\n\t\tidx = math.random(#alphabet)\n\t\tresult = result .. alphabet:sub(idx,idx)\n\tend\n\treturn result\nend\n\nlocal function printStep(step, s, fit)\n\tprint(string.format(\"%04d: \", step) .. s .. \" [\" .. fit ..\"]\")\nend\n\nmath.randomseed(os.time())\nlocal parent = randomString(#target)\nprintStep(0, parent, fitness(parent))\n\nlocal step = 0\nwhile parent ~= target do\n\tlocal bestFitness, bestChild, child, fitness = #target + 1\n\tfor i = 1,c do\n\t\tchild, fitness = mutate(parent, p)\n\t\tif fitness < bestFitness then bestFitness, bestChild = fitness, child end\n\tend\n\tparent, step = bestChild, step + 1\n\tprintStep(step, parent, bestFitness)\nend"} {"title": "Executable library", "language": "Lua", "task": "The general idea behind an executable library is to create a library \nthat when used as a library does one thing; \nbut has the ability to be run directly via command line. \nThus the API comes with a CLI in the very same source code file.\n\n'''Task detail'''\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:\n:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n'''Notes:''' \n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.\n* Interpreters are present in the runtime environment.\n\n", "solution": "#!/usr/bin/env luajit\nbit32=bit32 or bit\nlocal lib={\n\thailstone=function(n)\n\t\tlocal seq={n}\n\t\twhile n>1 do \n\t\t\tn=bit32.band(n,1)==1 and 3*n+1 or n/2\n\t\t\tseq[#seq+1]=n\n\t\tend\n\t\treturn seq\n\tend\n}\n\nif arg[0] and arg[0]:match(\"hailstone.lua\") then\n\tlocal function printf(fmt, ...) io.write(string.format(fmt, ...)) end\n\tlocal seq=lib.hailstone(27)\n\tprintf(\"27 has %d numbers in sequence:\\n\",#seq)\n\tfor _,i in ipairs(seq) do\n\t\tprintf(\"%d \", i)\n\tend\n\tprintf(\"\\n\")\nelse\n\treturn lib\nend\n"} {"title": "Execute Brain****", "language": "Lua", "task": "Brainf***}}\nRCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. \n\nBelow are links to each of the versions of RCBF.\n\nAn implementation need only properly implement the following instructions:\n{| class=\"wikitable\"\n!Command\n!Description\n|-\n| style=\"text-align:center\"| > || Move the pointer to the right\n|-\n| style=\"text-align:center\"| < || Move the pointer to the left\n|-\n| style=\"text-align:center\"| + || Increment the memory cell under the pointer\n|-\n| style=\"text-align:center\"| - || Decrement the memory cell under the pointer\n|-\n| style=\"text-align:center\"| . || Output the character signified by the cell at the pointer\n|-\n| style=\"text-align:center\"| , || Input a character and store it in the cell at the pointer\n|-\n| style=\"text-align:center\"| [ || Jump past the matching ] if the cell under the pointer is 0\n|-\n| style=\"text-align:center\"| ] || Jump back to the matching [ if the cell under the pointer is nonzero\n|}\nAny cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.\n\n", "solution": "local funs = {\n['>'] = 'ptr = ptr + 1; ',\n['<'] = 'ptr = ptr - 1; ',\n['+'] = 'mem[ptr] = mem[ptr] + 1; ',\n['-'] = 'mem[ptr] = mem[ptr] - 1; ',\n['['] = 'while mem[ptr] ~= 0 do ',\n[']'] = 'end; ',\n['.'] = 'io.write(string.char(mem[ptr])); ',\n[','] = 'mem[ptr] = (io.read(1) or \"\\\\0\"):byte(); ',\n}\n\nlocal prog = [[\n local mem = setmetatable({}, { __index = function() return 0 end})\n local ptr = 1\n]]\n\nlocal source = io.read('*all')\n\nfor p = 1, #source do\n local snippet = funs[source:sub(p,p)]\n if snippet then prog = prog .. snippet end\nend\n\nload(prog)()"} {"title": "Execute Computer/Zero", "language": "Lua", "task": "Computer/zero Assembly}}\n\n;Task:\nCreate a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs \"2+2\" and \"7*8\" found there.\n\n:* The virtual machine \"bytecode\" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.\n:* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.\n\n;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.\n\n\n\n", "solution": "vmz = {\n pc = 0,\n acc = 0,\n mem = { [0]=0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 },\n b2oa = function(byte) return math.floor(byte / 32), byte % 32 end,\n boot = function(self) self.pc, self.acc = 0, 0 for pc=0,31 do self.mem[pc]=0 end return self end,\n load = function(self, bytes) for pc = 0, 31 do self.mem[pc]=bytes[pc] or 0 end return self end,\n clam = function(n) if n<0 then n=n+256 elseif n>255 then n=n-256 end return n end,\n opfn = {[0]=\n function(self,addr) self.pc=self.pc+1 return true end, -- NOP\n function(self,addr) self.acc=self.mem[addr] self.pc=self.pc+1 return true end, -- LDA\n function(self,addr) self.mem[addr]=self.acc self.pc=self.pc+1 return true end, -- STA\n function(self,addr) self.acc=self.clam(self.acc+self.mem[addr]) self.pc=self.pc+1 return true end, -- ADD\n function(self,addr) self.acc=self.clam(self.acc-self.mem[addr]) self.pc=self.pc+1 return true end, -- SUB\n function(self,addr) if (self.acc==0) then self.pc=addr else self.pc=self.pc+1 end return true end, -- BRZ\n function(self,addr) self.pc=addr return true end, -- JMP\n function(self,addr) self.pc=self.pc+1 return false end, -- STP\n },\n step = function(self)\n local oper, addr = self.b2oa(self.mem[self.pc])\n return self.opfn[oper](self,addr)\n end,\n exec = function(self)\n while self.pc < 32 and self:step() do end\n return self\n end,\n}\n-- object code derived from js sim code\nprint(\"2 + 2 = \" .. vmz:boot():load({[0]=35,100,224,2,2}):exec().acc)\nprint(\"7 x 8 = \" .. vmz:boot():load({[0]=44,106,76,43,141,75,168,192,44,224,8,7,0,1}):exec().acc)"} {"title": "Execute HQ9+", "language": "Lua", "task": "Implement a ''' [[HQ9+]] ''' interpreter or compiler.\n\n", "solution": "function runCode( code )\n local acc, lc = 0\n for i = 1, #code do\n lc = code:sub( i, i ):upper()\n if lc == \"Q\" then print( lc )\n elseif lc == \"H\" then print( \"Hello, World!\" )\n elseif lc == \"+\" then acc = acc + 1\n elseif lc == \"9\" then\n for j = 99, 1, -1 do\n if j > 1 then\n print( string.format( \"%d bottles of beer on the wall\\n%d bottles of beer\\nTake one down, pass it around\\n%d bottles of beer on the wall\\n\", j, j, j - 1 ) )\n else\n print( \"1 bottle of beer on the wall\\n1 bottle of beer\\nTake one down and pass it around\\nno more bottles of beer on the wall\\n\\n\"..\n \"No more bottles of beer on the wall\\nNo more bottles of beer\\n\"..\n \"Go to the store and buy some more\\n99 bottles of beer on the wall.\\n\" )\n end\n end\n end\n end\nend\n"} {"title": "Exponentiation order", "language": "Lua", "task": "This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.\n\n(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)\n\n\n;Task requirements\nShow the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nUsing whatever operator or syntax your language supports (if any), show the results in three lines (with identification):\n \n::::* 5**3**2 \n::::* (5**3)**2\n::::* 5**(3**2)\n\n\nIf there are other methods (or formats) of multiple exponentiations, show them as well. \n\n\n;See also:\n* MathWorld entry: exponentiation\n\n\n;Related tasks:\n* exponentiation operator\n* arbitrary-precision integers (included)\n* [[Exponentiation with infix operators in (or operating on) the base]]\n\n", "solution": "print(\"5^3^2 = \" .. 5^3^2)\nprint(\"(5^3)^2 = \" .. (5^3)^2)\nprint(\"5^(3^2) = \" .. 5^(3^2))"} {"title": "Exponentiation with infix operators in (or operating on) the base", "language": "Lua", "task": "(Many programming languages, especially those with extended-precision integer arithmetic, usually\nsupport one of **, ^, | or some such for exponentiation.)\n\n\nSome languages treat/honor infix operators when performing exponentiation (raising\nnumbers to some power by the language's exponentiation operator, if the computer\nprogramming language has one).\n\n\nOther programming languages may make use of the '''POW''' or some other BIF\n ('''B'''uilt-'''I'''n '''F'''function), or some other library service.\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nThis task will deal with the case where there is some form of an ''infix operator'' operating\nin (or operating on) the base.\n\n\n;Example:\nA negative five raised to the 3rd power could be specified as:\n -5 ** 3 or as\n -(5) ** 3 or as\n (-5) ** 3 or as something else\n\n\n(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).\n\n\n;Task:\n:* compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.\n:* Raise the following numbers (integer or real):\n:::* -5 and\n:::* +5\n:* to the following powers:\n:::* 2nd and\n:::* 3rd\n:* using the following expressions (if applicable in your language):\n:::* -x**p\n:::* -(x)**p\n:::* (-x)**p\n:::* -(x**p)\n:* Show here (on this page) the four (or more) types of symbolic expressions for each number and power.\n\n\nTry to present the results in the same format/manner as the other programming entries to make any differences apparent.\n\n\nThe variables may be of any type(s) that is/are applicable in your language.\n\n\n;Related tasks:\n* [[Exponentiation order]]\n* [[Exponentiation operator]]\n* [[Arbitrary-precision integers (included)]]\n* [[Parsing/RPN to infix conversion]]\n* [[Operator precedence]]\n\n;References:\n* Wikipedia: Order of operations in Programming languages\n\n", "solution": "mathtype = math.type or type -- polyfill <5.3\nfunction test(xs, ps)\n for _,x in ipairs(xs) do\n for _,p in ipairs(ps) do\n print(string.format(\"%2.f %7s %2.f %7s %4.f %4.f %4.f %4.f\", x, mathtype(x), p, mathtype(p), -x^p, -(x)^p, (-x)^p, -(x^p)))\n end\n end\nend\nprint(\" x type(x) p type(p) -x^p -(x)^p (-x)^p -(x^p)\")\nprint(\"-- ------- -- ------- ------ ------ ------ ------\")\ntest( {-5.,5.}, {2.,3.} ) -- \"float\" (or \"number\" if <5.3)\nif math.type then -- if >=5.3\n test( {-5,5}, {2,3} ) -- \"integer\"\nend"} {"title": "Extend your language", "language": "Lua", "task": "{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.\n\nIf your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:\n\nOccasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are \"true\"). In a C-like language this could look like the following:\n\n if (condition1isTrue) {\n if (condition2isTrue)\n bothConditionsAreTrue();\n else\n firstConditionIsTrue();\n }\n else if (condition2isTrue)\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nBesides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.\n\nThis can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:\n\n if2 (condition1isTrue) (condition2isTrue)\n bothConditionsAreTrue();\n else1\n firstConditionIsTrue();\n else2\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nPick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.\n", "solution": "-- Extend your language, in Lua, 6/17/2020 db\n-- not to be taken seriously, ridiculous, impractical, esoteric, obscure, arcane ... but it works\n\n-------------------\n-- IMPLEMENTATION:\n-------------------\n\nfunction if2(cond1, cond2)\n return function(code)\n code = code:gsub(\"then2\", \"[3]=load[[\")\n code = code:gsub(\"else1\", \"]],[2]=load[[\")\n code = code:gsub(\"else2\", \"]],[1]=load[[\")\n code = code:gsub(\"neither\", \"]],[0]=load[[\")\n code = \"return {\" .. code .. \"]]}\"\n local block, err = load(code)\n if (err) then error(\"syntax error in if2 statement: \"..err) end\n local tab = block()\n tab[(cond1 and 2 or 0) + (cond2 and 1 or 0)]()\n end\nend\n\n----------\n-- TESTS:\n----------\n\nfor i = 1, 2 do\n for j = 1, 2 do\n print(\"i=\"..i..\" j=\"..j)\n\n if2 ( i==1, j==1 )[[ then2\n print(\"both conditions are true\")\n else1\n print(\"first is true, second is false\")\n else2\n print(\"first is false, second is true\")\n neither\n print(\"both conditions are false\")\n ]]\n\n end\nend"} {"title": "Extreme floating point values", "language": "Lua", "task": "The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.\n\nThe task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. \n\nPrint the values of these variables if possible; and show some arithmetic with these values and variables. \n\nIf your language can directly enter these extreme floating point values then show it.\n\n\n;See also:\n* What Every Computer Scientist Should Know About Floating-Point Arithmetic\n\n\n;Related tasks:\n* [[Infinity]]\n* [[Detect division by zero]]\n* [[Literals/Floating point]]\n\n", "solution": "local inf=math.huge\nlocal minusInf=-math.huge\nlocal NaN=0/0\nlocal negativeZeroSorta=-1E-240\n"} {"title": "FASTA format", "language": "Lua", "task": "In FASTA. \n\nA FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.\n\n\n;Task:\nWrite a program that reads a FASTA file such as:\n\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n", "solution": "local file = io.open(\"input.txt\",\"r\")\nlocal data = file:read(\"*a\")\nfile:close()\n\nlocal output = {}\nlocal key = nil\n\n-- iterate through lines\nfor line in data:gmatch(\"(.-)\\r?\\n\") do\n\tif line:match(\"%s\") then\n\t\terror(\"line contained space\")\n\telseif line:sub(1,1) == \">\" then\n\t\tkey = line:sub(2)\n\t\t-- if key already exists, append to the previous input\n\t\toutput[key] = output[key] or \"\"\n\telseif key ~= nil then\n\t\toutput[key] = output[key] .. line\n\tend\nend\n\n-- print result\nfor k,v in pairs(output) do\n\tprint(k..\": \"..v)\nend"} {"title": "Faces from a mesh", "language": "Lua", "task": "A mesh defining a surface has uniquely numbered vertices, and named, \nsimple-polygonal faces described usually by an ordered list of edge numbers \ngoing around the face, \n\n\nFor example:\nExternal image of two faces\nRough textual version without edges:\n\n\n 1 \n 17\n 7 A\n B\n\n 11 \n 23\n\n\n\n* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or\nany of all the rotations of those ordered vertices.\n 1 \n \n 7 A\n \n\n 11\n\n* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any \nof their rotations.\n1 \n 17\n\n B\n\n 11 \n 23\n\nLet's call the above the '''perimeter format''' as it traces around the perimeter.\n\n;A second format:\nA separate algorithm returns polygonal faces consisting of a face name and an unordered \nset of edge definitions for each face.\n* A single edge is described by the vertex numbers at its two ends, always in \nascending order.\n* All edges for the face are given, but in an undefined order.\n\nFor example face A could be described by the edges (1, 11), (7, 11), and (1, 7)\n(The order of each vertex number in an edge is ascending, but the order in \nwhich the edges are stated is arbitrary).\n\nSimilarly face B could be described by the edges (11, 23), (1, 17), (17, 23),\nand (1, 11) in arbitrary order of the edges. \n\nLet's call this second format the '''edge format'''.\n\n\n\n;Task:\n'''1.''' Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:\n Q: (8, 1, 3)\n R: (1, 3, 8)\n\n U: (18, 8, 14, 10, 12, 17, 19)\n V: (8, 14, 10, 12, 17, 19, 18)\n\n'''2.''' Write a routine and use it to transform the following faces from edge to perimeter format.\n E: {(1, 11), (7, 11), (1, 7)}\n F: {(11, 23), (1, 17), (17, 23), (1, 11)}\n G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}\n H: {(1, 3), (9, 11), (3, 11), (1, 11)}\n\n\nShow your output here.\n\n", "solution": "-- support\nfunction T(t) return setmetatable(t, {__index=table}) end\ntable.eql = function(t,u) if #t~=#u then return false end for i=1,#t do if t[i]~=u[i] then return false end end return true end\ntable.rol = function(t,n) local s=T{} for i=1,#t do s[i]=t[(i+n-1)%#t+1] end return s end\ntable.rev = function(t) local s=T{} for i=1,#t do s[#t-i+1]=t[i] end return s end\n\n-- 1\nfunction pfeq(pf1, pf2)\n if #pf1 ~= #pf2 then return false end -- easy case\n for w = 0,1 do -- exhaustive cases\n local pfw = pf1 -- w:winding\n if w==1 then pfw=pfw:rev() end\n for r = 0,#pfw do\n local pfr = pfw -- r:rotate\n if r>0 then pfr=pfr:rol(r) end\n if pf2:eql(pfr) then return true end\n end\n end\n return false\nend\n\nQ = T{8, 1, 3}\nR = T{1, 3, 8}\nU = T{18, 8, 14, 10, 12, 17, 19}\nV = T{8, 14, 10, 12, 17, 19, 18}\nprint(\"pfeq(Q,R): \", pfeq(Q, R))\nprint(\"pfeq(U,V): \", pfeq(U, V))\n\n-- 2\nfunction ef2pf(ef)\n local pf, hse = T{}, T{} -- hse:hash of sorted edges\n for i,e in ipairs(ef) do table.sort(e) hse[e]=e end\n local function nexte(e)\n if not e then return ef[1] end\n for k,v in pairs(hse) do\n if e[2]==v[1] then return v end\n if e[2]==v[2] then v[1],v[2]=v[2],v[1] return v end\n end\n end\n local e = nexte()\n while e do\n pf[#pf+1] = e[1]\n hse[e] = nil\n e = nexte(e)\n end \n if #pf ~= #ef then pf=T{\"failed to convert edge format to perimeter format\"} end\n return pf\nend\n\nE = {{1, 11}, {7, 11}, {1, 7}}\nF = {{11, 23}, {1, 17}, {17, 23}, {1, 11}}\nG = {{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}}\nH = {{1, 3}, {9, 11}, {3, 11}, {1, 11}}\nprint(\"ef2pf(E): \", ef2pf(E):concat(\",\"))\nprint(\"ef2pf(F): \", ef2pf(F):concat(\",\"))\nprint(\"ef2pf(G): \", ef2pf(G):concat(\",\"))\nprint(\"ef2pf(H): \", ef2pf(H):concat(\",\"))"} {"title": "Fairshare between two and more", "language": "Lua from D", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "function turn(base, n)\n local sum = 0\n while n ~= 0 do\n local re = n % base\n n = math.floor(n / base)\n sum = sum + re\n end\n return sum % base\nend\n\nfunction fairShare(base, count)\n io.write(string.format(\"Base %2d:\", base))\n for i=1,count do\n local t = turn(base, i - 1)\n io.write(string.format(\" %2d\", t))\n end\n print()\nend\n\nfunction turnCount(base, count)\n local cnt = {}\n\n for i=1,base do\n cnt[i - 1] = 0\n end\n\n for i=1,count do\n local t = turn(base, i - 1)\n if cnt[t] ~= nil then\n cnt[t] = cnt[t] + 1\n else\n cnt[t] = 1\n end\n end\n\n local minTurn = count\n local maxTurn = -count\n local portion = 0\n for _,num in pairs(cnt) do\n if num > 0 then\n portion = portion + 1\n end\n if num < minTurn then\n minTurn = num\n end\n if maxTurn < num then\n maxTurn = num\n end\n end\n\n io.write(string.format(\" With %d people: \", base))\n if minTurn == 0 then\n print(string.format(\"Only %d have a turn\", portion))\n elseif minTurn == maxTurn then\n print(minTurn)\n else\n print(minTurn .. \" or \" .. maxTurn)\n end\nend\n\nfunction main()\n fairShare(2, 25)\n fairShare(3, 25)\n fairShare(5, 25)\n fairShare(11, 25)\n\n print(\"How many times does each get a turn in 50000 iterations?\")\n turnCount(191, 50000)\n turnCount(1377, 50000)\n turnCount(49999, 50000)\n turnCount(50000, 50000)\n turnCount(50001, 50000)\nend\n\nmain()"} {"title": "Farey sequence", "language": "Lua", "task": "The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.\n\nThe ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. \n\n\nEach Farey sequence:\n:::* starts with the value '''0''' (zero), denoted by the fraction \\frac{0}{1} \n:::* ends with the value '''1''' (unity), denoted by the fraction \\frac{1}{1}.\n\n\nThe Farey sequences of orders '''1''' to '''5''' are:\n\n:::: {\\bf\\it{F}}_1 = \\frac{0}{1}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_2 = \\frac{0}{1}, \\frac{1}{2}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_3 = \\frac{0}{1}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_4 = \\frac{0}{1}, \\frac{1}{4}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{3}{4}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_5 = \\frac{0}{1}, \\frac{1}{5}, \\frac{1}{4}, \\frac{1}{3}, \\frac{2}{5}, \\frac{1}{2}, \\frac{3}{5}, \\frac{2}{3}, \\frac{3}{4}, \\frac{4}{5}, \\frac{1}{1}\n\n;Task\n* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).\n* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.\n* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length (the number of fractions) of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 x n2 / \\pi2 \n\n;See also:\n* OEIS sequence A006842 numerators of Farey series of order 1, 2, *** \n* OEIS sequence A006843 denominators of Farey series of order 1, 2, *** \n* OEIS sequence A005728 number of fractions in Farey series of order n \n* MathWorld entry Farey sequence\n* Wikipedia entry Farey sequence\n\n", "solution": "-- Return farey sequence of order n\nfunction farey (n)\n local a, b, c, d, k = 0, 1, 1, n\n local farTab = {{a, b}}\n while c <= n do\n k = math.floor((n + b) / d)\n a, b, c, d = c, d, k * c - a, k * d - b\n table.insert(farTab, {a, b})\n end\n return farTab\nend\n\n-- Main procedure\nfor i = 1, 11 do\n io.write(i .. \": \")\n for _, frac in pairs(farey(i)) do io.write(frac[1] .. \"/\" .. frac[2] .. \" \") end\n print()\nend\nfor i = 100, 1000, 100 do print(i .. \": \" .. #farey(i) .. \" items\") end"} {"title": "Fast Fourier transform", "language": "Lua", "task": "Calculate the FFT (Fast Fourier Transform) of an input sequence.\n\nThe most general case allows for complex numbers at the input \nand results in a sequence of equal length, again of complex numbers. \nIf you need to restrict yourself to real numbers, the output should \nbe the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. \n\nThe classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "-- operations on complex number\ncomplex = {__mt={} }\n \nfunction complex.new (r, i) \n local new={r=r, i=i or 0} \n setmetatable(new,complex.__mt)\n return new\nend\n\nfunction complex.__mt.__add (c1, c2)\n return complex.new(c1.r + c2.r, c1.i + c2.i)\nend\n\nfunction complex.__mt.__sub (c1, c2)\n return complex.new(c1.r - c2.r, c1.i - c2.i)\nend\n\nfunction complex.__mt.__mul (c1, c2)\n return complex.new(c1.r*c2.r - c1.i*c2.i,\n c1.r*c2.i + c1.i*c2.r)\nend\n\nfunction complex.expi (i)\n return complex.new(math.cos(i),math.sin(i))\nend\n\nfunction complex.__mt.__tostring(c)\n return \"(\"..c.r..\",\"..c.i..\")\"\nend\n \n\n-- Cooley\u2013Tukey FFT (in-place, divide-and-conquer)\n-- Higher memory requirements and redundancy although more intuitive\nfunction fft(vect)\n local n=#vect\n if n<=1 then return vect end\n-- divide \n local odd,even={},{}\n for i=1,n,2 do\n odd[#odd+1]=vect[i]\n even[#even+1]=vect[i+1]\n end\n-- conquer\n fft(even);\n fft(odd);\n-- combine\n for k=1,n/2 do\n local t=even[k] * complex.expi(-2*math.pi*(k-1)/n)\n vect[k] = odd[k] + t;\n vect[k+n/2] = odd[k] - t;\n end\n return vect\nend\n\nfunction toComplex(vectr)\n vect={}\n for i,r in ipairs(vectr) do\n vect[i]=complex.new(r)\n end\n return vect\nend\n\n-- test\ndata = toComplex{1, 1, 1, 1, 0, 0, 0, 0};\n\n-- this works for old lua versions & luaJIT (depends on version!)\n-- print(\"orig:\", unpack(data))\n-- print(\"fft:\", unpack(fft(data)))\n\n-- Beginning with Lua 5.2 you have to write\nprint(\"orig:\", table.unpack(data))\nprint(\"fft:\", table.unpack(fft(data)))"} {"title": "Feigenbaum constant calculation", "language": "Lua", "task": "Calculate the Feigenbaum constant. \n\n\n;See:\n:* Details in the Wikipedia article: Feigenbaum constant.\n\n", "solution": "function leftShift(n,p)\n local r = n\n while p>0 do\n r = r * 2\n p = p - 1\n end\n return r\nend\n\n-- main\n\nlocal MAX_IT = 13\nlocal MAX_IT_J = 10\nlocal a1 = 1.0\nlocal a2 = 0.0\nlocal d1 = 3.2\n\nprint(\" i d\")\nfor i=2,MAX_IT do\n local a = a1 + (a1 - a2) / d1\n for j=1,MAX_IT_J do\n local x = 0.0\n local y = 0.0\n for k=1,leftShift(1,i) do\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n end\n a = a - x / y\n end\n d = (a1 - a2) / (a - a1)\n print(string.format(\"%2d %.8f\", i, d))\n d1 = d\n a2 = a1\n a1 = a\nend"} {"title": "Fibonacci n-step number sequences", "language": "Lua", "task": "These number series are an expansion of the ordinary [[Fibonacci sequence]] where:\n# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2\n# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3\n# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...\n# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \\sum_{i=1}^{(n)} {F_{k-i}^{(n)}}\n\nFor small values of n, Greek numeric prefixes are sometimes used to individually name each series.\n\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Fibonacci n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Series name !! Values\n|-\n| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\n|-\n| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\n|-\n| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\n|-\n| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\n|-\n| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\n|-\n| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\n|-\n| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\n|-\n| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\n|-\n| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n|}\n\nAllied sequences can be generated where the initial values are changed:\n: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.\n\n\n\n;Task:\n# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\n\n;Related tasks:\n* [[Fibonacci sequence]]\n* Wolfram Mathworld\n* [[Hofstadter Q sequence]]\n* [[Leonardo numbers]]\n\n\n;Also see:\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers\n\n", "solution": "function nStepFibs (seq, limit)\n local iMax, sum = #seq - 1\n while #seq < limit do\n sum = 0\n for i = 0, iMax do sum = sum + seq[#seq - i] end\n table.insert(seq, sum)\n end\n return seq\nend\n\nlocal fibSeqs = {\n {name = \"Fibonacci\", values = {1, 1} },\n {name = \"Tribonacci\", values = {1, 1, 2} },\n {name = \"Tetranacci\", values = {1, 1, 2, 4}},\n {name = \"Lucas\", values = {2, 1} }\n}\nfor _, sequence in pairs(fibSeqs) do\n io.write(sequence.name .. \": \")\n print(table.concat(nStepFibs(sequence.values, 10), \" \"))\nend"} {"title": "Fibonacci word", "language": "Lua", "task": "The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:\n\n Define F_Word1 as '''1'''\n Define F_Word2 as '''0'''\n Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''\n Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2\n\n\n;Task:\nPerform the above steps for n = 37.\n\nYou may display the first few but not the larger values of n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for F_Words '''1''' to '''37''' which shows:\n::* The number of characters in the word\n::* The word's [[Entropy]]\n\n\n;Related tasks: \n* Fibonacci word/fractal\n* [[Entropy]]\n* [[Entropy/Narcissist]]\n\n", "solution": "-- Return the base two logarithm of x\nfunction log2 (x) return math.log(x) / math.log(2) end\n \n-- Return the Shannon entropy of X\nfunction entropy (X)\n local N, count, sum, i = X:len(), {}, 0\n for char = 1, N do\n i = X:sub(char, char)\n if count[i] then\n count[i] = count[i] + 1\n else\n count[i] = 1\n end\n end\n for n_i, count_i in pairs(count) do\n sum = sum + count_i / N * log2(count_i / N)\n end\n return -sum\nend\n\n-- Return a table of the first n Fibonacci words\nfunction fibWords (n)\n local fw = {1, 0}\n while #fw < n do fw[#fw + 1] = fw[#fw] .. fw[#fw - 1] end\n return fw\nend\n\n-- Main procedure\nprint(\"n\\tWord length\\tEntropy\")\nfor k, v in pairs(fibWords(37)) do\n v = tostring(v)\n io.write(k .. \"\\t\" .. #v)\n if string.len(#v) < 8 then io.write(\"\\t\") end\n print(\"\\t\" .. entropy(v))\nend"} {"title": "File extension is in extensions list", "language": "Lua", "task": "Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the [[Extract file extension]] task.\n\n\n;Related tasks: \n* [[Extract file extension]]\n* [[String matching]]\n\n", "solution": "-- Data declarations\nlocal extentions = {\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\"}\nlocal testCases = {\n \"MyData.a##\",\n \"MyData.tar.Gz\",\n \"MyData.gzip\",\n \"MyData.7z.backup\",\n \"MyData...\",\n \"MyData\",\n \"MyData_v1.0.tar.bz2\",\n \"MyData_v1.0.bz2\"\n}\n\n-- Return boolean of whether example has a file extension found in extList\nfunction extMatch (extList, example)\n for _, extension in pairs(extList) do\n if example:lower():match(\"%.\" .. extension:lower() .. \"$\") then\n return true\n end\n end\n return false\nend\n\n-- Main procedure\nfor _, case in pairs(testCases) do\n print(case .. \": \" .. tostring(extMatch(extentions, case)))\nend"} {"title": "Find if a point is within a triangle", "language": "Lua from C++", "task": "Find if a point is within a triangle.\n\n\n;Task:\n \n::* Assume points are on a plane defined by (x, y) real number coordinates.\n\n::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. \n\n::* You may use any algorithm. \n\n::* Bonus: explain why the algorithm you chose works.\n\n\n;Related tasks:\n* [[Determine_if_two_triangles_overlap]]\n\n\n;Also see:\n:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]\n:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]\n:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]\n:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]\n\n", "solution": "EPS = 0.001\nEPS_SQUARE = EPS * EPS\n\nfunction side(x1, y1, x2, y2, x, y)\n return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1)\nend\n\nfunction naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n local checkSide1 = side(x1, y1, x2, y2, x, y) >= 0\n local checkSide2 = side(x2, y2, x3, y3, x, y) >= 0\n local checkSide3 = side(x3, y3, x1, y1, x, y) >= 0\n return checkSide1 and checkSide2 and checkSide3\nend\n\nfunction pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)\n local xMin = math.min(x1, x2, x3) - EPS\n local xMax = math.max(x1, x2, x3) + EPS\n local yMin = math.min(y1, y2, y3) - EPS\n local yMax = math.max(y1, y2, y3) + EPS\n return not (x < xMin or xMax < x or y < yMin or yMax < y)\nend\n\nfunction distanceSquarePointToSegment(x1, y1, x2, y2, x, y)\n local p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)\n local dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength\n if dotProduct < 0 then\n return (x - x1) * (x - x1) + (y - y1) * (y - y1)\n end\n if dotProduct <= 1 then\n local p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y)\n return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength\n end\n return (x - x2) * (x - x2) + (y - y2) * (y - y2)\nend\n\nfunction accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)\n if not pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) then\n return false\n end\n if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) then\n return true\n end\n if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then\n return true\n end\n if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then\n return true\n end\n if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then\n return true\n end\n return false\nend\n\nfunction printPoint(x, y)\n io.write('('..x..\", \"..y..')')\nend\n\nfunction printTriangle(x1, y1, x2, y2, x3, y3)\n io.write(\"Triangle is [\")\n printPoint(x1, y1)\n io.write(\", \")\n printPoint(x2, y2)\n io.write(\", \")\n printPoint(x3, y3)\n print(\"]\")\nend\n\nfunction test(x1, y1, x2, y2, x3, y3, x, y)\n printTriangle(x1, y1, x2, y2, x3, y3)\n io.write(\"Point \")\n printPoint(x, y)\n print(\" is within triangle? \" .. tostring(accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)))\nend\n\ntest(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0)\ntest(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1)\ntest(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1)\nprint()\n\ntest(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348)\nprint()\n\ntest(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348)\nprint()"} {"title": "Find limit of recursion", "language": "Lua", "task": "{{selection|Short Circuit|Console Program Basics}}\n\n \n\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "local c = 0\nfunction Tail(proper)\n c = c + 1\n if proper then\n if c < 9999999 then return Tail(proper) else return c end\n else\n return 1/c+Tail(proper) -- make the recursive call must keep previous stack\n end \nend\n\nlocal ok,check = pcall(Tail,true)\nprint(c, ok, check)\nc=0\nok,check = pcall(Tail,false)\nprint(c, ok, check)\n"} {"title": "Find the intersection of a line with a plane", "language": "Lua", "task": "Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.\n\n\n;Task:\nFind the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].\n\n", "solution": "function make(xval, yval, zval)\n return {x=xval, y=yval, z=zval}\nend\n\nfunction plus(lhs, rhs)\n return make(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)\nend\n\nfunction minus(lhs, rhs)\n return make(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)\nend\n\nfunction times(lhs, scale)\n return make(scale * lhs.x, scale * lhs.y, scale * lhs.z)\nend\n\nfunction dot(lhs, rhs)\n return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z\nend\n\nfunction tostr(val)\n return \"(\" .. val.x .. \", \" .. val.y .. \", \" .. val.z .. \")\"\nend\n\nfunction intersectPoint(rayVector, rayPoint, planeNormal, planePoint)\n diff = minus(rayPoint, planePoint)\n prod1 = dot(diff, planeNormal)\n prod2 = dot(rayVector, planeNormal)\n prod3 = prod1 / prod2\n return minus(rayPoint, times(rayVector, prod3))\nend\n\nrv = make(0.0, -1.0, -1.0)\nrp = make(0.0, 0.0, 10.0)\npn = make(0.0, 0.0, 1.0)\npp = make(0.0, 0.0, 5.0)\nip = intersectPoint(rv, rp, pn, pp)\nprint(\"The ray intersects the plane at \" .. tostr(ip))"} {"title": "Find the intersection of two lines", "language": "Lua from C#", "task": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]\n\n;Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though (4,0) and (6,10) . \nThe 2nd line passes though (0,3) and (10,7) .\n\n", "solution": "function intersection (s1, e1, s2, e2)\n local d = (s1.x - e1.x) * (s2.y - e2.y) - (s1.y - e1.y) * (s2.x - e2.x)\n local a = s1.x * e1.y - s1.y * e1.x\n local b = s2.x * e2.y - s2.y * e2.x\n local x = (a * (s2.x - e2.x) - (s1.x - e1.x) * b) / d\n local y = (a * (s2.y - e2.y) - (s1.y - e1.y) * b) / d\n return x, y\nend\n\nlocal line1start, line1end = {x = 4, y = 0}, {x = 6, y = 10}\nlocal line2start, line2end = {x = 0, y = 3}, {x = 10, y = 7}\nprint(intersection(line1start, line1end, line2start, line2end))"} {"title": "Find the last Sunday of each month", "language": "Lua", "task": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n\n;Related tasks\n* [[Day of the week]]\n* [[Five weekends]]\n* [[Last Friday of each month]]\n\n", "solution": "function isLeapYear (y)\n return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0\nend\n\nfunction dayOfWeek (y, m, d)\n local t = os.time({year = y, month = m, day = d})\n return os.date(\"%A\", t)\nend\n\nfunction lastWeekdays (wday, year)\n local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}\n if isLeapYear(year) then monthLength[2] = 29 end\n for month = 1, 12 do\n day = monthLength[month]\n while dayOfWeek(year, month, day) ~= wday do day = day - 1 end\n print(year .. \"-\" .. month .. \"-\" .. day)\n end\nend\n\nlastWeekdays(\"Sunday\", tonumber(arg[1]))"} {"title": "Find the missing permutation", "language": "Lua", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "local permute, tablex = require(\"pl.permute\"), require(\"pl.tablex\")\nlocal permList, pStr = {\n \"ABCD\", \"CABD\", \"ACDB\", \"DACB\", \"BCDA\", \"ACBD\", \"ADCB\", \"CDAB\",\n \"DABC\", \"BCAD\", \"CADB\", \"CDBA\", \"CBAD\", \"ABDC\", \"ADBC\", \"BDCA\",\n \"DCBA\", \"BACD\", \"BADC\", \"BDAC\", \"CBDA\", \"DBCA\", \"DCAB\"\n}\nfor perm in permute.iter({\"A\",\"B\",\"C\",\"D\"}) do\n pStr = table.concat(perm)\n if not tablex.find(permList, pStr) then print(pStr) end\nend"} {"title": "First-class functions/Use numbers analogously", "language": "Lua", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": "-- This function returns another function that\n-- keeps n1 and n2 in scope, ie. a closure.\nfunction multiplier (n1, n2)\n return function (m)\n return n1 * n2 * m\n end\nend\n\n-- Multiple assignment a-go-go\nlocal x, xi, y, yi = 2.0, 0.5, 4.0, 0.25\nlocal z, zi = x + y, 1.0 / ( x + y )\nlocal nums, invs = {x, y, z}, {xi, yi, zi}\n\n-- 'new_function' stores the closure and then has the 0.5 applied to it\n-- (this 0.5 isn't in the task description but everyone else used it)\nfor k, v in pairs(nums) do\n new_function = multiplier(v, invs[k])\n print(v .. \" * \" .. invs[k] .. \" * 0.5 = \" .. new_function(0.5))\nend\n"} {"title": "Fivenum", "language": "Lua", "task": "Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, there are variations among statistical packages for the whiskers.\n\n", "solution": "function slice(tbl, low, high)\n local copy = {}\n\n for i=low or 1, high or #tbl do\n copy[#copy+1] = tbl[i]\n end\n\n return copy\nend\n\n-- assumes that tbl is sorted\nfunction median(tbl)\n m = math.floor(#tbl / 2) + 1\n if #tbl % 2 == 1 then\n return tbl[m]\n end\n return (tbl[m-1] + tbl[m]) / 2\nend\n\nfunction fivenum(tbl)\n table.sort(tbl)\n\n r0 = tbl[1]\n r2 = median(tbl)\n r4 = tbl[#tbl]\n\n m = math.floor(#tbl / 2)\n if #tbl % 2 == 1 then\n low = m\n else\n low = m - 1\n end\n r1 = median(slice(tbl, nil, low+1))\n r3 = median(slice(tbl, low+2, nil))\n\n return r0, r1, r2, r3, r4\nend\n\nx1 = {\n {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},\n {36.0, 40.0, 7.0, 39.0, 41.0, 15.0},\n {\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,\n -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n }\n}\n\nfor i,x in ipairs(x1) do\n print(fivenum(x))\nend"} {"title": "Fixed length records", "language": "Lua", "task": "Fixed length read/write\n\nBefore terminals, computers commonly used punch card readers or paper tape input.\n\nA common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.\n\nThese input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.\n\nThese devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).\n\n;Task:\nWrite a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. \n\nSamples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.\n\n'''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.\n\nThese fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''.\n\n;Sample data:\nTo create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size.\n\nLine 1...1.........2.........3.........4.........5.........6.........7.........8\nLine 2\nLine 3\nLine 4\n\nLine 6\nLine 7\n Indented line 8............................................................\nLine 9 RT MARGIN\nprompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input.\n\nprompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines.\n\n\n;Bonus round:\nForth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).\n\nWrite a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.\n\nAlso demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.\n\nThe COBOL example uses forth.txt and forth.blk filenames.\n\n", "solution": "-- prep: convert given sample text to fixed length \"infile.dat\"\nlocal sample = [[\nLine 1...1.........2.........3.........4.........5.........6.........7.........8\nLine 2\nLine 3\nLine 4\n \nLine 6\nLine 7\n Indented line 8............................................................\nLine 9 RT MARGIN]]\nlocal txtfile = io.open(\"sample.txt\", \"w\")\ntxtfile:write(sample)\ntxtfile:close()\nos.execute(\"dd if=sample.txt of=infile.dat cbs=80 conv=block > /dev/null 2>&1\")\n\n-- task: convert fixed length \"infile.dat\" to fixed length \"outfile.dat\" (reversed lines)\nlocal infile = io.open(\"infile.dat\", \"rb\")\nlocal outfile = io.open(\"outfile.dat\", \"wb\")\nwhile true do\n local line = infile:read(80)\n if not line then break end\n outfile:write(string.reverse(line))\nend\ninfile:close()\noutfile:close()\n\n-- output:\nos.execute(\"dd if=outfile.dat cbs=80 conv=unblock\")"} {"title": "Flatten a list", "language": "Lua", "task": "Write a function to flatten the nesting in an arbitrary list of values. \n\nYour program should work on the equivalent of this list:\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\nWhere the correct result would be the list:\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n;Related task:\n* [[Tree traversal]]\n\n", "solution": "function flatten(list)\n if type(list) ~= \"table\" then return {list} end\n local flat_list = {}\n for _, elem in ipairs(list) do\n for _, val in ipairs(flatten(elem)) do\n flat_list[#flat_list + 1] = val\n end\n end\n return flat_list\nend\n\ntest_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}\n\nprint(table.concat(flatten(test_list), \",\"))"} {"title": "Flipping bits game", "language": "Lua", "task": "The game:\nGiven an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.\n\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered \ncolumns at once (as one move).\n\nIn an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.\n\n\n;Task:\nCreate a program to score for the Flipping bits game.\n# The game should create an original random target configuration and a starting configuration.\n# Ensure that the starting position is ''never'' the target position.\n# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).\n# The number of moves taken so far should be shown.\n\n\nShow an example of a short game here, on this page, for a '''3x3''' array of bits.\n\n", "solution": "target, board, moves, W, H = {}, {}, 0, 3, 3\n\nfunction getIndex( i, j ) return i + j * W - W end\n\nfunction flip( d, r )\n function invert( a ) if a == 1 then return 0 end return 1 end\n local idx\n if d == 1 then\n for i = 1, W do\n idx = getIndex( i, r )\n board[idx] = invert( board[idx] )\n end\n else\n for i = 1, H do\n idx = getIndex( r, i )\n board[idx] = invert( board[idx] )\n end\n end\n moves = moves + 1\nend\nfunction createTarget()\n target, board = {}, {}\n local idx\n for j = 1, H do\n for i = 1, W do\n idx = getIndex( i, j )\n if math.random() < .5 then target[idx] = 0\n else target[idx] = 1\n end\n board[idx] = target[idx]\n end\n end\n for i = 1, 103 do\n if math.random() < .5 then flip( 1, math.random( H ) )\n else flip( 2, math.random( W ) )\n end\n end\n moves = 0\nend\nfunction getUserInput()\n io.write( \"Input row and/or column: \" ); local r = io.read()\n local a\n for i = 1, #r do\n a = string.byte( r:sub( i, i ):lower() )\n if a >= 48 and a <= 57 then flip( 2, a - 48 ) end\n if a >= 97 and a <= string.byte( 'z' ) then flip( 1, a - 96 ) end\n end\nend\nfunction solved()\n local idx\n for j = 1, H do\n for i = 1, W do\n idx = getIndex( i, j )\n if target[idx] ~= board[idx] then return false end\n end\n end\n return true\nend\nfunction display()\n local idx\n io.write( \"\\nTARGET\\n \" )\n for i = 1, W do io.write( string.format( \"%d \", i ) ) end; print()\n for j = 1, H do\n io.write( string.format( \"%s \", string.char( 96 + j ) ) )\n for i = 1, W do\n idx = getIndex( i, j )\n io.write( string.format( \"%d \", target[idx] ) )\n end; io.write( \"\\n\" )\n end\n io.write( \"\\nBOARD\\n \" )\n for i = 1, W do io.write( string.format( \"%d \", i ) ) end; print()\n for j = 1, H do\n io.write( string.format( \"%s \", string.char( 96 + j ) ) )\n for i = 1, W do\n idx = getIndex( i, j )\n io.write( string.format( \"%d \", board[idx] ) )\n end; io.write( \"\\n\" )\n end\n io.write( string.format( \"Moves: %d\\n\", moves ) )\nend\nfunction play()\n while true do\n createTarget()\n repeat\n display()\n getUserInput()\n until solved()\n display()\n io.write( \"Very well!\\nPlay again(Y/N)? \" );\n if io.read():lower() ~= \"y\" then return end\n end\nend\n--[[entry point]]--\nmath.randomseed( os.time() )\nplay()\n"} {"title": "Floyd's triangle", "language": "Lua", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "function print_floyd(rows)\n\tlocal c = 1\n\tlocal h = rows*(rows-1)/2\n\tfor i=1,rows do\n\t\tlocal s = \"\"\n\t\tfor j=1,i do\n\t\t\tfor k=1, #tostring(h+j)-#tostring(c) do\n\t\t\t\ts = s .. \" \"\n\t\t\tend\n\t\t\tif j ~= 1 then s = s .. \" \" end\n\t\t\ts = s .. tostring(c)\n\t\t\tc = c + 1\n\t\tend\n\t\tprint(s)\n\tend\nend\n\nprint_floyd(5)\nprint_floyd(14)"} {"title": "Four bit adder", "language": "Lua", "task": "\"''Simulate''\" a four-bit adder.\n \nThis design can be realized using four 1-bit full adders. \nEach of these 1-bit full adders can be built with two gate. ; \n\nFinally a half adder can be made using an ''xor'' gate and an ''and'' gate. \n\nThe ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.\n\n'''Not''', '''or''' and '''and''', the only allowed \"gates\" for the task, can be \"imitated\" by using the bitwise operators of your language. \n\nIf there is not a ''bit type'' in your language, to be sure that the ''not'' does not \"invert\" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other \"constructive blocks\", in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \n! (A half adder) \n! (A full adder) \n! (A 4-bit adder) \n|-\n|Xor gate done with ands, ors and nots\n|A half adder\n|A full adder\n|A 4-bit adder\n|}\n\n\n\nSolutions should try to be as descriptive as possible, making it as easy as possible to identify \"connections\" between higher-order \"blocks\". \n\nIt is not mandatory to replicate the syntax of higher-order blocks in the atomic \"gate\" blocks, i.e. basic \"gate\" operations can be performed as usual bitwise operations, or they can be \"wrapped\" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.\n\nTo test the implementation, show the sum of two four-bit numbers (in binary).\n\n\n", "solution": "-- Build XOR from AND, OR and NOT\nfunction xor (a, b) return (a and not b) or (b and not a) end\n \n-- Can make half adder now XOR exists\nfunction halfAdder (a, b) return xor(a, b), a and b end\n \n-- Full adder is two half adders with carry outputs OR'd\nfunction fullAdder (a, b, cIn)\n local ha0s, ha0c = halfAdder(cIn, a)\n local ha1s, ha1c = halfAdder(ha0s, b)\n local cOut, s = ha0c or ha1c, ha1s\n return cOut, s\nend\n \n-- Carry bits 'ripple' through adders, first returned value is overflow\nfunction fourBitAdder (a3, a2, a1, a0, b3, b2, b1, b0) -- LSB-first\n local fa0c, fa0s = fullAdder(a0, b0, false)\n local fa1c, fa1s = fullAdder(a1, b1, fa0c)\n local fa2c, fa2s = fullAdder(a2, b2, fa1c)\n local fa3c, fa3s = fullAdder(a3, b3, fa2c)\n return fa3c, fa3s, fa2s, fa1s, fa0s -- Return as MSB-first\nend\n \n-- Take string of noughts and ones, convert to native boolean type\nfunction toBool (bitString)\n local boolList, bit = {}\n for digit = 1, 4 do\n bit = string.sub(string.format(\"%04d\", bitString), digit, digit)\n if bit == \"0\" then table.insert(boolList, false) end\n if bit == \"1\" then table.insert(boolList, true) end\n end\n return boolList\nend\n \n-- Take list of booleans, convert to string of binary digits (variadic)\nfunction toBits (...)\n local bStr = \"\"\n for i, bool in pairs{...} do\n if bool then bStr = bStr .. \"1\" else bStr = bStr .. \"0\" end\n end\n return bStr\nend\n \n-- Little driver function to neaten use of the adder\nfunction add (n1, n2)\n local A, B = toBool(n1), toBool(n2)\n local v, s0, s1, s2, s3 = fourBitAdder( A[1], A[2], A[3], A[4],\n B[1], B[2], B[3], B[4] )\n return toBits(s0, s1, s2, s3), v\nend\n \n-- Main procedure (usage examples)\nprint(\"SUM\", \"OVERFLOW\\n\")\nprint(add(0001, 0001)) -- 1 + 1 = 2\nprint(add(0101, 1010)) -- 5 + 10 = 15\nprint(add(0000, 1111)) -- 0 + 15 = 15\nprint(add(0001, 1111)) -- 1 + 15 = 16 (causes overflow)"} {"title": "Four is magic", "language": "Lua", "task": "Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* [[Four is the number of_letters in the ...]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Summarize and say sequence]]\n:* [[Spelling of ordinal numbers]]\n:* [[De Bruijn sequences]]\n\n", "solution": "-- Four is magic, in Lua, 6/16/2020 db\nlocal oneslist = { [0]=\"\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }\nlocal teenlist = { [0]=\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" }\nlocal tenslist = { [0]=\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" }\nlocal lionlist = { [0]=\"\", \"thousand\", \"million\", \"billion\", \"trillion\", \"quadrillion\", \"quintillion\", \"sextillion\", \"septillion\", \"octillion\", \"nonillion\", \"decillion\" }\nlocal abs, floor = math.abs, math.floor\n\nlocal function numname(num)\n if (num == 0) then return \"zero\" end\n local absnum, lion, result = abs(num), 0, \"\"\n local function dashed(s) return s==\"\" and s or \"-\"..s end\n local function spaced(s) return s==\"\" and s or \" \"..s end\n while (absnum > 0) do\n local word, ones, tens, huns = \"\", absnum%10, floor(absnum/10)%10, floor(absnum/100)%10\n if (tens==0) then word = oneslist[ones]\n elseif (tens==1) then word = teenlist[ones]\n else word = tenslist[tens] .. dashed(oneslist[ones]) end\n if (huns > 0) then word = oneslist[huns] .. \" hundred\" .. spaced(word) end\n if (word ~= \"\") then result = word .. spaced(lionlist[lion]) .. spaced(result) end\n absnum = floor(absnum / 1000)\n lion = lion + 1\n end\n if (num < 0) then result = \"negative \" .. result end\n return result\nend\n\nlocal function fourismagic(num)\n local function fim(num)\n local name = numname(num)\n if (num == 4) then\n return name .. \" is magic.\"\n else\n local what = numname(#name)\n return name .. \" is \" .. what .. \", \" .. fim(#name)\n end\n end\n local result = fim(num):gsub(\"^%l\", string.upper)\n return result\nend\n\nlocal numbers = { -21,-1, 0,1,2,3,4,5,6,7,8,9, 12,34,123,456,1024,1234,12345,123456,1010101 }\nfor _, num in ipairs(numbers) do\n print(num, fourismagic(num))\nend"} {"title": "Function prototype", "language": "Lua", "task": "Some languages provide the facility to declare functions and subroutines through the use of function prototyping. \n\n\n;Task:\nDemonstrate the methods available for declaring prototypes within the language. The provided solutions should include:\n\n* An explanation of any placement restrictions for prototype declarations\n* A prototype declaration for a function that does not require arguments\n* A prototype declaration for a function that requires two arguments\n* A prototype declaration for a function that utilizes varargs\n* A prototype declaration for a function that utilizes optional arguments\n* A prototype declaration for a function that utilizes named parameters\n* Example of prototype declarations for subroutines or procedures (if these differ from functions)\n* An explanation and example of any special forms of prototyping not covered by the above\n\n\nLanguages that do not provide function prototyping facilities should be omitted from this task.\n\n", "solution": "function Func() -- Does not require arguments\n\treturn 1\nend\n\nfunction Func(a,b) -- Requires arguments\n\treturn a + b\nend\n\nfunction Func(a,b) -- Arguments are optional\n\treturn a or 4 + b or 2\nend\n\nfunction Func(a,...) -- One argument followed by varargs\n\treturn a,{...} -- Returns both arguments, varargs as table\nend"} {"title": "Functional coverage tree", "language": "Lua", "task": "Functional coverage is a measure of how much a particular function of a system \nhas been verified as correct. It is used heavily in tracking the completeness \nof the verification of complex System on Chip (SoC) integrated circuits, where \nit can also be used to track how well the functional ''requirements'' of the \nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking \nfunctional coverage but uses a more familiar(?) scenario.\n\n;Task Description:\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when \nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on \neach house who return with a breakdown of how they will report on progress in \neach house.\n\nThe overall hierarchy of (sub)tasks is as follows, \ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n\n;Calculation:\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\n;Extra Credit:\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.\nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\nFollowed by a call to:\n\n top.delta_calculation(power=1)\n\n\n'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.\n\n", "solution": "-- DATA:\nlocal function node(name, weight, coverage, children)\n return { name=name, weight=weight or 1.0, coverage=coverage or 0.0, sumofweights=0, delta=0, children=children }\nend\n\nlocal root =\nnode(\"cleaning\", nil, nil, {\n node(\"house1\", 40, nil, {\n node(\"bedrooms\", nil, 0.25),\n node(\"bathrooms\", nil, nil, {\n node(\"bathroom1\", nil, 0.5),\n node(\"bathroom2\"),\n node(\"outside_lavatory\", nil, 1)\n }),\n node(\"attic\", nil, 0.75),\n node(\"kitchen\", nil, 0.1),\n node(\"living_rooms\", nil, nil, {\n node(\"lounge\"),\n node(\"dining_room\"),\n node(\"conservatory\"),\n node(\"playroom\",nil,1)\n }),\n node(\"basement\"),\n node(\"garage\"),\n node(\"garden\", nil, 0.8)\n }),\n node(\"house2\", 60, nil, {\n node(\"upstairs\", nil, nil, {\n node(\"bedrooms\", nil, nil, {\n node(\"suite_1\"),\n node(\"suite_2\"),\n node(\"bedroom_3\"),\n node(\"bedroom_4\")\n }),\n node(\"bathroom\"),\n node(\"toilet\"),\n node(\"attics\", nil, 0.6)\n }),\n node(\"groundfloor\", nil, nil, {\n node(\"kitchen\"),\n node(\"living_rooms\", nil, nil, {\n node(\"lounge\"),\n node(\"dining_room\"),\n node(\"conservatory\"),\n node(\"playroom\")\n }),\n node(\"wet_room_&_toilet\"),\n node(\"garage\"),\n node(\"garden\", nil, 0.9),\n node(\"hot_tub_suite\", nil, 1)\n }),\n node(\"basement\", nil, nil, {\n node(\"cellars\", nil, 1),\n node(\"wine_cellar\", nil, 1),\n node(\"cinema\", nil, 0.75)\n })\n })\n})\n\n-- TASK:\nlocal function calccover(node)\n if (node.children) then\n local cnt, sum = 0, 0\n for _,child in ipairs(node.children) do\n local ccnt, csum = calccover(child)\n cnt, sum = cnt+ccnt, sum+csum\n end\n node.coverage = sum/cnt\n node.sumofweights = cnt -- just as prep for extra credit\n end\n return node.weight, node.coverage * node.weight\nend\ncalccover(root)\n\n-- EXTRA CREDIT:\nlocal function calcdelta(node, power)\n node.delta = (1.0 - node.coverage) * power\n if (node.children) then\n for _,child in ipairs(node.children) do\n calcdelta(child, power * child.weight / node.sumofweights)\n end\n end\nend\ncalcdelta(root,1)\n\n-- OUTPUT:\nlocal function printnode(node, space)\n print(string.format(\"%-32s| %3.f | %8.6f | %8.6f |\", string.rep(\" \",space)..node.name, node.weight, node.coverage, node.delta))\n if node.children then\n for _,child in ipairs(node.children) do printnode(child,space+4) end\n end\nend\nprint(\"NAME_HIERARCHY |WEIGHT |COVERAGE |DELTA |\")\nprintnode(root,0)"} {"title": "Fusc sequence", "language": "Lua from C", "task": "Definitions:\nThe '''fusc''' integer sequence is defined as:\n::* fusc(0) = 0\n::* fusc(1) = 1\n::* for '''n'''>1, the '''n'''th term is defined as:\n::::* if '''n''' is even; fusc(n) = fusc(n/2)\n::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).\n\n\n\n;An observation:\n:::::* fusc(A) = fusc(B)\n\nwhere '''A''' is some non-negative integer expressed in binary, and\nwhere '''B''' is the binary value of '''A''' reversed.\n\n\n\nFusc numbers are also known as:\n::* fusc function (named by Dijkstra, 1982)\n::* Stern's Diatomic series (although it starts with unity, not zero)\n::* Stern-Brocot sequence (although it starts with unity, not zero)\n\n\n\n;Task:\n::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.\n::* show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* show all numbers with commas (if appropriate).\n::* show all output here.\n\n\n;Related task:\n::* RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* the MathWorld entry: Stern's Diatomic Series.\n::* the OEIS entry: A2487.\n\n", "solution": "function fusc(n)\n n = math.floor(n)\n if n == 0 or n == 1 then\n return n\n elseif n % 2 == 0 then\n return fusc(n / 2)\n else\n return fusc((n - 1) / 2) + fusc((n + 1) / 2)\n end\nend\n\nfunction numLen(n)\n local sum = 1\n while n > 9 do\n n = math.floor(n / 10)\n sum = sum + 1\n end\n return sum\nend\n\nfunction printLargeFuscs(limit)\n print(\"Printing all largest Fusc numbers up to \" .. limit)\n print(\"Index-------Value\")\n local maxLen = 1\n for i=0,limit do\n local f = fusc(i)\n local le = numLen(f)\n if le > maxLen then\n maxLen = le\n print(string.format(\"%5d%12d\", i, f))\n end\n end\nend\n\nfunction main()\n print(\"Index-------Value\")\n for i=0,60 do\n print(string.format(\"%5d%12d\", i, fusc(i)))\n end\n printLargeFuscs(math.pow(2, 31) - 1)\nend\n\nmain()"} {"title": "Gapful numbers", "language": "Lua from C", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''187'''. \n\n\nAbout 7.46% of positive integers are ''gapful''. \n\n\n;Task:\n:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page\n:* Show the first '''30''' gapful numbers\n:* Show the first '''15''' gapful numbers >= '''1,000,000'''\n:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''\n\n\n;Related tasks:\n:* Harshad or Niven series.\n:* palindromic gapful numbers.\n:* largest number divisible by its digits.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n:* numbersaplenty gapful numbers\n\n", "solution": "function generateGaps(start, count)\n local counter = 0\n local i = start\n\n print(string.format(\"First %d Gapful numbers >= %d :\", count, start))\n\n while counter < count do\n local str = tostring(i)\n local denom = 10 * tonumber(str:sub(1, 1)) + (i % 10)\n if i % denom == 0 then\n print(string.format(\"%3d : %d\", counter + 1, i))\n counter = counter + 1\n end\n i = i + 1\n end\nend\n\ngenerateGaps(100, 30)\nprint()\n\ngenerateGaps(1000000, 15)\nprint()\n\ngenerateGaps(1000000000, 15)\nprint()"} {"title": "Generate Chess960 starting position", "language": "Lua", "task": "Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:\n\n* as in the standard chess game, all eight white pawns must be placed on the second rank.\n* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:\n** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)\n** the King must be between two rooks (with any number of other pieces between them all)\n* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)\n\n\nWith those constraints there are '''960''' possible starting positions, thus the name of the variant.\n\n\n;Task:\nThe purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "-- Insert 'str' into 't' at a random position from 'left' to 'right'\nfunction randomInsert (t, str, left, right)\n local pos\n repeat pos = math.random(left, right) until not t[pos]\n t[pos] = str\n return pos\nend\n\n-- Generate a random Chess960 start position for white major pieces\nfunction chess960 ()\n local t, b1, b2 = {}\n local kingPos = randomInsert(t, \"K\", 2, 7)\n randomInsert(t, \"R\", 1, kingPos - 1)\n randomInsert(t, \"R\", kingPos + 1, 8)\n b1 = randomInsert(t, \"B\", 1, 8)\n b2 = randomInsert(t, \"B\", 1, 8)\n while (b2 - b1) % 2 == 0 do\n t[b2] = false\n b2 = randomInsert(t, \"B\", 1, 8)\n end\n randomInsert(t, \"Q\", 1, 8)\n randomInsert(t, \"N\", 1, 8)\n randomInsert(t, \"N\", 1, 8)\n return t\nend\n\n-- Main procedure\nmath.randomseed(os.time())\nprint(table.concat(chess960()))"} {"title": "Generator/Exponential", "language": "Lua", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "--could be done with a coroutine, but a simple closure works just as well.\nlocal function powgen(m)\n local count = 0\n return function()\n count = count + 1\n return count^m\n end\nend\n\nlocal squares = powgen(2)\nlocal cubes = powgen(3)\n\nlocal cowrap,coyield = coroutine.wrap, coroutine.yield\n\nlocal function filter(f,g)\n return cowrap(function()\n local ff,gg = f(), g()\n while true do\n if ff == gg then\n ff,gg = f(), g()\n elseif ff < gg then\n coyield(ff)\n ff = f()\n else\n gg = g()\n end\n end\n end)\nend\n\nfilter = filter(squares,cubes)\n\nfor i = 1,30 do\n local result = filter()\n if i > 20 then\n print(result)\n end\nend\n"} {"title": "Get system command output", "language": "Lua", "task": "Task\nExecute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). \n\n;Related task\n* Execute a system command\n\n", "solution": "local output = io.popen(\"echo Hurrah!\")\nprint(output:read(\"*all\"))"} {"title": "Globally replace text in several files", "language": "Lua", "task": "Replace every occurring instance of a piece of text in a group of text files with another one. \n\n\nFor this task we want to replace the text \"'''Goodbye London!'''\" with \"'''Hello New York!'''\" for a list of files.\n\n", "solution": "filenames = { \"f1.txt\", \"f2.txt\" }\n\nfor _, fn in pairs( filenames ) do\n fp = io.open( fn, \"r\" )\n str = fp:read( \"*all\" )\n str = string.gsub( str, \"Goodbye London!\", \"Hello New York!\" )\n fp:close()\n\n fp = io.open( fn, \"w+\" )\n fp:write( str )\n fp:close()\nend"} {"title": "Gray code", "language": "Lua from Euphoria", "task": "Karnaugh maps in order from left to right or top to bottom.\nCreate functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* Converting Between Gray and Binary Codes. It includes step-by-step animations.\n\n", "solution": "local bit = require 'bit'\nlocal gray = require 'gray'\n\n-- simple binary string formatter\nlocal function to_bit_string(n, width)\n width = width or 1\n local output = \"\"\n while n > 0 do\n output = bit.band(n,1) .. output\n n = bit.rshift(n,1)\n end\n while #output < width do\n output = '0' .. output\n end\n return output\nend\n\nfor i = 0,31 do\n g = gray.encode(i);\n gd = gray.decode(g);\n print(string.format(\"%2d : %s => %s => %s : %2d\", i,\n to_bit_string(i,5), to_bit_string(g, 5), \n to_bit_string(gd,5), gd))\nend"} {"title": "Greatest subsequential sum", "language": "Lua", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "function sumt(t, start, last) return start <= last and t[start] + sumt(t, start+1, last) or 0 end\nfunction maxsub(ary, idx)\n local idx = idx or 1\n if not ary[idx] then return {} end\n local maxsum, last = 0, idx\n for i = idx, #ary do\n if sumt(ary, idx, i) > maxsum then maxsum, last = sumt(ary, idx, i), i end\n end\n local v = maxsub(ary, idx + 1)\n if maxsum < sumt(v, 1, #v) then return v end\n local ret = {}\n for i = idx, last do ret[#ret+1] = ary[i] end\n return ret\nend"} {"title": "Hailstone sequence", "language": "Lua", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "function hailstone( n, print_numbers )\n local n_iter = 1\n\n while n ~= 1 do\n if print_numbers then print( n ) end\n if n % 2 == 0 then \n n = n / 2\n else\n n = 3 * n + 1\n end \n \n n_iter = n_iter + 1\n end\n if print_numbers then print( n ) end\n \n return n_iter;\nend\n\nhailstone( 27, true )\n\nmax_i, max_iter = 0, 0\nfor i = 1, 100000 do\n num = hailstone( i, false )\n if num >= max_iter then\n max_i = i\n max_iter = num\n end\nend\n\nprint( string.format( \"Needed %d iterations for the number %d.\\n\", max_iter, max_i ) )"} {"title": "Harmonic series", "language": "Lua", "task": "{{Wikipedia|Harmonic number}}\n\n\nIn mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers: \n\n\n'''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n'''\n\nThe series of harmonic numbers thus obtained is often loosely referred to as the harmonic series. \n\nHarmonic numbers are closely related to the Euler-Mascheroni constant.\n\nThe harmonic series is divergent, albeit quite slowly, and grows toward infinity.\n\n\n;Task\n* Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers.\n* Use that procedure to show the values of the first 20 harmonic numbers.\n* Find and show the position in the series of the first value greater than the integers 1 through 5\n\n\n;Stretch\n* Find and show the position in the series of the first value greater than the integers 6 through 10\n\n\n;Related\n* [[Egyptian fractions]]\n\n\n", "solution": "-- Task 1\nfunction harmonic (n)\n if n < 1 or n ~= math.floor(n) then\n error(\"Argument to harmonic function is not a natural number\")\n end\n local Hn = 1\n for i = 2, n do\n Hn = Hn + (1/i)\n end\n return Hn\nend\n\n-- Task 2\nfor x = 1, 20 do\n print(x .. \" :\\t\" .. harmonic(x))\nend\n\n-- Task 3\nlocal x, lastInt, Hx = 0, 1\nrepeat\n x = x + 1\n Hx = harmonic(x)\n if Hx > lastInt then\n io.write(\"The first harmonic number above \" .. lastInt)\n print(\" is \" .. Hx .. \" at position \" .. x)\n lastInt = lastInt + 1\n end\nuntil lastInt > 10 -- Stretch goal just meant changing that value from 5 to 10\n -- Execution still only takes about 120 ms under LuaJIT"} {"title": "Harshad or Niven series", "language": "Lua", "task": "The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. \n\nFor example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.\n\nAssume that the series is defined as the numbers in increasing order.\n\n\n;Task:\nThe task is to create a function/method/procedure to generate successive members of the Harshad sequence. \n\nUse it to:\n::* list the first '''20''' members of the sequence, and\n::* list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* Increasing gaps between consecutive Niven numbers\n\n\n;See also\n* OEIS: A005349\n\n", "solution": "function isHarshad(n)\n local s=0\n local n_str=tostring(n)\n for i=1,#n_str do\n s=s+tonumber(n_str:sub(i,i))\n end\n return n%s==0\nend\n\nlocal count=0\nlocal harshads={}\nlocal n=1\n\nwhile count<20 do\n if isHarshad(n) then\n count=count+1\n table.insert(harshads, n)\n end\n n=n+1\nend\n\nprint(table.concat(harshads, \" \"))\n\nlocal h=1001\nwhile not isHarshad(h) do\n h=h+1\nend\nprint(h)\n"} {"title": "Hash join", "language": "Lua", "task": "{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "local function recA(age, name) return { Age=age, Name=name } end\nlocal tabA = { recA(27,\"Jonah\"), recA(18,\"Alan\"), recA(28,\"Glory\"), recA(18,\"Popeye\"), recA(28,\"Alan\") }\n\nlocal function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end\nlocal tabB = { recB(\"Jonah\",\"Whales\"), recB(\"Jonah\",\"Spiders\"), recB(\"Alan\",\"Ghosts\"), recB(\"Alan\",\"Zombies\"), recB(\"Glory\",\"Buffy\") }\n\nlocal function hashjoin(taba, cola, tabb, colb)\n local hash, join = {}, {}\n for _,rowa in pairs(taba) do\n if (not hash[rowa[cola]]) then hash[rowa[cola]] = {} end\n table.insert(hash[rowa[cola]], rowa)\n end\n for _,rowb in pairs(tabb) do\n for _,rowa in pairs(hash[rowb[colb]]) do\n join[#join+1] = { A=rowa, B=rowb }\n end\n end\n return join\nend\n\nfor _,row in pairs(hashjoin(tabA, \"Name\", tabB, \"Character\")) do\n print(row.A.Age, row.A.Name, row.B.Character, row.B.Nemesis)\nend"} {"title": "Haversine formula", "language": "Lua", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "local function haversine(x1, y1, x2, y2)\nr=0.017453292519943295769236907684886127;\nx1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1;\na = math.pow(math.sin(dx/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c;\nreturn d;\nend"} {"title": "Here document", "language": "Lua", "task": "A ''here document'' (or \"heredoc\") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. \n\nDepending on the language being used, a ''here document'' is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string. \n\nThe text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.\n\n\n;Task:\nDemonstrate the use of ''here documents'' within the language.\n\n;Related task:\n* [[Documentation]]\n\n", "solution": "print([[\nThis is a long paragraph of text\nit is the simplest while using it\nwith lua, however it will have the\nsame line breaks and spacing as\n you set in this block.\n]])\n\nprint([=[by using equals signs, ]] may be embedded.]=])\n\nlocal msg = [[this is a message that spans\nmultiple lines and will have the next lines\npreserved as they were entered, so be careful\nwhen using this]]\n\nprint(msg)\n\n"} {"title": "Heronian triangles", "language": "Lua", "task": "Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere ''s'' is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''Heronian triangles'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.\n\nDefine a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor \nof all three sides is '''1''' (unity). \n\nThis will exclude, for example, triangle '''6, 8, 10.'''\n\n\n;Task:\n# Create a named function/method/procedure/... that implements Hero's formula.\n# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.\n# Show the count of how many triangles are found.\n# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths\n# Show the first ten ordered triangles in a table of sides, perimeter, and area.\n# Show a similar ordered table for those triangles with area = 210\n\n\nShow all output here.\n\n'''Note''': when generating triangles it may help to restrict a <= b <= c\n", "solution": "-- Returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one\nlocal function tryHt( a, b, c )\n local result\n local s = ( a + b + c ) / 2;\n local areaSquared = s * ( s - a ) * ( s - b ) * ( s - c );\n if areaSquared > 0 then\n -- a, b, c does form a triangle\n local area = math.sqrt( areaSquared );\n if math.floor( area ) == area then\n -- the area is integral so the triangle is Heronian\n result = { a = a, b = b, c = c, perimeter = a + b + c, area = area }\n end\n end\n return result\nend\n\n-- Returns the GCD of a and b\nlocal function gcd( a, b ) return ( b == 0 and a ) or gcd( b, a % b ) end\n\n-- Prints the details of the Heronian triangle t\nlocal function htPrint( t ) print( string.format( \"%4d %4d %4d %4d %4d\", t.a, t.b, t.c, t.area, t.perimeter ) ) end\n-- Prints headings for the Heronian Triangle table\nlocal function htTitle() print( \" a b c area perimeter\" ); print( \"---- ---- ---- ---- ---------\" ) end\n\n-- Construct ht as a table of the Heronian Triangles with sides up to 200\nlocal ht = {};\nfor c = 1, 200 do\n for b = 1, c do\n for a = 1, b do\n local t = gcd( gcd( a, b ), c ) == 1 and tryHt( a, b, c );\n if t then\n ht[ #ht + 1 ] = t\n end\n end\n end\nend\n\n-- sort the table on ascending area, perimiter and max side length\n-- note we constructed the triangles with c as the longest side\ntable.sort( ht, function( a, b )\n return a.area < b.area or ( a.area == b.area\n and ( a.perimeter < b.perimeter\n or ( a.perimiter == b.perimiter\n and a.c < b.c\n )\n )\n )\n end\n );\n\n-- Display the triangles\nprint( \"There are \" .. #ht .. \" Heronian triangles with sides up to 200\" );\nhtTitle();\nfor htPos = 1, 10 do htPrint( ht[ htPos ] ) end\nprint( \" ...\" );\nprint( \"Heronian triangles with area 210:\" );\nhtTitle();\nfor htPos = 1, #ht do\n local t = ht[ htPos ];\n if t.area == 210 then htPrint( t ) end\nend"} {"title": "History variables", "language": "Lua", "task": "''Storing the history of objects in a program is a common task. \nMaintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.''\n\n''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables.\n'' \n\n\"History Variables: \nThe Semantics, Formal Correctness, and Implementation of History Variables \nin an Imperative Programming Language\" by Mallon and Takaoka\n\nConcept also discussed on LtU and Patents.com.\n\n;Task: \nDemonstrate History variable support: \n* enable history variable support (if needed) \n* define a history variable\n* assign three values\n* non-destructively display the history\n* recall the three values. \n\nFor extra points, if the language of choice does not support history variables, \ndemonstrate how this might be implemented.\n\n", "solution": "-- History variables in Lua 6/12/2020 db\nlocal HistoryVariable = {\n new = function(self)\n return setmetatable({history={}},self)\n end,\n get = function(self)\n return self.history[#self.history]\n end,\n set = function(self, value)\n self.history[#self.history+1] = value\n end,\n undo = function(self)\n self.history[#self.history] = nil\n end,\n}\nHistoryVariable.__index = HistoryVariable\n\nlocal hv = HistoryVariable:new()\nprint(\"defined:\", hv)\nprint(\"value is:\", hv:get())\n--\nhv:set(1); print(\"set() to:\", hv:get())\nhv:set(2); print(\"set() to:\", hv:get())\nhv:set(3); print(\"set() to:\", hv:get())\n--\nprint(\"history:\", table.concat(hv.history,\",\"))\n--\nhv:undo(); print(\"undo() to:\", hv:get())\nhv:undo(); print(\"undo() to:\", hv:get())\nhv:undo(); print(\"undo() to:\", hv:get())"} {"title": "Hofstadter-Conway $10,000 sequence", "language": "Lua", "task": "The definition of the sequence is colloquially described as:\n* Starting with the list [1,1],\n* Take the last number in the list so far: 1, I'll call it x.\n* Count forward x places from the beginning of the list to find the first number to add (1)\n* Count backward x places from the end of the list to find the second number to add (1)\n* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* This would then produce [1,1,2] where 2 is the third element of the sequence.\n\nNote that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.\n\nA less wordy description of the sequence is:\n a(1)=a(2)=1\n a(n)=a(a(n-1))+a(n-a(n-1))\n\nThe sequence begins:\n 1, 1, 2, 2, 3, 4, 4, 4, 5, ...\n\nInteresting features of the sequence are that:\n* a(n)/n tends to 0.5 as n grows towards infinity.\n* a(n)/n where n is a power of 2 is 0.5\n* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.\n\na(n) / n for n in 1..256 \n\n\nThe sequence is so named because John Conway offered a prize of $10,000 to the first person who could\nfind the first position, p in the sequence where \n |a(n)/n| < 0.55 for all n > p\nIt was later found that Hofstadter had also done prior work on the sequence.\n\nThe 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20\n# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20\n\n\n\n;Also see:\n* Conways Challenge Sequence, Mallows' own account.\n* Mathworld Article.\n\n", "solution": "local fmt, write=string.format,io.write\nlocal hof=coroutine.wrap(function()\n\tlocal yield=coroutine.yield\n\tlocal a={1,1}\n\tyield(a[1], 1)\n\tyield(a[2], 2)\n\tlocal n=a[#a]\n\trepeat\n\t\tn=a[n]+a[1+#a-n]\n\t\ta[#a+1]=n\n\t\tyield(n, #a)\n\tuntil false\nend)\n\nlocal mallows, mdiv=0,0\nfor p=1,20 do\n\tlocal max, div, num, last, fdiv=0,0,0,0,0\n\tfor i=2^(p-1),2^p-1 do\n\t\th,n=hof()\n\t\tdiv=h/n\n\t\tif div>max then\n\t\t\tmax=div\n\t\t\tnum=n\n\t\tend\n\t\tif div>0.55 then\n\t\t\tlast=n\n\t\t\tfdiv=div\n\t\tend\n\tend\n\twrite(fmt(\"From 2^%-2d to 2^%-2d the max is %.4f the %6dth Hofstadter number.\\n\", \n\t\tp-1, p, max, num))\n\tif max>.55 and p>4 then \n\t\tmallows, mdiv=last, fdiv\n\tend\nend\nwrite(\"So Mallows number is \", mallows, \" with \", fmt(\"%.4f\",mdiv), \", yay, just wire me my $10000 now!\\n\")\n"} {"title": "Horner's rule for polynomial evaluation", "language": "Lua", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.\n\nCf. [[Formal power series]]\n\n", "solution": "function horners_rule( coeff, x )\n local res = 0 \n for i = #coeff, 1, -1 do\n res = res * x + coeff[i]\n end\n return res\nend\n\nx = 3\ncoefficients = { -19, 7, -4, 6 }\nprint( horners_rule( coefficients, x ) )"} {"title": "ISBN13 check digit", "language": "Lua from C", "task": "Validate the check digit of an ISBN-13 code:\n::* Multiply every other digit by '''3'''.\n::* Add these numbers and the other digits.\n::* Take the remainder of this number after division by '''10'''.\n::* If it is '''0''', the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* 978-0596528126 (good)\n::::* 978-0596528120 (bad)\n::::* 978-1788399081 (good)\n::::* 978-1788399083 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* for details: 13-digit ISBN method of validation. (installs cookies.)\n\n", "solution": "function checkIsbn13(isbn)\n local count = 0\n local sum = 0\n for c in isbn:gmatch\".\" do\n if c == ' ' or c == '-' then\n -- skip\n elseif c < '0' or '9' < c then\n return false\n else\n local digit = c - '0'\n if (count % 2) > 0 then\n sum = sum + 3 * digit\n else\n sum = sum + digit\n end\n count = count + 1\n end\n end\n\n if count ~= 13 then\n return false\n end\n return (sum % 10) == 0\nend\n\nfunction test(isbn)\n if checkIsbn13(isbn) then\n print(isbn .. \": good\")\n else\n print(isbn .. \": bad\")\n end\nend\n\nfunction main()\n test(\"978-1734314502\")\n test(\"978-1734314509\")\n test(\"978-1788399081\")\n test(\"978-1788399083\")\nend\n\nmain()"} {"title": "I before E except after C", "language": "Lua", "task": "The phrase \"I before E, except after C\" is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# ''\"I before E when not preceded by C\"''\n:::# ''\"E before I when preceded by C\"''\n\n\nIf both sub-phrases are plausible then the original phrase can be said to be plausible.\n\nSomething is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).\n \n\n;Stretch goal:\nAs a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.\n\n\n''Show your output here as well as your program.''\n\n\n\n\n;cf.:\n* Schools to rethink 'i before e' - BBC news, 20 June 2009\n* I Before E Except After C - QI Series 8 Ep 14, (humorous)\n* Companion website for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "-- Needed to get dictionary file from web server\nlocal http = require(\"socket.http\")\n\n-- Return count of words that contain pattern\nfunction count (pattern, wordList)\n local total = 0\n for word in wordList:gmatch(\"%S+\") do\n if word:match(pattern) then total = total + 1 end\n end\n return total\nend\n\n-- Check plausibility of case given its opposite\nfunction plaus (case, opposite, words)\n if count(case, words) > 2 * count(opposite, words) then\n print(\"PLAUSIBLE\")\n return true\n else\n print(\"IMPLAUSIBLE\")\n return false\n end\nend\n\n-- Main procedure\nlocal page = http.request(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\")\nio.write(\"I before E when not preceded by C: \")\nlocal sub1 = plaus(\"[^c]ie\", \"cie\", page)\nio.write(\"E before I when preceded by C: \")\nlocal sub2 = plaus(\"cei\", \"[^c]ei\", page)\nio.write(\"Overall the phrase is \")\nif not (sub1 and sub2) then io.write(\"not \") end\nprint(\"plausible.\")"} {"title": "Identity matrix", "language": "Lua", "task": "Build an identity matrix of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', \nwhere the diagonal elements are all '''1'''s (ones), \nand all the other elements are all '''0'''s (zeroes).\n\n\nI_n = \\begin{bmatrix}\n 1 & 0 & 0 & \\cdots & 0 \\\\\n 0 & 1 & 0 & \\cdots & 0 \\\\\n 0 & 0 & 1 & \\cdots & 0 \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\cdots & 1 \\\\\n\\end{bmatrix}\n\n\n;Related tasks:\n* [[Spiral matrix]]\n* [[Zig-zag matrix]] \n* [[Ulam_spiral_(for_primes)]]\n\n", "solution": "function identity_matrix (size)\n local m = {}\n for i = 1, size do\n m[i] = {}\n for j = 1, size do\n m[i][j] = i == j and 1 or 0\n end\n end\n return m\nend\n\nfunction print_matrix (m)\n for i = 1, #m do\n print(table.concat(m[i], \" \"))\n end\nend\n\nprint_matrix(identity_matrix(5))"} {"title": "Idiomatically determine all the characters that can be used for symbols", "language": "Lua", "task": "Idiomatically determine all the characters that can be used for ''symbols''.\nThe word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''.\n\nThe method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n\n;Task requirements\n\nDisplay the set of all the characters that can be used for symbols which can be used (allowed) by the computer program. \nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\nNote that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned).\n\n;See also\n* Idiomatically determine all the lowercase and uppercase letters.\n\n", "solution": "function isValidIdentifier(id)\n local reserved = {\n [\"and\"]=true, [\"break\"]=true, [\"do\"]=true, [\"end\"]=true, [\"else\"]=true, [\"elseif\"]=true, [\"end\"]=true,\n [\"false\"]=true, [\"for\"]=true, [\"function\"]=true, [\"goto\"]=true, [\"if\"]=true, [\"in\"]=true,\n [\"local\"]=true, [\"nil\"]=true, [\"not\"]=true, [\"or\"]=true, [\"repeat\"]=true, [\"return\"]=true,\n [\"then\"]=true, [\"true\"]=true, [\"until\"]=true, [\"while\"]=true }\n return id:find(\"^[a-zA-Z_][a-zA-Z0-9_]*$\") ~= nil and not reserved[id]\nend\nvfc, vsc = {}, {}\nfor i = 0, 255 do\n local c = string.char(i)\n if isValidIdentifier(c) then vfc[#vfc+1]=c end\n if isValidIdentifier(\"_\"..c) then vsc[#vsc+1]=c end\nend\nprint(\"Valid First Characters: \" .. table.concat(vfc))\nprint(\"Valid Subsequent Characters: \" .. table.concat(vsc))"} {"title": "Idiomatically determine all the lowercase and uppercase letters", "language": "Lua", "task": "Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.\nThe method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n \n\n;Task requirements\n\nDisplay the set of all:\n::::::* lowercase letters \n::::::* uppercase letters\n\nthat can be used (allowed) by the computer program,\n\nwhere ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. \n\n\nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\n\n;See also\n* Idiomatically determine all the characters that can be used for symbols.\n\n", "solution": "function ASCIIstring (pattern)\n local matchString, ch = \"\"\n for charNum = 0, 255 do\n ch = string.char(charNum)\n if string.match(ch, pattern) then\n matchString = matchString .. ch\n end\n end\n return matchString\nend\n\nprint(ASCIIstring(\"%l\"))\nprint(ASCIIstring(\"%u\"))\n"} {"title": "Integer overflow", "language": "Lua", "task": "Some languages support one or more integer types of the underlying processor.\n\nThis integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.\nThe integers supported by such a type can be ''signed'' or ''unsigned''.\n\nArithmetic for machine level integers can often be done by single CPU instructions.\nThis allows high performance and is the main reason to support machine level integers.\n\n\n;Definition:\nAn integer overflow happens when the result of a computation does not fit into the fixed size integer.\nThe result can be too small or too big to be representable in the fixed size integer.\n\n\n;Task:\nWhen a language has fixed size integer types, create a program that\ndoes arithmetic computations for the fixed size integers of the language.\n\nThese computations must be done such that the result would overflow.\n\nThe program should demonstrate what the following expressions do.\n\n\nFor 32-bit signed integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit signed integer\n|-\n| -(-2147483647-1)\n| 2147483648\n|-\n| 2000000000 + 2000000000\n| 4000000000\n|-\n| -2147483647 - 2147483647\n| -4294967294\n|-\n| 46341 * 46341\n| 2147488281\n|-\n| (-2147483647-1) / -1\n| 2147483648\n|}\n\nFor 64-bit signed integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit signed integer\n|-\n| -(-9223372036854775807-1)\n| 9223372036854775808\n|-\n| 5000000000000000000+5000000000000000000\n| 10000000000000000000\n|-\n| -9223372036854775807 - 9223372036854775807\n| -18446744073709551614\n|-\n| 3037000500 * 3037000500\n| 9223372037000250000\n|-\n| (-9223372036854775807-1) / -1\n| 9223372036854775808\n|}\n\nFor 32-bit unsigned integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit unsigned integer\n|-\n| -4294967295\n| -4294967295\n|-\n| 3000000000 + 3000000000\n| 6000000000\n|-\n| 2147483647 - 4294967295\n| -2147483648\n|-\n| 65537 * 65537\n| 4295098369\n|}\n\nFor 64-bit unsigned integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit unsigned integer\n|-\n| -18446744073709551615\n| -18446744073709551615\n|-\n| 10000000000000000000 + 10000000000000000000\n| 20000000000000000000\n|-\n| 9223372036854775807 - 18446744073709551615\n| -9223372036854775808\n|-\n| 4294967296 * 4294967296\n| 18446744073709551616\n|}\n\n\n;Notes:\n:* When the integer overflow does trigger an exception show how the exception is caught.\n:* When the integer overflow produces some value, print it.\n:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.\n:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.\n:* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.\n\n", "solution": "assert(math.type~=nil, \"Lua 5.3+ required for this test.\")\nminint, maxint = math.mininteger, math.maxinteger\nprint(\"min, max int64 = \" .. minint .. \", \" .. maxint)\nprint(\"min-1 underflow = \" .. (minint-1) .. \" equals max? \" .. tostring(minint-1==maxint))\nprint(\"max+1 overflow = \" .. (maxint+1) .. \" equals min? \" .. tostring(maxint+1==minint))"} {"title": "Integer sequence", "language": "Lua", "task": "Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.\n\nIf appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.\n\n", "solution": "i = 1\n\n-- in the event that the number inadvertently wraps around,\n-- stop looping - this is unlikely with Lua's default underlying\n-- number type (double), but on platform without double\n-- the C type used for numbers can be changed\nwhile i > 0 do\n print( i )\n i = i + 1\nend\n"} {"title": "Inverted syntax", "language": "Lua", "task": "'''Inverted syntax with conditional expressions'''\n\nIn traditional syntax conditional expressions are usually shown before the action within a statement or code block:\n\n IF raining=true THEN needumbrella=true \n\nIn inverted syntax, the action is listed before the conditional expression in the statement or code block:\n\n needumbrella=true IF raining=true \n\n'''Inverted syntax with assignment'''\n\nIn traditional syntax, assignments are usually expressed with the variable appearing before the expression:\n\n a = 6\n\nIn inverted syntax, the expression appears before the variable:\n 6 = a\n\n'''Task'''\n\nThe task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.\n", "solution": "a = {1,3,5,4,2} -- a \"plain\" table\ntable.sort(a) -- library method passing a as param\nprint(table.concat(a)) -- and again --> \"12345\"\n\nb = {1,3,5,4,2} -- a \"plain\" table, so far..\nsetmetatable(b, {__index=table}) -- ..but now \"meta-decorated\"\nb:sort() -- syntax sugar passes b as \"self\"\nprint(b:concat()) -- and again --> \"12345\""} {"title": "Isqrt (integer square root) of X", "language": "Lua from C", "task": "Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a\nreal non-negative number.\n\nOften '''X''' is actually a non-negative integer.\n\nFor the purposes of this task, '''X''' can be an integer or a real number, but if it\nsimplifies things in your computer programming language, assume it's an integer.\n\n\nOne of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or\nprimes) up to the \n X of that\ninteger, either to find the factors of that integer, or to determine primality.\n\n\nAn alternative method for finding the '''Isqrt''' of a number is to\ncalculate: floor( sqrt(X) ) \n::* where '''sqrt''' is the square root function for non-negative real numbers, and\n::* where '''floor''' is the floor function for real numbers.\n\n\nIf the hardware supports the computation of (real) square roots, the above method might be a faster method for\nsmall numbers that don't have very many significant (decimal) digits.\n\nHowever, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support.\n\n\n;Pseudo-code using quadratic residue:\nFor this task, the integer square root of a non-negative number will be computed using a version\nof ''quadratic residue'', which has the advantage that no ''floating point'' calculations are\nused, only integer arithmetic. \n\nFurthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions.\n\nThe disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.\n\n\nPseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers):\n q <-- 1 /*initialize Q to unity. */\n /*find a power of 4 that's greater than X.*/\n perform while q <= x /*perform while Q <= X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n /*Q is now greater than X.*/\n z <-- x /*set Z to the value of X.*/\n r <-- 0 /*initialize R to zero. */\n perform while q > 1 /*perform while Q > unity. */\n q <-- q / 4 /*integer divide by four. */\n t <-- z - r - q /*compute value of T. */\n r <-- r / 2 /*integer divide by two. */\n if t >= 0 then do \n z <-- t /*set Z to value of T. */\n r <-- r + q /*compute new value of R. */\n end\n end /*perform*/\n /*R is now the Isqrt(X). */\n \n /* Sidenote: Also, Z is now the remainder after square root (i.e. */\n /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */\n\nAnother version for the (above) 1st '''perform''' is:\n perform until q > X /*perform until Q > X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n\n\nInteger square roots of some values:\n Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9\n Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10\n Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10\n Isqrt( 3) is 1 Isqrt(63) is 7\n Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10\n Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11\n Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11\n Isqrt( 7) is 2 Isqrt(67) is 8\n Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11\n Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12\n Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12\n\n\n;Task:\nCompute and show all output here (on this page) for:\n::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format.\n::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format.\n::* use commas in the displaying of larger numbers.\n\n\nYou can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.\nIf your computer programming language only supports smaller integers, show what you can.\n\n\n;Related tasks:\n:* sequence of non-squares\n:* integer roots\n:* square root by hand\n\n", "solution": "function isqrt(x)\n local q = 1\n local r = 0\n while q <= x do\n q = q << 2\n end\n while q > 1 do\n q = q >> 2\n local t = x - r - q\n r = r >> 1\n if t >= 0 then\n x = t\n r = r + q\n end\n end\n return r\nend\n\nprint(\"Integer square root for numbers 0 to 65:\")\nfor n=0,65 do\n io.write(isqrt(n) .. ' ')\nend\nprint()\nprint()\n\nprint(\"Integer square roots of oddd powers of 7 from 1 to 21:\")\nprint(\" n | 7 ^ n | isqrt(7 ^ n)\")\nlocal p = 7\nlocal n = 1\nwhile n <= 21 do\n print(string.format(\"%2d | %18d | %12d\", n, p, isqrt(p)))\n ----------------------\n n = n + 2\n p = p * 49\nend"} {"title": "Iterated digits squaring", "language": "Lua", "task": "If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:\n15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89\n7 -> 49 -> 97 -> 130 -> 10 -> 1\n\nAn example in Python:\n\n>>> step = lambda x: sum(int(d) ** 2 for d in str(x))\n>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))\n>>> [iterate(x) for x in xrange(1, 20)]\n[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]\n\n\n;Task:\n: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.\nOr, for much less credit - (showing that your algorithm and/or language is slow):\n: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.\n\nThis problem derives from the Project Euler problem 92.\n\nFor a quick algorithm for this task see the talk page\n\n\n;Related tasks:\n* [[Combinations with repetitions]]\n* [[Digital root]]\n* [[Digital root/Multiplicative digital root]]\n\n", "solution": "squares = {}\n\nfor i = 0, 9 do\n for j = 0, 9 do\n squares[i * 10 + j] = i * i + j * j\n end\nend\n\nfor i = 1, 99 do\n for j = 0, 99 do\n squares[i * 100 + j] = squares[i] + squares[j]\n end\nend\n\nfunction sum_squares(n)\n if n < 9999.5 then\n return squares[n]\n else\n local m = math.floor(n / 10000)\n return squares[n - 10000 * m] + sum_squares(m)\n end\nend\n\nmemory = {}\n\nfunction calc_1_or_89(n)\n local m = {}\n n = memory[n] or n\n while n ~= 1 and n ~= 89 do\n n = memory[n] or sum_squares(n)\n table.insert(m, n)\n end\n for _, i in pairs(m) do\n memory[i] = n\n end\n return n\nend\n\ncounter = 0\n\nfor i = 1, 100000000 do\n if calc_1_or_89(i) == 89 then\n counter = counter + 1\n end\nend\n\nprint(counter)"} {"title": "JSON", "language": "Lua", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": "local json = require(\"json\")\n\nlocal json_data = [=[[\n 42,\n 3.14159,\n [ 2, 4, 8, 16, 32, 64, \"apples\", \"bananas\", \"cherries\" ],\n { \"H\": 1, \"He\": 2, \"X\": null, \"Li\": 3 },\n null,\n true,\n false\n]]=]\n\nprint(\"Original JSON: \" .. json_data)\nlocal data = json.decode(json_data)\njson.util.printValue(data, 'Lua')\nprint(\"JSON re-encoded: \" .. json.encode(data))\n\nlocal data = {\n 42,\n 3.14159,\n {\n 2, 4, 8, 16, 32, 64,\n \"apples\",\n \"bananas\",\n \"cherries\"\n },\n {\n H = 1,\n He = 2,\n X = json.util.null(),\n Li = 3\n },\n json.util.null(),\n true,\n false\n}\n\nprint(\"JSON from new Lua data: \" .. json.encode(data))"} {"title": "Jewels and stones", "language": "Lua from C", "task": "Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by this problem.\n\n\n\n", "solution": "function count_jewels(s, j)\n local count = 0\n for i=1,#s do\n local c = s:sub(i,i)\n if string.match(j, c) then\n count = count + 1\n end\n end\n return count\nend\n\nprint(count_jewels(\"aAAbbbb\", \"aA\"))\nprint(count_jewels(\"ZZ\", \"z\"))"} {"title": "Julia set", "language": "Lua", "task": "Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* Mandelbrot Set\n\n", "solution": "local cmap = { [0]=\" \", \".\", \":\", \"-\", \"=\", \"+\", \"*\", \"#\", \"%\", \"$\", \"@\" }\nfor y = -1.0, 1.0, 0.05 do\n for x = -1.5, 1.5, 0.025 do\n local zr, zi, i = x, y, 0\n while i < 100 do\n zr, zi = zr*zr - zi*zi - 0.79, zr * zi * 2 + 0.15\n if (zr*zr + zi*zi > 4) then break else i = i + 1 end\n end\n io.write(cmap[math.floor(i/10)])\n end\n print()\nend"} {"title": "Jump anywhere", "language": "Lua", "task": "Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.\n\nThis task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. \nFor the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. \nThis task provides a \"grab bag\" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!\n\n* Some languages can ''go to'' any global label in a program.\n* Some languages can break multiple function calls, also known as ''unwinding the call stack''.\n* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).\n\nThese jumps are not all alike. \nA simple ''goto'' never touches the call stack. \nA continuation saves the call stack, so you can continue a function call after it ends.\n\n\n;Task:\nUse your language to demonstrate the various types of jumps that it supports. \n\nBecause the possibilities vary by language, this task is not specific. \nYou have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].\n\n", "solution": "-- Forward jump\ngoto skip_print\nprint \"won't print\"\n::skip_print::\n\n-- Backward jump\n::loop::\nprint \"infinite loop\"\ngoto loop\n\n-- Labels follow the same scoping rules as local variables, but with no equivalent of upvalues\ngoto next\ndo\n ::next:: -- not visible to above goto\n print \"won't print\"\nend\n::next:: -- goto actually jumps here\n\n-- goto cannot jump into or out of a function\n::outside::\nfunction nope () goto outside end -- error: no visible label 'outside' for at line 2\n\ngoto inside\nfunction nope () ::inside:: end -- error: no visible label 'inside' for at line 1\n\n-- Convenient for breaking out of nested loops\nfor i = 1, 10 do\n for j = 1, 10 do\n for k = 1, 10 do\n if i^2 + j^2 == k^2 then\n print((\"found: i=%d j=%d k=%d\"):format(i, j, k))\n goto exit\n end\n end\n end\nend\nprint \"not found\"\n::exit::"} {"title": "Kaprekar numbers", "language": "Lua", "task": "A positive integer is a Kaprekar number if:\n* It is '''1''' (unity)\n* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. \nNote that a split resulting in a part consisting purely of 0s is not valid, \nas 0 is not considered positive.\n\n\n;Example Kaprekar numbers:\n* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.\n* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....\n\n\n;Example process:\n10000 (1002) splitting from left to right:\n* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.\n* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.\n\n\n;Task:\nGenerate and show all Kaprekar numbers less than 10,000. \n\n\n;Extra credit:\nOptionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.\n\n\n;Extra extra credit:\nThe concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); \nif you can, show that Kaprekar numbers exist in other bases too. \n\n\nFor this purpose, do the following:\n* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);\n* Display each of them in base 10 representation;\n* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. \n \nFor example, 225(10) is \"d4\" in base 17, its square \"a52g\", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g\n\n\n;Reference:\n* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version\n\n\n;Related task:\n* [[Casting out nines]]\n\n", "solution": "-- Return length of an integer without string conversion\nfunction numLength (n)\n local length = 0\n repeat\n n = math.floor(n / 10)\n length = length + 1\n until n == 0\n return length\nend\n\n-- Return a boolean indicating whether n is a Kaprekar number\nfunction isKaprekar (n)\n if n == 1 then return true end\n local nSquared, a, b = n * n\n for splitPoint = 1, numLength(nSquared) - 1 do\n a = math.floor(nSquared / 10^splitPoint)\n b = nSquared % 10^splitPoint\n if a > 0 and b > 0 and a + b == n then return true end\n end\n return false\nend\n\n-- Main task\nfor n = 1, 10^4 do\n if isKaprekar(n) then io.write(n .. \" \") end\nend\n \n-- Extra credit\nlocal count = 0\nfor n = 1, 10^6 do\n if isKaprekar(n) then count = count + 1 end\nend\nprint(\"\\nThere are \" .. count .. \" Kaprekar numbers under one million.\")"} {"title": "Kernighans large earthquake problem", "language": "Lua", "task": "Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.\n\n;Problem:\nYou are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.\n\nExample lines from the file would be lines like:\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n\n;Task:\n* Create a program or script invocation to find all the events with magnitude greater than 6\n* Assuming an appropriate name e.g. \"data.txt\" for the file:\n:# Either: Show how your program is invoked to process a data file of that name.\n:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).\n\n", "solution": "-- arg[1] is the first argument provided at the command line\nfor line in io.lines(arg[1] or \"data.txt\") do -- use data.txt if arg[1] is nil\n magnitude = line:match(\"%S+$\")\n if tonumber(magnitude) > 6 then print(line) end\nend"} {"title": "Knight's tour", "language": "Lua", "task": "Task\nProblem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be \"closed\"; that is, the knight need not end within a single move of its start position.\n\nInput and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "N = 8\n\nmoves = { {1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2} }\n\nfunction Move_Allowed( board, x, y )\n if board[x][y] >= 8 then return false end\n\n local new_x, new_y = x + moves[board[x][y]+1][1], y + moves[board[x][y]+1][2] \n if new_x >= 1 and new_x <= N and new_y >= 1 and new_y <= N and board[new_x][new_y] == 0 then return true end\n \n return false\nend\n\n\t\t \nboard = {}\nfor i = 1, N do\n board[i] = {}\n for j = 1, N do\n board[i][j] = 0\n end\nend\n\nx, y = 1, 1\n\nlst = {}\nlst[1] = { x, y }\n\nrepeat\n if Move_Allowed( board, x, y ) then\n board[x][y] = board[x][y] + 1\n x, y = x+moves[board[x][y]][1], y+moves[board[x][y]][2]\n lst[#lst+1] = { x, y }\n else\n if board[x][y] >= 8 then\n board[x][y] = 0\n lst[#lst] = nil\n if #lst == 0 then\n print \"No solution found.\"\n os.exit(1)\n end\n x, y = lst[#lst][1], lst[#lst][2]\n end\n board[x][y] = board[x][y] + 1 \n end\nuntil #lst == N^2\n\nlast = lst[1]\nfor i = 2, #lst do\n print( string.format( \"%s%d - %s%d\", string.sub(\"ABCDEFGH\",last[1],last[1]), last[2], string.sub(\"ABCDEFGH\",lst[i][1],lst[i][1]), lst[i][2] ) )\n last = lst[i]\nend"} {"title": "Koch curve", "language": "Lua", "task": "Draw a Koch curve. See details: Koch curve\n\n", "solution": "local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi\n\nfunction Bitmap:render()\n for y = 1, self.height do\n print(table.concat(self.pixels[y]))\n end\nend\n\nfunction Bitmap:drawKochPath(path, x, y, angle, speed, color)\n local rules = {\n [\"+\"] = function() angle = angle + pi/3 end,\n [\"-\"] = function() angle = angle - pi/3 end,\n [\"F\"] = function()\n local nx, ny = x+speed*cos(angle), y+speed*sin(angle)\n self:line(floor(x*2+0.5), floor(y+0.5), floor(nx*2+0.5), floor(ny+0.5), color)\n x, y = nx, ny\n end\n }\n path:gsub(\"(.)\", function(c) rules[c]() end)\nend\n\nfunction LSystem(axiom, rules, reps)\n for i = 1, reps do\n axiom = axiom:gsub(\"(.)\", function(c) return rules[c] or c end)\n end\n return axiom\nend\nfunction KochPath(reps) return LSystem(\"F--F--F--\", { F = \"F+F--F+F\" }, reps) end\n\ndemos = {\n { n=0, w= 11, h= 6, x=1, y= 4 },\n { n=1, w= 22, h=14, x=1, y= 9 },\n { n=2, w= 60, h=34, x=1, y=24 },\n { n=3, w=168, h=96, x=1, y=71 }\n}\nfor _,d in ipairs(demos) do\n bitmap = Bitmap(d.w, d.h)\n bitmap:clear(\".\")\n bitmap:drawKochPath(KochPath(d.n), d.x, d.y, 0, 3, \"@\")\n bitmap:render()\n print()\nend"} {"title": "Kolakoski sequence", "language": "Lua from C", "task": "The natural numbers, (excluding zero); with the property that:\n: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.\n\n;Example:\nThis is ''not'' a Kolakoski sequence:\n1,1,2,2,2,1,2,2,1,2,...\nIts sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:\n\n: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...\n\nThe above gives the RLE of:\n2, 3, 1, 2, 1, ...\n\nThe original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.\n\n;Creating a Kolakoski sequence:\n\nLets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....\n\n# We start the sequence s with the first item from the cycle c: 1\n# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. \nWe will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.\n\nWe started s with 1 and therefore s[k] states that it should appear only the 1 time.\n\nIncrement k\nGet the next item from c and append it to the end of sequence s. s will then become: 1, 2\nk was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2\nIncrement k\nAppend the next item from the cycle to the list: 1, 2,2, 1\nk is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1\nincrement k\n\n...\n\n'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.\n\n;Task:\n# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.\n# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.\n# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).\n# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 20 members of the sequence generated from (2, 1)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)\n# Check the sequence againt its RLE.\n(There are rules on generating Kolakoski sequences from this method that are broken by the last example)\n\n", "solution": "function next_in_cycle(c,length,index)\n local pos = index % length\n return c[pos]\nend\n\nfunction kolakoski(c,s,clen,slen)\n local i = 0\n local k = 0\n\n while true do\n s[i] = next_in_cycle(c,clen,k)\n if s[k] > 1 then\n for j=1,s[k]-1 do\n i = i + 1\n if i == slen then\n return nil\n end\n s[i] = s[i - 1]\n end\n end\n i = i + 1\n if i == slen then\n return nil\n end\n k = k + 1\n end\n return nil\nend\n\nfunction possible_kolakoski(s,length)\n local j = 0\n local prev = s[0]\n local count = 1\n local rle = {}\n local result = \"True\"\n\n for i=0,length do\n rle[i] = 0\n end\n\n for i=1,length-1 do\n if s[i] == prev then\n count = count + 1\n else\n rle[j] = count\n j = j + 1\n count = 1\n prev = s[i]\n end\n end\n\n -- no point adding the final 'count' to rle as we're not going to compare it anyway\n for i=0,j-1 do\n if rle[i] ~= s[i] then\n result = \"False\"\n break\n end\n end\n\n return result\nend\n\nfunction print_array(a)\n io.write(\"[\")\n for i=0,#a do\n if i>0 then\n io.write(\", \")\n end\n io.write(a[i])\n end\n io.write(\"]\")\nend\n\n-- main\nlocal c0 = {[0]=1, [1]=2}\nlocal c1 = {[0]=2, [1]=1}\nlocal c2 = {[0]=1, [1]=3, [2]=1, [3]=2}\nlocal c3 = {[0]=1, [1]=3, [2]=2, [3]=1}\n\nlocal cs = {[0]=c0, [1]=c1, [2]=c2, [3]=c3}\nlocal clens = {[0]=2, [1]=2, [2]=4, [3]=4}\nlocal slens = {[0]=20, [1]=20, [2]=30, [3]=30}\n\nfor i=0,3 do\n local clen = clens[i]\n local slen = slens[i]\n local s = {}\n\n for j=0,slen-1 do\n s[j] = 0\n end\n\n kolakoski(cs[i],s,clen,slen)\n io.write(string.format(\"First %d members of the sequence generated by \", slen))\n print_array(cs[i])\n print(\":\")\n print_array(s)\n print()\n\n local p = possible_kolakoski(s,slen)\n print(string.format(\"Possible Kolakoski sequence? %s\", p))\n\n print()\nend"} {"title": "Kosaraju", "language": "Lua from C++", "task": "{{wikipedia|Graph}}\n\n\nKosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.\n\nFor this task consider the directed graph with these connections:\n 0 -> 1\n 1 -> 2\n 2 -> 0\n 3 -> 1, 3 -> 2, 3 -> 4\n 4 -> 3, 4 -> 5\n 5 -> 2, 5 -> 6\n 6 -> 5\n 7 -> 4, 7 -> 6, 7 -> 7\n\nAnd report the kosaraju strongly connected component for each node.\n\n;References:\n* The article on Wikipedia.\n\n", "solution": "function write_array(a)\n io.write(\"[\")\n for i=0,#a do\n if i>0 then\n io.write(\", \")\n end\n io.write(tostring(a[i]))\n end\n io.write(\"]\")\nend\n\nfunction kosaraju(g)\n -- 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.\n local size = #g\n\n local vis = {}\n for i=0,size do\n -- all false by default\n vis[i] = false\n end\n\n local l = {}\n for i=0,size do\n -- all zero by default\n l[i] = 0\n end\n\n local x = size+1 -- index for filling l in reverse order\n\n local t = {} -- transpose graph\n\n -- Recursive subroutine 'visit'\n function visit(u)\n if not vis[u] then\n vis[u] = true\n for i=0,#g[u] do\n local v = g[u][i]\n visit(v)\n if t[v] then\n local a = t[v]\n a[#a+1] = u\n else\n t[v] = {[0]=u}\n end\n end\n x = x - 1\n l[x] = u\n end\n end\n\n -- 2. For each vertex u of the graph do visit(u)\n for i=0,#g do\n visit(i)\n end\n local c = {}\n for i=0,size do\n -- used for component assignment\n c[i] = 0\n end\n\n -- Recursive subroutine 'assign'\n function assign(u, root)\n if vis[u] then -- repurpose vis to mean 'unassigned'\n vis[u] = false\n c[u] = root\n for i=0,#t[u] do\n local v = t[u][i]\n assign(v, root)\n end\n end\n end\n\n -- 3: For each element u of l in order, do assign(u, u)\n for i=0,#l do\n local u = l[i]\n assign(u, u)\n end\n\n return c\nend\n\n-- main\nlocal g = {\n [0]={[0]=1},\n [1]={[0]=2},\n [2]={[0]=0},\n [3]={[0]=1, [1]=2, [2]=4},\n [4]={[0]=3, [1]=5},\n [5]={[0]=2, [1]=6},\n [6]={[0]=5},\n [7]={[0]=4, [1]=6, [2]=7},\n}\n\nwrite_array(kosaraju(g))\nprint()"} {"title": "Largest int from concatenated ints", "language": "Lua from Python", "task": "Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.\n\nUse the following two sets of integers as tests and show your program output here.\n\n:::::* {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* {54, 546, 548, 60}\n\n\n;Possible algorithms:\n# A solution could be found by trying all combinations and return the best. \n# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.\n# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.\n\n\n;See also:\n* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?\n* Constructing the largest number possible by rearranging a list\n\n", "solution": "function icsort(numbers)\n\ttable.sort(numbers,function(x,y) return (x..y) > (y..x) end)\n\treturn numbers\nend\n\nfor _,numbers in pairs({{1, 34, 3, 98, 9, 76, 45, 4}, {54, 546, 548, 60}}) do\t\n\tprint(('Numbers: {%s}\\n Largest integer: %s'):format(\n\t\ttable.concat(numbers,\",\"),table.concat(icsort(numbers))\n\t))\nend"} {"title": "Largest number divisible by its digits", "language": "Lua", "task": "Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the\n(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.\n\n\nNote that the digit zero (0) can not be in the number as integer division by zero is undefined. \n\nThe digits must all be unique so a base ten number will have at most '''9''' digits.\n\nFeel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)\n\n\n;Stretch goal:\nDo the same thing for hexadecimal.\n\n\n;Related tasks:\n:* gapful numbers.\n:* palindromic gapful numbers. \n\n\n;Also see:\n:* The OEIS sequence: A115569: Lynch-Bell numbers. \n\n", "solution": "function isDivisible(n)\n local t = n\n local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}\n\n while t ~= 0 do\n local r = t % 10\n if r == 0 then\n return false\n end\n if n % r ~= 0 then\n return false\n end\n if a[r + 1] > 0 then\n return false\n end\n a[r + 1] = 1\n t = math.floor(t / 10)\n end\n\n return true\nend\n\nfor i=9999999999,0,-1 do\n if isDivisible(i) then\n print(i)\n break\n end\nend\n"} {"title": "Last Friday of each month", "language": "Lua", "task": "Write a program or a script that returns the date of the last Fridays of each month of a given year. \n\nThe year may be given through any simple input method in your language (command line, std in, etc).\n\n\nExample of an expected output:\n./last_fridays 2012\n2012-01-27\n2012-02-24\n2012-03-30\n2012-04-27\n2012-05-25\n2012-06-29\n2012-07-27\n2012-08-31\n2012-09-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n\n;Related tasks\n* [[Five weekends]]\n* [[Day of the week]]\n* [[Find the last Sunday of each month]]\n\n", "solution": "function isLeapYear (y)\n return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0\nend\n\nfunction dayOfWeek (y, m, d)\n local t = os.time({year = y, month = m, day = d})\n return os.date(\"%A\", t)\nend\n\nfunction lastWeekdays (wday, year)\n local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}\n if isLeapYear(year) then monthLength[2] = 29 end\n for month = 1, 12 do\n day = monthLength[month]\n while dayOfWeek(year, month, day) ~= wday do day = day - 1 end\n print(year .. \"-\" .. month .. \"-\" .. day)\n end\nend\n\nlastWeekdays(\"Friday\", tonumber(arg[1]))"} {"title": "Last letter-first letter", "language": "Lua", "task": "A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \"animals\" as the category,\n\nChild 1: dog \nChild 2: goldfish\nChild 1: hippopotamus\nChild 2: snake\n...\n\n\n\n;Task:\nTake the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. \n\nNo Pokemon name is to be repeated.\n\n\naudino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\ncresselia croagunk darmanitan deino emboar emolga exeggcute gabite\ngirafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\nkricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\nnosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\nsealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\ntyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\n\n\n\nExtra brownie points for dealing with the full list of 646 names.\n\n", "solution": "-- BUILDING:\npokemon = [[\naudino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\ncresselia croagunk darmanitan deino emboar emolga exeggcute gabite\ngirafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\nkricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\nnosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\nsealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\ntyrogue vigoroth vulpix wailord wartortle whismur wingull yamask]]\nwords, inits, succs = {}, {}, {}\nfor word in pokemon:gmatch(\"%S+\") do\n table.insert(words, word)\n local ch = word:sub(1,1)\n inits[ch] = inits[ch] or {}\n table.insert(inits[ch], word)\nend\nfor _,word in pairs(words) do\n succs[word] = {}\n local ch = word:sub(-1,-1)\n if inits[ch] then\n for _,succ in pairs(inits[ch]) do\n if succ~=word then\n table.insert(succs[word],succ)\n end\n end\n end\nend\n\n-- SEARCHING:\nfunction expand(list, used, answer)\n local word = list[#list]\n for _,succ in ipairs(succs[word]) do\n if not used[succ] then\n used[succ] = true\n list[#list+1] = succ\n if #list == answer.len then\n local perm = table.concat(list,\" \")\n answer.perms[perm] = perm\n answer.num = answer.num + 1\n elseif #list > answer.len then\n answer.len = #list\n local perm = table.concat(list,\" \")\n answer.perms = {[perm] = perm}\n answer.num = 1\n end\n expand(list, used, answer)\n list[#list] = nil\n used[succ] = nil\n end\n end\nend\nanswers = {}\nfor _,word in ipairs(words) do\n local answer = { word=word, len=0, num=0, perms={} }\n answers[#answers+1] = answer\n expand({word}, {[word]=true}, answer)\nend\n\n-- REPORTING:\ntable.sort(answers, function(a,b) return a.len 0 do\n l = l - 1\n if (t % 2) == 1 then\n io.write('(')\n else\n io.write(')')\n end\n t = t >> 1\n end\nend\n\nfunction listTrees(n)\n local i = offset[n]\n while i < offset[n + 1] do\n show(tree_list[i + 1], n * 2)\n print()\n i = i + 1\n end\nend\n\nfunction assemble(m, t, sl, pos, rem)\n if rem == 0 then\n append(t)\n return\n end\n\n local pp = pos\n local ss = sl\n\n if sl > rem then\n ss = rem\n pp = offset[ss]\n elseif pp >= offset[ss + 1] then\n ss = ss - 1\n if ss == 0 then\n return\n end\n pp = offset[ss]\n end\n\n assemble(n, t << (2 * ss) | tree_list[pp + 1], ss, pp, rem - ss)\n assemble(n, t, ss, pp + 1, rem)\nend\n\nfunction makeTrees(n)\n if offset[n + 1] ~= 0 then\n return\n end\n if n > 0 then\n makeTrees(n - 1)\n end\n assemble(n, 0, n - 1, offset[n - 1], n - 1)\n offset[n + 1] = #tree_list\nend\n\nfunction test(n)\n append(0)\n\n makeTrees(n)\n print(string.format(\"Number of %d-trees: %d\", n, offset[n+1] - offset[n]))\n listTrees(n)\nend\n\ninit()\ntest(5)"} {"title": "Long literals, with continuations", "language": "Lua", "task": "This task is about writing a computer program that has long literals (character\nliterals that may require specifying the words/tokens on more than one (source)\nline, either with continuations or some other method, such as abutments or\nconcatenations (or some other mechanisms).\n\n\nThe literal is to be in the form of a \"list\", a literal that contains many\nwords (tokens) separated by a blank (space), in this case (so as to have a\ncommon list), the (English) names of the chemical elements of the periodic table.\n\n\nThe list is to be in (ascending) order of the (chemical) element's atomic number:\n\n ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''\n\n... up to the last known (named) chemical element (at this time).\n\n\nDo not include any of the \"unnamed\" chemical element names such as:\n\n ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''\n\n\nTo make computer programming languages comparable, the statement widths should be\nrestricted to less than '''81''' bytes (characters), or less\nif a computer programming language has more restrictive limitations or standards.\n\nAlso mention what column the programming statements can start in if ''not'' \nin column one.\n\n\nThe list ''may'' have leading/embedded/trailing blanks during the\ndeclaration (the actual program statements), this is allow the list to be\nmore readable. The \"final\" list shouldn't have any leading/trailing or superfluous\nblanks (when stored in the program's \"memory\").\n\nThis list should be written with the idea in mind that the\nprogram ''will'' be updated, most likely someone other than the\noriginal author, as there will be newer (discovered) elements of the periodic\ntable being added (possibly in the near future). These future updates\nshould be one of the primary concerns in writing these programs and it should be \"easy\"\nfor someone else to add chemical elements to the list (within the computer\nprogram).\n\nAttention should be paid so as to not exceed the ''clause length'' of\ncontinued or specified statements, if there is such a restriction. If the\nlimit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.\n\n\n;Task:\n:* Write a computer program (by whatever name) to contain a list of the known elements.\n:* The program should eventually contain a long literal of words (the elements).\n:* The literal should show how one could create a long list of blank-delineated words.\n:* The \"final\" (stored) list should only have a single blank between elements.\n:* Try to use the most idiomatic approach(es) in creating the final list.\n:* Use continuation if possible, and/or show alternatives (possibly using concatenation).\n:* Use a program comment to explain what the continuation character is if it isn't obvious.\n:* The program should contain a variable that has the date of the last update/revision.\n:* The program, when run, should display with verbiage:\n:::* The last update/revision date (and should be unambiguous).\n:::* The number of chemical elements in the list.\n:::* The name of the highest (last) element name.\n\n\nShow all output here, on this page.\n\n\n\n", "solution": "revised = \"February 2, 2021\"\n-- the long literal string is delimited by double square brackets: [[...]]\n-- each word must be separated by at least one whitespace character\n-- additional whitespace may optionally be used to improve readability\n-- (starting column does not matter, clause length is more than adequate)\nlongliteral = [[\n hydrogen helium lithium beryllium\n boron carbon nitrogen oxygen\n fluorine neon sodium magnesium\n aluminum silicon phosphorous sulfur\n chlorine argon potassium calcium\n scandium titanium vanadium chromium\n manganese iron cobalt nickel\n copper zinc gallium germanium\n arsenic selenium bromine krypton\n rubidium strontium yttrium zirconium\n niobium molybdenum technetium ruthenium\n rhodium palladium silver cadmium\n indium tin antimony tellurium\n iodine xenon cesium barium\n lanthanum cerium praseodymium neodymium\n promethium samarium europium gadolinium\n terbium dysprosium holmium erbium\n thulium ytterbium lutetium hafnium\n tantalum tungsten rhenium osmium\n iridium platinum gold mercury\n thallium lead bismuth polonium\n astatine radon francium radium\n actinium thorium protactinium uranium\n neptunium plutonium americium curium\n berkelium californium einsteinium fermium\n mendelevium nobelium lawrencium rutherfordium\n dubnium seaborgium bohrium hassium\n meitnerium darmstadtium roentgenium copernicium\n nihonium flerovium moscovium livermorium\n tennessine oganesson\n]]\n-- the task requires the \"final list\" as single-space-between string version\n-- (a more idiomatic overall approach would be to directly split into a table)\nfinallist = longliteral:gsub(\"%s+\",\" \")\n\nelements = {}\n-- longliteral could be used here DIRECTLY instead of using finallist:\nfor name in finallist:gmatch(\"%w+\") do elements[#elements+1]=name end\nprint(\"revised date: \" .. revised)\nprint(\"# elements : \" .. #elements)\nprint(\"last element: \" .. elements[#elements])\n\n-- then, if still required, produce a single-space-between string version:\n--finallist = table.concat(elements,\" \")"} {"title": "Longest common subsequence", "language": "Lua", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.\n\nA chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].\n\nEvery Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.\n\nAccording to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.\n\n'''Background'''\n\nWhere the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.\n\nThe divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.\n\nA binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "function LCS( a, b ) \n if #a == 0 or #b == 0 then \n return \"\" \n elseif string.sub( a, -1, -1 ) == string.sub( b, -1, -1 ) then\n return LCS( string.sub( a, 1, -2 ), string.sub( b, 1, -2 ) ) .. string.sub( a, -1, -1 ) \n else \n local a_sub = LCS( a, string.sub( b, 1, -2 ) )\n local b_sub = LCS( string.sub( a, 1, -2 ), b )\n \n if #a_sub > #b_sub then\n return a_sub\n else\n return b_sub\n end\n end\nend\n\nprint( LCS( \"thisisatest\", \"testing123testing\" ) )"} {"title": "Longest increasing subsequence", "language": "Lua", "task": "Calculate and show here a longest increasing subsequence of the list:\n:\\{3, 2, 6, 4, 5, 1\\}\nAnd of the list:\n:\\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\\}\n\nNote that a list may have more than one subsequence that is of the maximum length.\n\n\n\n;Ref:\n# Dynamic Programming #1: Longest Increasing Subsequence on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "function buildLIS(seq)\n local piles = { { {table.remove(seq, 1), nil} } }\n while #seq>0 do\n local x=table.remove(seq, 1)\n for j=1,#piles do\n if piles[j][#piles[j]][1]>x then\n table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])})\n break\n elseif j==#piles then\n table.insert(piles, {{x, #piles[j]}})\n end\n end\n end\n local t={}\n table.insert(t, piles[#piles][1][1])\n local p=piles[#piles][1][2]\n for i=#piles-1,1,-1 do\n table.insert(t, piles[i][p][1])\n p=piles[i][p][2]\n end\n table.sort(t)\n print(unpack(t))\nend\n\nbuildLIS({3,2,6,4,5,1})\nbuildLIS({0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15})\n"} {"title": "MAC vendor lookup", "language": "Lua", "task": "Every connected device around the world comes with a unique Media Access Control address, or a MAC address. \n\nA common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.\n\n\n;Task:\nInterface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.\n\nA MAC address that does not return a valid result should return the String \"N/A\". An error related to the network connectivity or the API should return a null result.\n\nMany implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.\n\n'''{\"errors\":{\"detail\":\"Too Many Requests\",\"message\":\"Please slow down your requests or upgrade your plan at https://macvendors.com\"}}'''\n\n", "solution": "-- Requires LuaSocket extension by Lua\n-- Created by James A. Donnell Jr.\n-- www.JamesDonnell.com\n\nlocal baseURL = \"http://api.macvendors.com/\"\n\nlocal function lookup(macAddress)\n\thttp = require \"socket.http\"\n\tresult, statuscode, content = http.request(baseURL .. macAddress)\n\treturn result\nend\n\nlocal macAddress = \"FC-A1-3E-2A-1C-33\"\nprint(lookup(macAddress))"} {"title": "Mad Libs", "language": "Lua", "task": "{{wikipedia}}\n\n\nMad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. \n\n\n;Task;\nWrite a program to create a Mad Libs like story. \n\nThe program should read an arbitrary multiline story from input.\n\nThe story will be terminated with a blank line. \n\nThen, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.\n\nStop when there are none left and print the final story.\n\n\nThe input should be an arbitrary story in the form:\n\n went for a walk in the park. \nfound a . decided to take it home.\n\nGiven this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).\n\n\n\n", "solution": "print(\"Enter a multi-line story (finish with blank line):\")\ndict, story, line = {}, \"\", io.read()\nwhile #line>0 do story=story..line..\"\\n\" line=io.read() end\nstory = story:gsub(\"(%<.-%>)\", function(what)\n if dict[what] then return dict[what] end\n io.write(\"Please enter a \" .. what .. \": \")\n dict[what] = io.read()\n return dict[what]\n end)\nprint(\"\\n\"..story)"} {"title": "Magic 8-ball", "language": "Lua", "task": "Create Magic 8-Ball. \n\n\nSee details at: Magic 8-Ball.\n\n\n\n", "solution": "math.randomseed(os.time())\nanswers = {\n \"It is certain.\", \"It is decidedly so.\", \"Without a doubt.\", \"Yes, definitely.\", \"You may rely on it.\",\n \"As I see it, yes.\", \"Most likely.\", \"Outlook good.\", \"Signs point to yes.\", \"Yes.\",\n \"Reply hazy, try again.\", \"Ask again later.\", \"Better not tell you now.\", \"Cannot predict now.\", \"Concentrate and ask again.\",\n \"Don't bet on it.\", \"My reply is no.\", \"My sources say no.\", \"Outlook not so good.\", \"Very doubtful.\"\n}\nwhile true do\n io.write(\"Q: \")\n question = io.read()\n print(\"A: \"..answers[math.random(#answers)])\nend"} {"title": "Magic squares of doubly even order", "language": "Lua", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). \n\nThis means that the subsquares also have an even size, which plays a role in the construction.\n\n \n{| class=\"wikitable\" style=\"float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%\"\n|-\n|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''\n|-\n|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''\n|-\n|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''\n|-\n|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''\n|-\n|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''\n|-\n|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''\n|-\n|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''\n|-\n|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''\n|}\n\n;Task\nCreate a magic square of '''8 x 8'''.\n\n\n;Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n\n\n;See also:\n* Doubly Even Magic Squares (1728.org)\n\n", "solution": "For all three kinds of Magic Squares(Odd, singly and doubly even)
\nSee [[Magic_squares/Lua]].\n\n"} {"title": "Magic squares of odd order", "language": "Lua", "task": "A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| class=\"wikitable\" style=\"float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "For all three kinds of Magic Squares(Odd, singly and doubly even)
\nSee [[Magic_squares/Lua]].\n\n"} {"title": "Magic squares of singly even order", "language": "Lua", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.\n\n;Task\nCreate a magic square of 6 x 6.\n\n\n; Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of doubly even order]]\n\n; See also\n* Singly Even Magic Squares (1728.org)\n\n", "solution": "For all three kinds of Magic Squares(Odd, singly and doubly even)
\nSee [[Magic_squares/Lua]].\n\n"} {"title": "Map range", "language": "Lua", "task": "Given two ranges: \n:::* [a_1,a_2] and \n:::* [b_1,b_2]; \n:::* then a value s in range [a_1,a_2]\n:::* is linearly mapped to a value t in range [b_1,b_2]\n where: \n\n\n:::* t = b_1 + {(s - a_1)(b_2 - b_1) \\over (a_2 - a_1)}\n\n\n;Task:\nWrite a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. \n\nUse this function to map values from the range [0, 10] to the range [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "function map_range( a1, a2, b1, b2, s )\n return b1 + (s-a1)*(b2-b1)/(a2-a1)\nend\n\nfor i = 0, 10 do\n print( string.format( \"f(%d) = %f\", i, map_range( 0, 10, -1, 0, i ) ) )\nend"} {"title": "Maximum triangle path sum", "language": "Lua", "task": "Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "local triangleSmall = {\n { 55 },\n { 94, 48 },\n { 95, 30, 96 },\n { 77, 71, 26, 67 },\n}\n\nlocal triangleLarge = {\n { 55 },\n { 94, 48 },\n { 95, 30, 96 },\n { 77, 71, 26, 67 },\n { 97, 13, 76, 38, 45 },\n { 7, 36, 79, 16, 37, 68 },\n { 48, 7, 9, 18, 70, 26, 6 },\n { 18, 72, 79, 46, 59, 79, 29, 90 },\n { 20, 76, 87, 11, 32, 7, 7, 49, 18 },\n { 27, 83, 58, 35, 71, 11, 25, 57, 29, 85 },\n { 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55 },\n { 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23 },\n { 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42 },\n { 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72 },\n { 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36 },\n { 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52 },\n { 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15 },\n { 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 },\n};\n\nfunction solve(triangle)\n\n -- Get total number of rows in triangle.\n local nRows = table.getn(triangle)\n\n -- Start at 2nd-to-last row and work up to the top.\n for row = nRows-1, 1, -1 do\n\n -- For each value in row, add the max of the 2 children beneath it.\n for i = 1, row do\n local child1 = triangle[row+1][i]\n local child2 = triangle[row+1][i+1]\n triangle[row][i] = triangle[row][i] + math.max(child1, child2)\n end\n\n end\n\n -- The top of the triangle now holds the answer.\n return triangle[1][1];\n\nend\n\nprint(solve(triangleSmall))\nprint(solve(triangleLarge))\n"} {"title": "McNuggets problem", "language": "Lua", "task": "From Wikipedia:\n The McNuggets version of the coin problem was introduced by Henri Picciotto,\n who included it in his algebra textbook co-authored with Anita Wah. Picciotto\n thought of the application in the 1980s while dining with his son at\n McDonald's, working the problem out on a napkin. A McNugget number is\n the total number of McDonald's Chicken McNuggets in any number of boxes.\n In the United Kingdom, the original boxes (prior to the introduction of\n the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.\n\n;Task:\nCalculate (from 0 up to a limit of 100) the largest non-McNuggets\nnumber (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''\nwhere ''x'', ''y'' and ''z'' are natural numbers).\n\n", "solution": "function range(A,B)\n return function()\n return coroutine.wrap(function()\n for i = A, B do coroutine.yield(i) end\n end)\n end\nend\n\nfunction filter(stream, f)\n return function()\n return coroutine.wrap(function()\n for i in stream() do\n if f(i) then coroutine.yield(i) end\n end\n end)\n end\nend\n\nfunction triple(s1, s2, s3)\n return function()\n return coroutine.wrap(function()\n for x in s1() do\n for y in s2() do\n for z in s3() do\n coroutine.yield{x,y,z}\n end\n end\n end\n end)\n end\nend\n\nfunction apply(f, stream)\n return function()\n return coroutine.wrap(function()\n for T in stream() do\n coroutine.yield(f(table.unpack(T)))\n end\n end)\n end\nend\n\nfunction exclude(s1, s2)\n local exlusions = {} for x in s1() do exlusions[x] = true end\n return function()\n return coroutine.wrap(function()\n for x in s2() do\n if not exlusions[x] then\n coroutine.yield(x)\n end\n end\n end)\n end\nend\n\nfunction maximum(stream)\n local M = math.mininteger\n for x in stream() do\n M = math.max(M, x)\n end\n return M\nend\n\nlocal N = 100\nlocal A, B, C = 6, 9, 20\n\nlocal Xs = filter(range(0, N), function(x) return x % A == 0 end)\nlocal Ys = filter(range(0, N), function(x) return x % B == 0 end)\nlocal Zs = filter(range(0, N), function(x) return x % C == 0 end)\nlocal sum = filter(apply(function(x, y, z) return x + y + z end, triple(Xs, Ys, Zs)), function(x) return x <= N end)\n\nprint(maximum(exclude(sum, range(1, N))))\n"} {"title": "Middle three digits", "language": "Lua", "task": "Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "function middle_three(n)\n\tif n < 0 then\n\t\tn = -n\n\tend\n\t\t\n\tn = tostring(n)\n\tif #n % 2 == 0 then\n\t\treturn \"Error: the number of digits is even.\"\n\telseif #n < 3 then\n\t\treturn \"Error: the number has less than 3 digits.\"\n\tend\n\n\tlocal l = math.floor(#n/2)\n\treturn n:sub(l, l+2)\nend\n\n-- test\ndo\n\tlocal t = {123, 12345, 1234567, 987654321,\n\t10001, -10001, -123, -100, 100, -12345, 1,\n\t2, -1, -10, 2002, -2002, 0}\n\n\tfor _,n in pairs(t) do\n\t\tprint(n, middle_three(n))\t\n\tend\nend"} {"title": "Mind boggling card trick", "language": "Lua", "task": "Matt Parker of the \"Stand Up Maths channel\" has a YouTube video of a card trick that creates a semblance of order from chaos.\n\nThe task is to simulate the trick in a way that mimics the steps shown in the video.\n\n; 1. Cards.\n# Create a common deck of cards of 52 cards (which are half red, half black).\n# Give the pack a good shuffle.\n; 2. Deal from the shuffled deck, you'll be creating three piles.\n# Assemble the cards face down.\n## Turn up the ''top card'' and hold it in your hand. \n### if the card is black, then add the ''next'' card (unseen) to the \"black\" pile. \n### If the card is red, then add the ''next'' card (unseen) to the \"red\" pile.\n## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness).\n# Repeat the above for the rest of the shuffled deck.\n; 3. Choose a random number (call it '''X''') that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose '''X''' cards from the \"red\" pile (unseen), let's call this the \"red\" bunch. \n# Randomly choose '''X''' cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \"red\" bunch into the \"black\" pile.\n# Put the \"black\" bunch into the \"red\" pile.\n# (The above two steps complete the swap of '''X''' cards of the \"red\" and \"black\" piles. (Without knowing what those cards are --- they could be red or black, nobody knows).\n; 4. Order from randomness?\n# Verify (or not) the mathematician's assertion that: \n '''The number of black cards in the \"black\" pile equals the number of red cards in the \"red\" pile.''' \n\n\n(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)\n\nShow output on this page.\n\n", "solution": "-- support:\nfunction T(t) return setmetatable(t, {__index=table}) end\ntable.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end\ntable.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end\ntable.filter = function(t,f) local s=T{} for i=1,#t do if f(t[i]) then s[#s+1]=t[i] end end return s end\ntable.clone = function(t) local s=T{} for k,v in ipairs(t) do s[k]=v end return s end\ntable.head = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end\ntable.tail = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[#t-n+i] end return s end\ntable.append = function(t,v) local s=t:clone() for i=1,#v do s[#s+1]=v[i] end return s end\ntable.shuffle = function(t) for i=#t,2,-1 do local j=math.random(i) t[i],t[j]=t[j],t[i] end return t end -- inplace!\n\n-- task:\nfunction cardtrick()\n -- 1.\n local deck = T{}:range(52):map(function(v) return v%2==0 and \"B\" or \"R\" end):shuffle()\n print(\"1. DECK : \" .. deck:concat())\n -- 2. (which guarantees the outcome)\n local bpile, rpile, discs = T{}, T{}, T{}\n local xpile = {B=bpile, R=rpile}\n while #deck>0 do\n local card, next = deck:remove(), deck:remove()\n xpile[card]:insert(next)\n discs:insert(card)\n end\n print(\"2. BLACK PILE: \" .. bpile:concat())\n print(\"2. RED PILE : \" .. rpile:concat())\n print(\"2. DISCARDS : \" .. discs:concat())\n -- 3. (which cannot change the outcome)\n local x = math.random(0, math.min(#bpile, #rpile))\n local btake, rtake = T{}, T{}\n for i = 1, x do\n btake:insert((bpile:remove(math.random(#bpile))))\n rtake:insert((rpile:remove(math.random(#rpile))))\n end\n print(\"3. SWAPPING X: \" .. x)\n print(\"3. BLACK SWAP: keep:\" .. bpile:concat() .. \" take:\" .. btake:concat())\n print(\"3. RED SWAP : keep:\" .. rpile:concat() .. \" take:\" .. rtake:concat())\n bpile, rpile = bpile:append(rtake), rpile:append(btake)\n print(\"3. BLACK PILE: \" .. bpile:concat())\n print(\"3. RED PILE : \" .. rpile:concat())\n -- 4. (\"proving\" that which was guaranteed earlier)\n local binb, rinr = bpile:filter(function(v) return v==\"B\" end), rpile:filter(function(v) return v==\"R\" end)\n print(\"4. BLACK PILE: contains \" .. #binb .. \" B's\")\n print(\"4. RED PILE : contains \" .. #rinr .. \" R's\")\n print(#binb==#rinr and \"VERIFIED\" or \"NOT VERIFIED\")\n print()\nend\n\n-- demo:\nmath.randomseed(os.time())\nfor i = 1,3 do cardtrick() end"} {"title": "Minimum positive multiple in base 10 using only 0 and 1", "language": "Lua", "task": "Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.\n\nThis is simple to do, but can be challenging to do efficiently.\n\nTo avoid repeating long, unwieldy phrases, the operation \"minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1\" will hereafter be referred to as \"'''B10'''\".\n\n;Task:\n\nWrite a routine to find the B10 of a given integer. \n\nE.G. \n \n '''n''' '''B10''' '''n''' x '''multiplier'''\n 1 1 ( 1 x 1 )\n 2 10 ( 2 x 5 )\n 7 1001 ( 7 x 143 )\n 9 111111111 ( 9 x 12345679 )\n 10 10 ( 10 x 1 )\n\nand so on.\n\nUse the routine to find and display here, on this page, the '''B10''' value for: \n\n 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999\n\nOptionally find '''B10''' for:\n\n 1998, 2079, 2251, 2277\n\nStretch goal; find '''B10''' for:\n\n 2439, 2997, 4878\n\nThere are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.\n\n\n;See also:\n\n:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.\n:* How to find Minimum Positive Multiple in base 10 using only 0 and 1\n\n", "solution": "Without a bignum library, some values do not display or calculate properly\n"} {"title": "Minimum positive multiple in base 10 using only 0 and 1", "language": "Lua from Ruby", "task": "Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.\n\nThis is simple to do, but can be challenging to do efficiently.\n\nTo avoid repeating long, unwieldy phrases, the operation \"minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1\" will hereafter be referred to as \"'''B10'''\".\n\n;Task:\n\nWrite a routine to find the B10 of a given integer. \n\nE.G. \n \n '''n''' '''B10''' '''n''' x '''multiplier'''\n 1 1 ( 1 x 1 )\n 2 10 ( 2 x 5 )\n 7 1001 ( 7 x 143 )\n 9 111111111 ( 9 x 12345679 )\n 10 10 ( 10 x 1 )\n\nand so on.\n\nUse the routine to find and display here, on this page, the '''B10''' value for: \n\n 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999\n\nOptionally find '''B10''' for:\n\n 1998, 2079, 2251, 2277\n\nStretch goal; find '''B10''' for:\n\n 2439, 2997, 4878\n\nThere are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.\n\n\n;See also:\n\n:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.\n:* How to find Minimum Positive Multiple in base 10 using only 0 and 1\n\n", "solution": "function array1D(n, v)\n local tbl = {}\n for i=1,n do\n table.insert(tbl, v)\n end\n return tbl\nend\n\nfunction array2D(h, w, v)\n local tbl = {}\n for i=1,h do\n table.insert(tbl, array1D(w, v))\n end\n return tbl\nend\n\nfunction mod(m, n)\n m = math.floor(m)\n local result = m % n\n if result < 0 then\n result = result + n\n end\n return result\nend\n\nfunction getA004290(n)\n if n == 1 then\n return 1\n end\n local arr = array2D(n, n, 0)\n arr[1][1] = 1\n arr[1][2] = 1\n local m = 0\n while true do\n m = m + 1\n if arr[m][mod(-10 ^ m, n) + 1] == 1 then\n break\n end\n arr[m + 1][1] = 1\n for k = 1, n - 1 do\n arr[m + 1][k + 1] = math.max(arr[m][k + 1], arr[m][mod(k - 10 ^ m, n) + 1])\n end\n end\n local r = 10 ^ m\n local k = mod(-r, n)\n for j = m - 1, 1, -1 do\n if arr[j][k + 1] == 0 then\n r = r + 10 ^ j\n k = mod(k - 10 ^ j, n)\n end\n end\n if k == 1 then\n r = r + 1\n end\n return r\nend\n\nfunction test(cases)\n for _,n in ipairs(cases) do\n local result = getA004290(n)\n print(string.format(\"A004290(%d) = %s = %d * %d\", n, math.floor(result), n, math.floor(result / n)))\n end\nend\n\ntest({1, 2, 3, 4, 5, 6, 7, 8, 9})\ntest({95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105})\ntest({297, 576, 594, 891, 909, 999})\n--test({1998, 2079, 2251, 2277})\n--test({2439, 2997, 4878})"} {"title": "Modular arithmetic", "language": "Lua", "task": "equivalence relation called ''congruence''. \n\nFor any positive integer p called the ''congruence modulus'', \ntwo numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:\n:a = b + k\\,p\n\nThe corresponding set of multiplicative inverse for this task.\n\nAddition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.\n\nThe purpose of this task is to show, if your programming language allows it, \nhow to redefine operators so that they can be used transparently on modular integers. \nYou can do it either by using a dedicated library, or by implementing your own class.\n\nYou will use the following function for demonstration:\n:f(x) = x^{100} + x + 1\nYou will use 13 as the congruence modulus and you will compute f(10).\n\nIt is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. \nIn other words, the function is an algebraic expression that could be used with any ring, not just integers.\n\n", "solution": "function make(value, modulo)\n local v = value % modulo\n local tbl = {value=v, modulo=modulo}\n\n local mt = {\n __add = function(lhs, rhs)\n if type(lhs) == \"table\" then\n if type(rhs) == \"table\" then\n if lhs.modulo ~= rhs.modulo then\n error(\"Cannot add rings with different modulus\")\n end\n return make(lhs.value + rhs.value, lhs.modulo)\n else\n return make(lhs.value + rhs, lhs.modulo)\n end\n else\n error(\"lhs is not a table in +\")\n end\n end,\n __mul = function(lhs, rhs)\n if lhs.modulo ~= rhs.modulo then\n error(\"Cannot multiply rings with different modulus\")\n end\n return make(lhs.value * rhs.value, lhs.modulo)\n end,\n __pow = function(b,p)\n if p<0 then\n error(\"p must be zero or greater\")\n end\n\n local pp = p\n local pwr = make(1, b.modulo)\n while pp > 0 do\n pp = pp - 1\n pwr = pwr * b\n end\n return pwr\n end,\n __concat = function(lhs, rhs)\n if type(lhs) == \"table\" and type(rhs) == \"string\" then\n return \"ModInt(\"..lhs.value..\", \"..lhs.modulo..\")\"..rhs\n elseif type(lhs) == \"string\" and type(rhs) == \"table\" then\n return lhs..\"ModInt(\"..rhs.value..\", \"..rhs.modulo..\")\"\n else\n return \"todo\"\n end\n end\n }\n\n setmetatable(tbl, mt)\n return tbl\nend\n\nfunction func(x)\n return x ^ 100 + x + 1\nend\n\n-- main\nlocal x = make(10, 13)\nlocal y = func(x)\nprint(\"x ^ 100 + x + 1 for \"..x..\" is \"..y)"} {"title": "Monads/Maybe monad", "language": "lua 5.3", "task": "Demonstrate in your programming language the following:\n\n#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String\n#Compose the two functions with bind\n\n\nA Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.\n\nA Maybe Monad is a monad which specifically encapsulates the type of an undefined value.\n\n", "solution": "-- None is represented by an empty table. Some is represented by any\n-- array with one element. You SHOULD NOT compare maybe values with the\n-- Lua operator == because it will give incorrect results. Use the\n-- functions isMaybe(), isNone(), and isSome().\n\n-- define once for efficiency, to avoid many different empty tables\nlocal NONE = {}\n\nlocal function unit(x) return { x } end\nlocal Some = unit\nlocal function isNone(mb) return #mb == 0 end\nlocal function isSome(mb) return #mb == 1 end\nlocal function isMaybe(mb) return isNone(mb) or isSome(mb) end\n\n-- inverse of Some(), extract the value from the maybe; get(Some(x)) === x\nlocal function get(mb) return mb[1] end\n\nfunction maybeToStr(mb)\n\treturn isNone(mb) and \"None\" or (\"Some \" .. tostring(get(mb)))\nend\n\nlocal function bind(mb, ...) -- monadic bind for multiple functions\n\tlocal acc = mb\n\tfor _, fun in ipairs({...}) do -- fun should be a monadic function\n\t\tassert(type(fun) == \"function\")\n\t\tif isNone(acc) then return NONE\n\t\telse acc = fun(get(acc)) end\n\tend\n\treturn acc\nend\n\nlocal function fmap(mb, ...) -- monadic fmap for multiple functions\n\tlocal acc = mb\n\tfor _, fun in ipairs({...}) do -- fun should be a regular function\n\t\tassert(type(fun) == \"function\")\n\t\tif isNone(acc) then return NONE\n\t\telse acc = Some(fun(get(acc))) end\n\tend\n\treturn acc\nend\n-- ^^^ End of generic maybe monad functionality ^^^\n\n--- vvv Start of example code vvv\n\nlocal function time2(x) return x * 2 end\nlocal function plus1(x) return x + 1 end\n\nlocal answer\nanswer = fmap(Some(3), time2, plus1, time2)\nassert(get(answer)==14)\n\nanswer = fmap(NONE, time2, plus1, time2)\nassert(isNone(answer))\n\nlocal function safeReciprocal(x)\n\tif x ~= 0 then return Some(1/x) else return NONE end\nend\nlocal function safeRoot(x)\n\tif x >= 0 then return Some(math.sqrt(x)) else return NONE end\nend\nlocal function safeLog(x)\n\tif x > 0 then return Some(math.log(x)) else return NONE end\nend\nlocal function safeComputation(x)\n\treturn bind(safeReciprocal(x), safeRoot, safeLog)\nend\n\nlocal function map(func, table)\n\tlocal result = {}\n\tfor key, val in pairs(table) do\n\t\tresult[key] = func(val)\n\tend\n\treturn result\nend\n\nlocal inList = {-2, -1, -0.5, 0, math.exp (-1), 1, 2, math.exp (1), 3, 4, 5}\nprint(\"input:\", table.concat(map(tostring, inList), \", \"), \"\\n\")\n\nlocal outList = map(safeComputation, inList)\nprint(\"output:\", table.concat(map(maybeToStr, outList), \", \"), \"\\n\")\n"} {"title": "Move-to-front algorithm", "language": "Lua", "task": "Given a symbol table of a ''zero-indexed'' array of all possible input symbols\nthis algorithm reversibly transforms a sequence\nof input symbols into an array of output numbers (indices).\n\nThe transform in many cases acts to give frequently repeated input symbols\nlower indices which is useful in some compression algorithms.\n\n\n;Encoding algorithm:\n\n for each symbol of the input sequence:\n output the index of the symbol in the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Decoding algorithm:\n\n # Using the same starting symbol table\n for each index of the input sequence:\n output the symbol at that index of the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Example:\nEncoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''\n\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''b'''roood\n| 1\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| b'''r'''oood\n| 1 17\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| br'''o'''ood\n| 1 17 15\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| bro'''o'''od\n| 1 17 15 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| broo'''o'''d\n| 1 17 15 0 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| brooo'''d'''\n| 1 17 15 0 0 5\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\nDecoding the indices back to the original symbol order:\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''1''' 17 15 0 0 5\n| b\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| 1 '''17''' 15 0 0 5\n| br\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| 1 17 '''15''' 0 0 5\n| bro\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| 1 17 15 '''0''' 0 5\n| broo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 '''0''' 5\n| brooo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 0 '''5''' \n| broood\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\n;Task:\n:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. \n:* Show the strings and their encoding here.\n:* Add a check to ensure that the decoded string is the same as the original.\n\n\nThe strings are: \n\n broood \n bananaaa \n hiphophiphop \n(Note the misspellings in the above strings.)\n\n", "solution": "-- Return table of the alphabet in lower case\nfunction getAlphabet ()\n local letters = {}\n for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end\n return letters\nend\n\n-- Move the table value at ind to the front of tab\nfunction moveToFront (tab, ind)\n local toMove = tab[ind]\n for i = ind - 1, 1, -1 do tab[i + 1] = tab[i] end\n tab[1] = toMove\nend\n\n-- Perform move-to-front encoding on input\nfunction encode (input)\n local symbolTable, output, index = getAlphabet(), {}\n for pos = 1, #input do\n for k, v in pairs(symbolTable) do\n if v == input:sub(pos, pos) then index = k end\n end\n moveToFront(symbolTable, index)\n table.insert(output, index - 1)\n end\n return table.concat(output, \" \")\nend\n\n-- Perform move-to-front decoding on input\nfunction decode (input)\n local symbolTable, output = getAlphabet(), \"\"\n for num in input:gmatch(\"%d+\") do\n output = output .. symbolTable[num + 1]\n moveToFront(symbolTable, num + 1)\n end\n return output\nend\n\n-- Main procedure\nlocal testCases, output = {\"broood\", \"bananaaa\", \"hiphophiphop\"}\nfor _, case in pairs(testCases) do\n output = encode(case)\n print(\"Original string: \" .. case)\n print(\"Encoded: \" .. output)\n print(\"Decoded: \" .. decode(output))\n print()\nend"} {"title": "Multi-dimensional array", "language": "Lua", "task": "For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. \n\nIt is enough to:\n# State the number and extent of each index to the array.\n# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.\n# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.\n\n\n;Task:\n* State if the language supports multi-dimensional arrays in its syntax and usual implementation.\n* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.\n* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.\n:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).\n* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.\n* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.\n\n\nShow all output here, (but you may judiciously use ellipses to shorten repetitive output text).\n\n", "solution": "-- Variadic, first argument is the value with which to populate the array. \nfunction multiArray (initVal, ...)\n local function copy (t)\n local new = {}\n for k, v in pairs(t) do\n if type(v) == \"table\" then\n new[k] = copy(v)\n else\n new[k] = v\n end\n end\n return new\n end\n local dimensions, arr, newArr = {...}, {}\n for i = 1, dimensions[#dimensions] do table.insert(arr, initVal) end\n for d = #dimensions - 1, 1, -1 do\n newArr = {}\n for i = 1, dimensions[d] do table.insert(newArr, copy(arr)) end\n arr = copy(newArr)\n end\n return arr\nend\n \n-- Function to print out the specific example created here\nfunction show4dArray (a)\n print(\"\\nPrinting 4D array in 2D...\")\n for k, v in ipairs(a) do\n print(k)\n for l, w in ipairs(v) do\n print(\"\\t\" .. l)\n for m, x in ipairs(w) do\n print(\"\\t\", m, unpack(x))\n end\n end\n end\nend\n \n-- Main procedure\nlocal t = multiArray(\"a\", 2, 3, 4, 5)\nshow4dArray(t)\nt[1][1][1][1] = true\nshow4dArray(t)"} {"title": "Multifactorial", "language": "Lua", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\nMultifactorials generalize factorials as follows:\n: n! = n(n-1)(n-2)...(2)(1)\n: n!! = n(n-2)(n-4)...\n: n!! ! = n(n-3)(n-6)...\n: n!! !! = n(n-4)(n-8)...\n: n!! !! ! = n(n-5)(n-10)...\n\nIn all cases, the terms in the products are positive integers.\n\nIf we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: \n# Write a function that given n and the degree, calculates the multifactorial.\n# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.\n\n\n'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.\n\n", "solution": "function multiFact (n, degree)\n local fact = 1\n for i = n, 2, -degree do\n fact = fact * i\n end\n return fact\nend\n\nprint(\"Degree\\t|\\tMultifactorials 1 to 10\")\nprint(string.rep(\"-\", 52))\nfor d = 1, 5 do\n io.write(\" \" .. d, \"\\t| \")\n for n = 1, 10 do\n io.write(multiFact(n, d) .. \" \")\n end\n print()\nend"} {"title": "Multiple distinct objects", "language": "Lua", "task": "Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.\n\nBy ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.\n\nBy ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to \"zero\" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of \"zero\" for that type.\n\nThis task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.\n\nThis task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).\n\nSee also: [[Closures/Value capture]]\n\n", "solution": "-- This concept is relevant to tables in Lua\nlocal table1 = {1,2,3}\n\n-- The following will create a table of references to table1\nlocal refTab = {}\nfor i = 1, 10 do refTab[i] = table1 end\n\n-- Instead, tables should be copied using a function like this\t\nfunction copy (t)\n local new = {}\n for k, v in pairs(t) do new[k] = v end\n return new\nend\n\n-- Now we can create a table of independent copies of table1\nlocal copyTab = {}\nfor i = 1, 10 do copyTab[i] = copy(table1) end"} {"title": "Multisplit", "language": "Lua", "task": "It is often necessary to split a string into pieces \nbased on several different (potentially multi-character) separator strings, \nwhile still retaining the information about which separators were present in the input. \n\nThis is particularly useful when doing small parsing tasks. \nThe task is to write code to demonstrate this.\n\nThe function (or procedure or method, as appropriate) should \ntake an input string and an ordered collection of separators. \n\nThe order of the separators is significant: \nThe delimiter order represents priority in matching, with the first defined delimiter having the highest priority. \nIn cases where there would be an ambiguity as to \nwhich separator to use at a particular point \n(e.g., because one separator is a prefix of another) \nthe separator with the highest priority should be used. \nDelimiters can be reused and the output from the function should be an ordered sequence of substrings.\n\nTest your code using the input string \"a!===b=!=c\" and the separators \"==\", \"!=\" and \"=\".\n\nFor these inputs the string should be parsed as \"a\" (!=) \"\" (==) \"b\" (=) \"\" (!=) \"c\", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is \"a\", empty string, \"b\", empty string, \"c\". \nNote that the quotation marks are shown for clarity and do not form part of the output.\n\n'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.\n\n", "solution": "--[[\nReturns a table of substrings by splitting the given string on \noccurrences of the given character delimiters, which may be specified \nas a single- or multi-character string or a table of such strings.\nIf chars is omitted, it defaults to the set of all space characters, \nand keep is taken to be false. The limit and keep arguments are \noptional: they are a maximum size for the result and a flag \ndetermining whether empty fields should be kept in the result.\n]]\nfunction split (str, chars, limit, keep)\n local limit, splitTable, entry, pos, match = limit or 0, {}, \"\", 1\n if keep == nil then keep = true end\n if not chars then\n for e in string.gmatch(str, \"%S+\") do\n table.insert(splitTable, e)\n end\n return splitTable\n end\n while pos <= str:len() do\n match = nil\n if type(chars) == \"table\" then\n for _, delim in pairs(chars) do\n if str:sub(pos, pos + delim:len() - 1) == delim then\n match = string.len(delim) - 1\n break\n end\n end\n elseif str:sub(pos, pos + chars:len() - 1) == chars then\n match = string.len(chars) - 1\n end\n if match then\n if not (keep == false and entry == \"\") then\n table.insert(splitTable, entry)\n if #splitTable == limit then return splitTable end\n entry = \"\"\n end\n else\n entry = entry .. str:sub(pos, pos)\n end\n pos = pos + 1 + (match or 0)\n end\n if entry ~= \"\" then table.insert(splitTable, entry) end\n return splitTable\nend\n\nlocal multisplit = split(\"a!===b=!=c\", {\"==\", \"!=\", \"=\"})\n\n-- Returned result is a table (key/value pairs) - display all entries\nprint(\"Key\\tValue\")\nprint(\"---\\t-----\")\nfor k, v in pairs(multisplit) do\n print(k, v)\nend"} {"title": "Munchausen numbers", "language": "Lua", "task": "A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.\n\n('''Munchausen''' is also spelled: '''Munchhausen'''.) \n\nFor instance: 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between '''1''' and '''5000'''.\n\n\n;Also see:\n:* The OEIS entry: A046253\n:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''\n\n", "solution": "function isMunchausen (n)\n local sum, nStr, digit = 0, tostring(n)\n for pos = 1, #nStr do\n digit = tonumber(nStr:sub(pos, pos))\n sum = sum + digit ^ digit\n end\n return sum == n\nend\n\n-- alternative, faster version based on the C version, \n-- avoiding string manipulation, for Lua 5.3 or higher\nlocal function isMunchausen (n)\n local sum, digit, acc = 0, 0, n\n while acc > 0 do\n digit = acc % 10.0\n sum = sum + digit ^ digit\n acc = acc // 10 -- integer div\n end\n return sum == n\nend\n\nfor i = 1, 5000 do\n if isMunchausen(i) then print(i) end\nend"} {"title": "Musical scale", "language": "Lua", "task": "Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.\n\nThese are the notes \"C, D, E, F, G, A, B, C(1 octave higher)\", or \"Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)\" on Fixed do Solfege.\n\nFor the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.\n\nFor languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.\n\n", "solution": "c = string.char\nmidi = \"MThd\" .. c(0,0,0,6,0,0,0,1,0,96) -- header\nmidi = midi .. \"MTrk\" .. c(0,0,0,8*8+4) -- track\nfor _,note in ipairs{60,62,64,65,67,69,71,72} do\n midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0) -- notes\nend\nmidi = midi .. c(0, 0xFF, 0x2F, 0) -- end\n\nfile = io.open(\"scale.mid\", \"wb\")\nfile:write(midi)\nfile:close()\n\n-- (optional: hex dump to screen)\nmidi:gsub(\".\", function(c) io.write(string.format(\"%02X \", string.byte(c))) end)"} {"title": "N-queens problem", "language": "Lua", "task": "right\n\nSolve the eight queens puzzle. \n\n\nYou can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.\n \nFor the number of solutions for small values of '''N''', see OEIS: A000170.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[Peaceful chess queen armies]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "N = 8\n\n-- We'll use nil to indicate no queen is present.\ngrid = {}\nfor i = 0, N do\n grid[i] = {}\nend\n\nfunction can_find_solution(x0, y0)\n local x0, y0 = x0 or 0, y0 or 1 -- Set default vals (0, 1).\n for x = 1, x0 - 1 do\n if grid[x][y0] or grid[x][y0 - x0 + x] or grid[x][y0 + x0 - x] then\n return false\n end\n end\n grid[x0][y0] = true\n if x0 == N then return true end\n for y0 = 1, N do\n if can_find_solution(x0 + 1, y0) then return true end\n end\n grid[x0][y0] = nil\n return false\nend\n\nif can_find_solution() then\n for y = 1, N do\n for x = 1, N do\n -- Print \"|Q\" if grid[x][y] is true; \"|_\" otherwise.\n io.write(grid[x][y] and \"|Q\" or \"|_\")\n end\n print(\"|\")\n end\nelse\n print(string.format(\"No solution for %d queens.\\n\", N))\nend"} {"title": "Narcissistic decimal number", "language": "Lua", "task": "A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "function isNarc (n)\n local m, sum, digit = string.len(n), 0\n for pos = 1, m do\n digit = tonumber(string.sub(n, pos, pos))\n sum = sum + digit^m\n end\n return sum == n\nend\n\nlocal n, count = 0, 0\nrepeat\n if isNarc(n) then\n io.write(n .. \" \")\n count = count + 1\n end\n n = n + 1\nuntil count == 25"} {"title": "Nested function", "language": "Lua", "task": "In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.\n\n\n;Task: \nWrite a program consisting of two nested functions that prints the following text.\n\n 1. first\n 2. second\n 3. third\n\nThe outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator \". \" as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.\n\nThe inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.\n\n\n;References:\n:* Nested function\n\n", "solution": "function makeList (separator)\n local counter = 0\n local function makeItem(item)\n counter = counter + 1\n return counter .. separator .. item .. \"\\n\"\n end\n return makeItem(\"first\") .. makeItem(\"second\") .. makeItem(\"third\")\nend\n \nprint(makeList(\". \"))"} {"title": "Next highest int from digits", "language": "Lua", "task": "Given a zero or positive integer, the task is to generate the next largest\ninteger using only the given digits*1.\n\n* Numbers will not be padded to the left with zeroes.\n* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).\n* If there is no next highest integer return zero.\n\n\n:*1 Alternatively phrased as: \"Find the smallest integer larger than the (positive or zero) integer '''N''' \n:: which can be obtained by reordering the (base ten) digits of '''N'''\".\n\n\n;Algorithm 1:\n# Generate all the permutations of the digits and sort into numeric order.\n# Find the number in the list.\n# Return the next highest number from the list.\n\n\nThe above could prove slow and memory hungry for numbers with large numbers of\ndigits, but should be easy to reason about its correctness.\n\n\n;Algorithm 2:\n# Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.\n# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)\n\n\n'''E.g.:'''\n\n n = 12453\n\n 12_4_53\n\n 12_5_43\n\n 12_5_34\n\n return: 12534\n\n\nThis second algorithm is faster and more memory efficient, but implementations\nmay be harder to test. \n\nOne method of testing, (as used in developing the task), is to compare results from both\nalgorithms for random numbers generated from a range that the first algorithm can handle.\n\n\n;Task requirements:\nCalculate the next highest int from the digits of the following numbers:\n:* 0\n:* 9\n:* 12\n:* 21\n:* 12453\n:* 738440\n:* 45072010\n:* 95322020\n\n\n;Optional stretch goal:\n:* 9589776899767587796600\n\n", "solution": "unpack = unpack or table.unpack -- <=5.2 vs >=5.3 polyfill\n \nfunction nexthighestint(n)\n local digits, index = {}, {[0]={},{},{},{},{},{},{},{},{},{}}\n for d in tostring(n):gmatch(\"%d\") do digits[#digits+1]=tonumber(d) end\n for i,d in ipairs(digits) do index[d][#index[d]+1]=i end\n local function findswap(i,d)\n for D=d+1,9 do\n for I=1,#index[D] do\n if index[D][I] > i then return index[D][I] end\n end\n end\n end\n for i = #digits-1,1,-1 do\n local j = findswap(i,digits[i])\n if j then\n digits[i],digits[j] = digits[j],digits[i]\n local sorted = {unpack(digits,i+1)}\n table.sort(sorted)\n for k=1,#sorted do digits[i+k]=sorted[k] end\n return table.concat(digits)\n end\n end\nend\n\ntests = { 0, 9, 12, 21, 12453, 738440, 45072010, 95322020, -- task\n \"9589776899767587796600\", -- stretch\n \"123456789098765432109876543210\", -- stretchier\n \"1234567890999888777666555444333222111000\" -- stretchiest\n}\nfor _,n in ipairs(tests) do\n print(n .. \" -> \" .. (nexthighestint(n) or \"(none)\"))\nend"} {"title": "Nim game", "language": "Lua", "task": "Nim is a simple game where the second player-if they know the trick-will always win.\n\n\nThe game has only 3 rules:\n::* start with '''12''' tokens\n::* each player takes '''1, 2, or 3''' tokens in turn\n::* the player who takes the last token wins.\n\n\nTo win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. \n\n;Task:\nDesign a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.\n\n", "solution": "tokens = 12\n\nprint(\"Nim Game\\n\")\nprint(\"Starting with \" .. tokens .. \" tokens.\\n\\n\")\n\nfunction printRemaining()\n\tprint(tokens .. \" tokens remaining.\\n\")\nend\n\nfunction playerTurn(take)\n\ttake = math.floor(take)\n\tif (take < 1 or take > 3) then\n\t\tprint (\"\\nTake must be between 1 and 3.\\n\")\n\t\treturn false\n\tend\n\t\n\ttokens = tokens - take\n\t\n\tprint (\"\\nPlayer takes \" .. take .. \" tokens.\")\n\tprintRemaining()\n\treturn true\nend\n\nfunction computerTurn()\n\ttake = tokens % 4\n\ttokens = tokens - take\n\t\n\tprint(\"Computer takes \" .. take .. \" tokens.\")\n\tprintRemaining()\nend\n\nwhile (tokens > 0) do\n\tio.write(\"How many tokens would you like to take?: \")\n\tif playerTurn(io.read(\"*n\")) then\n\t\tcomputerTurn()\n\tend\nend\n\nprint (\"Computer wins.\")\n"} {"title": "Nonoblock", "language": "Lua", "task": "Nonogram puzzle.\n\n\n;Given:\n* The number of cells in a row.\n* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.\n\n\n;Task: \n* show all possible positions. \n* show the number of positions of the blocks for the following cases within the row. \n* show all output on this page. \n* use a \"neat\" diagram of the block positions.\n\n\n;Enumerate the following configurations:\n# '''5''' cells and '''[2, 1]''' blocks\n# '''5''' cells and '''[]''' blocks (no blocks)\n# '''10''' cells and '''[8]''' blocks\n# '''15''' cells and '''[2, 3, 2, 3]''' blocks\n# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)\n\n\n;Example:\nGiven a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:\n\n |_|_|_|_|_| # 5 cells and [2, 1] blocks\n\nAnd would expand to the following 3 possible rows of block positions:\n\n |A|A|_|B|_|\n |A|A|_|_|B|\n |_|A|A|_|B|\n\n\nNote how the sets of blocks are always separated by a space.\n\nNote also that it is not necessary for each block to have a separate letter. \nOutput approximating\n\nThis:\n |#|#|_|#|_|\n |#|#|_|_|#|\n |_|#|#|_|#|\n\nThis would also work:\n ##.#.\n ##..#\n .##.#\n\n\n;An algorithm:\n* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).\n* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.\n* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.\n\n(This is the algorithm used in the [[Nonoblock#Python]] solution). \n\n\n;Reference:\n* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "local examples = {\n\t{5, {2, 1}},\n\t{5, {}},\n\t{10, {8}},\n\t{15, {2, 3, 2, 3}},\n\t{5, {2, 3}},\n}\n\nfunction deep (blocks, iBlock, freedom, str)\n\tif iBlock == #blocks then -- last\n\t\tfor takenFreedom = 0, freedom do\n\t\t\tprint (str..string.rep(\"0\", takenFreedom) .. string.rep(\"1\", blocks[iBlock]) .. string.rep(\"0\", freedom - takenFreedom))\n\t\t\ttotal = total + 1\n\t\tend\n\telse\n\t\tfor takenFreedom = 0, freedom do\n\t\t\tlocal str2 = str..string.rep(\"0\", takenFreedom) .. string.rep(\"1\", blocks[iBlock]) .. \"0\"\n\t\t\tdeep (blocks, iBlock+1, freedom-takenFreedom, str2)\n\t\tend\n\tend\nend\n\nfunction main (cells, blocks) -- number, list\n\tlocal str = \"\t\"\n\tprint (cells .. ' cells and {' .. table.concat(blocks, ', ') .. '} blocks')\n\tlocal freedom = cells - #blocks + 1 -- freedom\n\tfor iBlock = 1, #blocks do\n\t\tfreedom = freedom - blocks[iBlock]\n\tend\n\tif #blocks == 0 then\n\t\tprint ('no blocks')\n\t\tprint (str..string.rep(\"0\", cells))\n\t\ttotal = 1\n\telseif freedom < 0 then\n\t\tprint ('no solutions')\n\telse\n\t\tprint ('Possibilities:')\n\t\tdeep (blocks, 1, freedom, str)\n\tend\nend\n\nfor i, example in ipairs (examples) do\n\tprint (\"\\n--\")\n\ttotal = 0\n\tmain (example[1], example[2])\n\tprint ('A total of ' .. total .. ' possible configurations.')\nend"} {"title": "Numbers which are the cube roots of the product of their proper divisors", "language": "Lua", "task": "Example\nConsider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title.\n\n;Task\nCompute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.\n\nAlso show the '''500th''' and '''5,000th''' such numbers.\n\n;Stretch\nCompute and show the '''50,000th''' such number.\n\n;Reference\n* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.\n\n;Note\nOEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.\n\n", "solution": "function is_1_or_has_eight_divisors (n)\n if n == 1 then return true end\n local divCount, sqr = 2, math.sqrt(n)\n for d = 2, sqr do\n if n % d == 0 then\n divCount = d == sqr and divCount + 1 or divCount + 2\n end\n if divCount > 8 then return false end\n end\n return divCount == 8\nend\n\n-- First 50\nlocal count, x = 0, 0\nwhile count < 50 do\n x = x + 1\n if is_1_or_has_eight_divisors(x) then\n io.write(x .. \" \")\n count = count + 1\n end\nend\n\n-- 500th, 5,000th and 50,000th\nwhile count < 50000 do\n x = x + 1\n if is_1_or_has_eight_divisors(x) then\n count = count + 1\n if count == 500 then print(\"\\n\\n500th: \" .. x) end\n if count == 5000 then print(\"5,000th: \" .. x) end\n end\nend\nprint(\"50,000th: \" .. x)"} {"title": "Odd word problem", "language": "Lua", "task": "Write a program that solves the odd word problem with the restrictions given below.\n\n\n;Description:\nYou are promised an input stream consisting of English letters and punctuations. \n\nIt is guaranteed that:\n* the words (sequence of consecutive letters) are delimited by one and only one punctuation,\n* the stream will begin with a word,\n* the words will be at least one letter long, and \n* a full stop (a period, [.]) appears after, and only after, the last word.\n\n\n;Example:\nA stream with six words: \n:: what,is,the;meaning,of:life. \n\n\nThe task is to reverse the letters in every other word while leaving punctuations intact, producing:\n:: what,si,the;gninaem,of:efil. \nwhile observing the following restrictions:\n# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;\n# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;\n# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.\n\n\n;Test cases:\nWork on both the \"life\" example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "function reverse()\n local ch = io.read(1)\n if ch:find(\"%w\") then\n local rc = reverse()\n io.write(ch)\n return rc\n end\n return ch\nend\n\nfunction forward()\n ch = io.read(1)\n io.write(ch)\n if ch == \".\" then return false end\n if not ch:find(\"%w\") then\n ch = reverse()\n if ch then io.write(ch) end\n if ch == \".\" then return false end\n end\n return true\nend\n\nwhile forward() do end"} {"title": "Old lady swallowed a fly", "language": "Lua", "task": "Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. \n\nThis song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.\n\n\n\n", "solution": "animals = {\"fly\", \"spider\", \"bird\", \"cat\",\"dog\", \"goat\", \"cow\", \"horse\"}\nphrases = {\n \"\",\n \"That wriggled and jiggled and tickled inside her\",\n \"How absurd to swallow a bird\",\n \"Fancy that to swallow a cat\",\n \"What a hog, to swallow a dog\",\n \"She just opened her throat and swallowed a goat\",\n \"I don't know how she swallowed a cow\",\n \" ...She's dead of course\"\n}\n\nfor i=0,7 do\n io.write(string.format(\"There was an old lady who swallowed a %s\\n\", animals[i+1]))\n if i>0 then io.write(phrases[i+1]) end\n if i==7 then break end\n if i>0 then\n io.write(\"\\n\")\n for j=i,1,-1 do\n io.write(string.format(\"She swallowed the %s to catch the %s\", animals[j+1], animals[j]))\n -- if j<4 then p='.' else p=',' end\n -- io.write(string.format(\"%s\\n\", p))\n io.write(\"\\n\")\n if j==2 then\n io.write(string.format(\"%s!\\n\", phrases[2]))\n end\n end\n end\n io.write(\"I don't know why she swallowed a fly - Perhaps she'll die!\\n\\n\")\nend"} {"title": "One of n lines in a file", "language": "Lua", "task": "A method of choosing a line randomly from a file:\n::* Without reading the file more than once\n::* When substantial parts of the file cannot be held in memory\n::* Without knowing how many lines are in the file\nIs to:\n::* keep the first line of the file as a possible choice, then\n::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.\n::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.\n::* ...\n::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N\n\n::* Return the computed possible choice when no further lines exist in the file.\n\n\n;Task:\n# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.\n# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.\n# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.\n\n\nNote: You may choose a smaller number of repetitions if necessary, but mention this up-front.\n\nNote: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling\n\n", "solution": "math.randomseed(os.time())\n\nlocal n = 10\nlocal trials = 1000000\n\nfunction one(n)\n local chosen = 1\n for i = 1, n do\n if math.random() < 1/i then\n chosen = i\n end\n end\n \n return chosen\nend\n\n-- 0 filled table for storing results\nlocal results = {}\nfor i = 1, n do results[i] = 0 end\n\n-- run simulation\nfor i = 1, trials do\n local result = one(n)\n results[result] = results[result] + 1\nend\n\nprint(\"Value\",\"Occurrences\")\nprint(\"-------------------\")\nfor k, v in ipairs(results) do\n print(k,v)\nend\n"} {"title": "Operator precedence", "language": "Lua", "task": "Operators in C and C++}}\n\n\n;Task:\nProvide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. \n\nOperators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. \n\nState whether arguments are passed by value or by reference.\n\n", "solution": "Table available [http://www.lua.org/manual/5.1/manual.html#2.5.6 here]. That table does not contain all operators, however.\n{| class=\"wikitable\"\n|-\n! Precedence\n! Operator\n! Description\n|-\n! lowest\n| '''or'''\n| Boolean OR\n|-\n!\n| '''and'''\n| Boolean AND\n|-\n!\n| '''<, <=, >, >=, ~=, =='''\n| Comparisons\n|-\n!\n| '''..'''\n| Concatenation [1]\n|-\n!\n| '''+, -'''\n| Addition and subtraction\n|-\n!\n| '''*, /, %'''\n| Multiplication, division, modulo\n|-\n!\n| '''not, -, #'''\n| Boolean NOT, negation, length\n|-\n!\n| '''^'''\n| Exponentiation [1]\n|-\n! highest\n| '''x[index], x.index, x(arguments...), x:m(arguments...)'''\n| Generic index, string index, function call, method index+call [2]\n|}\n\nNotes:\n# Concatenation and exponentiation are right-associative, all other binary operators are left-associative \n# Binding is done at the call site; therefore, method lookup is syntactically part of the call\n\n"} {"title": "Pangram checker", "language": "Lua", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: ''The quick brown fox jumps over the lazy dog''.\n\n\n;Task:\nWrite a function or method to check a sentence to see if it is a pangram (or not) and show its use.\n\n\n;Related tasks:\n:* determine if a string has all the same characters\n:* determine if a string has all unique characters\n\n", "solution": "require\"lpeg\"\nS, C = lpeg.S, lpeg.C\nfunction ispangram(s)\n return #(C(S(s)^0):match\"abcdefghijklmnopqrstuvwxyz\") == 26\nend\n\nprint(ispangram\"waltz, bad nymph, for quick jigs vex\")\nprint(ispangram\"bobby\")\nprint(ispangram\"long sentence\")"} {"title": "Parsing/RPN calculator algorithm", "language": "Lua", "task": "Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.\n\n\n* Assume an input of a correct, space separated, string of tokens of an RPN expression\n* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: \n 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* '''^''' means exponentiation in the expression above.\n* '''/''' means division.\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* [[Parsing/RPN to infix conversion]].\n* [[Arithmetic evaluation]].\n\n", "solution": "local stack = {}\nfunction push( a ) table.insert( stack, 1, a ) end\nfunction pop()\n if #stack == 0 then return nil end\n return table.remove( stack, 1 )\nend\nfunction writeStack()\n for i = #stack, 1, -1 do\n io.write( stack[i], \" \" )\n end\n print()\nend\nfunction operate( a )\n local s\n if a == \"+\" then\n push( pop() + pop() )\n io.write( a .. \"\\tadd\\t\" ); writeStack()\n elseif a == \"-\" then\n s = pop(); push( pop() - s )\n io.write( a .. \"\\tsub\\t\" ); writeStack()\n elseif a == \"*\" then\n push( pop() * pop() )\n io.write( a .. \"\\tmul\\t\" ); writeStack()\n elseif a == \"/\" then\n s = pop(); push( pop() / s )\n io.write( a .. \"\\tdiv\\t\" ); writeStack()\n elseif a == \"^\" then\n s = pop(); push( pop() ^ s )\n io.write( a .. \"\\tpow\\t\" ); writeStack()\n elseif a == \"%\" then\n s = pop(); push( pop() % s )\n io.write( a .. \"\\tmod\\t\" ); writeStack()\n else\n push( tonumber( a ) )\n io.write( a .. \"\\tpush\\t\" ); writeStack()\n end\nend\nfunction calc( s )\n local t, a = \"\", \"\"\n print( \"\\nINPUT\", \"OP\", \"STACK\" )\n for i = 1, #s do\n a = s:sub( i, i )\n if a == \" \" then operate( t ); t = \"\"\n else t = t .. a \n end\n end\n if a ~= \"\" then operate( a ) end\n print( string.format( \"\\nresult: %.13f\", pop() ) )\nend\n--[[ entry point ]]--\ncalc( \"3 4 2 * 1 5 - 2 3 ^ ^ / +\" )\ncalc( \"22 11 *\" )"} {"title": "Parsing/RPN to infix conversion", "language": "Lua", "task": "Create a program that takes an infix notation.\n\n* Assume an input of a correct, space separated, string of tokens\n* Generate a space separated output string representing the same expression in infix notation\n* Show how the major datastructure of your algorithm changes with each new token parsed.\n* Test with the following input RPN strings then print and display the output here.\n:::::{| class=\"wikitable\"\n! RPN input !! sample output\n|- || align=\"center\"\n| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\n|- || align=\"center\"\n| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\n|}\n\n* Operator precedence and operator associativity is given in this table:\n::::::::{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\" \n| ^ || 4 || right || exponentiation\n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\" \n| - || 2 || left || subtraction\n|}\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* Postfix to infix from the RubyQuiz site.\n\n", "solution": "function tokenize(rpn)\n local out = {}\n local cnt = 0\n for word in rpn:gmatch(\"%S+\") do\n table.insert(out, word)\n cnt = cnt + 1\n end\n return {tokens = out, pos = 1, size = cnt}\nend\n\nfunction advance(lex)\n if lex.pos <= lex.size then\n lex.pos = lex.pos + 1\n return true\n else\n return false\n end\nend\n\nfunction current(lex)\n return lex.tokens[lex.pos]\nend\n\nfunction isOperator(sym)\n return sym == '+' or sym == '-'\n or sym == '*' or sym == '/'\n or sym == '^'\nend\n\nfunction buildTree(lex)\n local stack = {}\n\n while lex.pos <= lex.size do\n local sym = current(lex)\n advance(lex)\n\n if isOperator(sym) then\n local b = table.remove(stack)\n local a = table.remove(stack)\n\n local t = {op=sym, left=a, right=b}\n table.insert(stack, t)\n else\n table.insert(stack, sym)\n end\n end\n\n return table.remove(stack)\nend\n\nfunction infix(tree)\n if type(tree) == \"table\" then\n local a = {}\n local b = {}\n\n if type(tree.left) == \"table\" then\n a = '(' .. infix(tree.left) .. ')'\n else\n a = tree.left\n end\n\n if type(tree.right) == \"table\" then\n b = '(' .. infix(tree.right) .. ')'\n else\n b = tree.right\n end\n\n return a .. ' ' .. tree.op .. ' ' .. b\n else\n return tree\n end\nend\n\nfunction convert(str)\n local lex = tokenize(str)\n local tree = buildTree(lex)\n print(infix(tree))\nend\n\nfunction main()\n convert(\"3 4 2 * 1 5 - 2 3 ^ ^ / +\")\n convert(\"1 2 + 3 4 + ^ 5 6 + ^\")\nend\n\nmain()"} {"title": "Parsing/Shunting-yard algorithm", "language": "Lua", "task": "Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "-- Lua 5.3.5\n-- Retrieved from: https://devforum.roblox.com/t/more-efficient-way-to-implement-shunting-yard/1328711\n-- Modified slightly to ensure conformity with other code snippets posted here\nlocal OPERATOR_PRECEDENCE = {\n -- [operator] = { [precedence], [is left assoc.] }\n ['-'] = { 2, true };\n ['+'] = { 2, true };\n ['/'] = { 3, true };\n ['*'] = { 3, true };\n ['^'] = { 4, false }; \n}\n\nlocal function shuntingYard(expression)\n local outputQueue = { }\n local operatorStack = { }\n \n local number, operator, parenthesis, fcall\n\n while #expression > 0 do\n local nStartPos, nEndPos = string.find(expression, '(%-?%d+%.?%d*)')\n \n if nStartPos == 1 and nEndPos > 0 then\n number, expression = string.sub(expression, nStartPos, nEndPos), string.sub(expression, nEndPos + 1)\n table.insert(outputQueue, tonumber(number))\n \n print('token:', number)\n print('queue:', unpack(outputQueue))\n print('stack:', unpack(operatorStack))\n else\n local oStartPos, oEndPos = string.find(expression, '([%-%+%*/%^])')\n \n if oStartPos == 1 and oEndPos > 0 then\n operator, expression = string.sub(expression, oStartPos, oEndPos), string.sub(expression, oEndPos + 1)\n \n if #operatorStack > 0 then\n while operatorStack[1] ~= '(' do\n local operator1Precedence = OPERATOR_PRECEDENCE[operator]\n local operator2Precedence = OPERATOR_PRECEDENCE[operatorStack[1]]\n \n if operator2Precedence and ((operator2Precedence[1] > operator1Precedence[1]) or (operator2Precedence[1] == operator1Precedence[1] and operator1Precedence[2])) then\n table.insert(outputQueue, table.remove(operatorStack, 1))\n else\n break \n end\n end\n end\n \n table.insert(operatorStack, 1, operator)\n \n print('token:', operator)\n print('queue:', unpack(outputQueue))\n print('stack:', unpack(operatorStack))\n else\n local pStartPos, pEndPos = string.find(expression, '[%(%)]')\n \n if pStartPos == 1 and pEndPos > 0 then\n parenthesis, expression = string.sub(expression, pStartPos, pEndPos), string.sub(expression, pEndPos + 1)\n \n if parenthesis == ')' then\n while operatorStack[1] ~= '(' do\n assert(#operatorStack > 0)\n table.insert(outputQueue, table.remove(operatorStack, 1))\n end\n \n assert(operatorStack[1] == '(')\n table.remove(operatorStack, 1)\n else\n table.insert(operatorStack, 1, parenthesis)\n end\n\n print('token:', parenthesis)\n print('queue:', unpack(outputQueue))\n print('stack:', unpack(operatorStack))\n else\n local wStartPos, wEndPos = string.find(expression, '%s+')\n \n if wStartPos == 1 and wEndPos > 0 then\n expression = string.sub(expression, wEndPos + 1)\n else\n error('Invalid character set: '.. expression)\n end\n end\n end\n end\n end\n \n while #operatorStack > 0 do\n assert(operatorStack[1] ~= '(')\n table.insert(outputQueue, table.remove(operatorStack, 1))\n end\n \n return table.concat(outputQueue, ' ')\nend\n\n\nlocal goodmath = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'\n\nprint('infix:', goodmath)\nprint('postfix:', shuntingYard(goodmath))\n"} {"title": "Pascal matrix generation", "language": "Lua", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.\n\nShown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. \n\nA Pascal upper-triangular matrix that is populated with jCi:\n\n[[1, 1, 1, 1, 1],\n [0, 1, 2, 3, 4],\n [0, 0, 1, 3, 6],\n [0, 0, 0, 1, 4],\n [0, 0, 0, 0, 1]]\n\n\nA Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):\n\n[[1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0],\n [1, 2, 1, 0, 0],\n [1, 3, 3, 1, 0],\n [1, 4, 6, 4, 1]]\n\n\nA Pascal symmetric matrix that is populated with i+jCi:\n\n[[1, 1, 1, 1, 1],\n [1, 2, 3, 4, 5],\n [1, 3, 6, 10, 15],\n [1, 4, 10, 20, 35],\n [1, 5, 15, 35, 70]]\n\n\n\n;Task:\nWrite functions capable of generating each of the three forms of n-by-n matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "function factorial (n)\n local f = 1\n for i = 2, n do\n f = f * i\n end\n return f\nend \n\nfunction binomial (n, k)\n if k > n then return 0 end\n return factorial(n) / (factorial(k) * factorial(n - k))\nend\n\nfunction pascalMatrix (form, size)\n local matrix = {}\n for row = 1, size do\n matrix[row] = {}\n for col = 1, size do\n if form == \"upper\" then\n matrix[row][col] = binomial(col - 1, row - 1)\n end\n if form == \"lower\" then\n matrix[row][col] = binomial(row - 1, col - 1)\n end\n if form == \"symmetric\" then\n matrix[row][col] = binomial(row + col - 2, col - 1)\n end\n end\n end\n matrix.form = form:sub(1, 1):upper() .. form:sub(2, -1)\n return matrix\nend\n\nfunction show (mat)\n print(mat.form .. \":\")\n for i = 1, #mat do\n for j = 1, #mat[i] do\n io.write(mat[i][j] .. \"\\t\")\n end\n print()\n end\n print()\nend\n\nfor _, form in pairs({\"upper\", \"lower\", \"symmetric\"}) do\n show(pascalMatrix(form, 5))\nend"} {"title": "Password generator", "language": "Lua", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a --> z\n upper-case letters: A --> Z\n digits: 0 --> 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include ''at least one'' (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), and \n one \"other\" character. \n\n\nThe user must be able to specify the password length and the number of passwords to generate. \n\nThe passwords should be displayed or written to a file, one per line.\n\nThe randomness should be from a system source or library. \n\nThe program should implement a help option or button which should describe the program and options when invoked. \n\nYou may also allow the user to specify a seed value, and give the option of excluding visually similar characters.\n\nFor example: Il1 O0 5S 2Z where the characters are: \n::::* capital eye, lowercase ell, the digit one\n::::* capital oh, the digit zero \n::::* the digit five, capital ess\n::::* the digit two, capital zee\n\n\n", "solution": "function randPW (length)\n local index, pw, rnd = 0, \"\"\n local chars = {\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n \"abcdefghijklmnopqrstuvwxyz\",\n \"0123456789\",\n \"!\\\"#$%&'()*+,-./:;<=>?@[]^_{|}~\"\n }\n repeat\n index = index + 1\n rnd = math.random(chars[index]:len())\n if math.random(2) == 1 then\n pw = pw .. chars[index]:sub(rnd, rnd)\n else\n pw = chars[index]:sub(rnd, rnd) .. pw\n end\n index = index % #chars\n until pw:len() >= length\n return pw\nend\n\nmath.randomseed(os.time())\nif #arg ~= 2 then\n print(\"\\npwgen.lua\")\n print(\"=========\\n\")\n print(\"A Lua script to generate random passwords.\\n\")\n print(\"Usage: lua pwgen.lua [password length] [number of passwords to generate]\\n\")\n os.exit()\nend\nfor i = 1, arg[2] do print(randPW(tonumber(arg[1]))) end"} {"title": "Pentagram", "language": "Lua", "task": "A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.\n\n\n;Task:\nDraw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.\n\n\n;See also\n* Angle sum of a pentagram\n\n", "solution": "local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi\n\nfunction Bitmap:render()\n for y = 1, self.height do\n print(table.concat(self.pixels[y]))\n end\nend\n\nfunction Bitmap:pentagram(x, y, radius, rotation, outlcolor, fillcolor)\n local function pxy(i) return x+radius*cos(i*pi*2/5+rotation), y+radius*sin(i*pi*2/5+rotation) end\n local x1, y1 = pxy(0)\n for i = 1, 5 do\n local x2, y2 = pxy(i*2) -- btw: pxy(i) ==> pentagon\n self:line(floor(x1*2), floor(y1), floor(x2*2), floor(y2), outlcolor)\n x1, y1 = x2, y2\n end\n self:floodfill(floor(x*2), floor(y), fillcolor)\n radius = radius / 2\n for i = 1, 5 do\n x1, y1 = pxy(i)\n self:floodfill(floor(x1*2), floor(y1), fillcolor)\n end\nend\n\nbitmap = Bitmap(40*2,40)\nbitmap:clear(\".\")\nbitmap:pentagram(20, 22, 20, -pi/2, \"@\", '+')\nbitmap:render()"} {"title": "Perfect shuffle", "language": "Lua", "task": "A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:\n\n\n\n::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K\n\n\n\nWhen you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:\n\n\n\n::::: {| style=\"border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right\"\n|-\n| ''original:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|-\n| ''after 1st shuffle:'' ||\n1\n5\n2\n6\n3\n7\n4\n8\n|-\n| ''after 2nd shuffle:'' ||\n1\n3\n5\n7\n2\n4\n6\n8\n|-\n| ''after 3rd shuffle:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|}\n\n\n'''''The Task'''''\n\n# Write a function that can perform a perfect shuffle on an even-sized list of values.\n# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under \"Test Cases\" below.\n#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all \"cards\" are unique within each deck.\n#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.\n'''''Test Cases'''''\n\n::::: {| class=\"wikitable\"\n|-\n! input ''(deck size)'' !! output ''(number of shuffles required)''\n|-\n| 8 || 3\n|-\n| 24 || 11\n|-\n| 52 || 8\n|-\n| 100 || 30\n|-\n| 1020 || 1018\n|-\n| 1024 || 10\n|-\n| 10000 || 300\n|}\n\n", "solution": "-- Perform weave shuffle\nfunction shuffle (cards)\n local pile1, pile2 = {}, {}\n for card = 1, #cards / 2 do table.insert(pile1, cards[card]) end\n for card = (#cards / 2) + 1, #cards do table.insert(pile2, cards[card]) end\n cards = {}\n for card = 1, #pile1 do\n table.insert(cards, pile1[card])\n table.insert(cards, pile2[card])\n end\n return cards\nend\n\n-- Return boolean indicating whether or not the cards are in order\nfunction inOrder (cards)\n for k, v in pairs(cards) do\n if k ~= v then return false end\n end\n return true\nend\n\n-- Count the number of shuffles needed before the cards are in order again\nfunction countShuffles (deckSize)\n local deck, count = {}, 0\n for i = 1, deckSize do deck[i] = i end\n repeat\n deck = shuffle(deck)\n count = count + 1\n until inOrder(deck)\n return count\nend\n\n-- Main procedure\nlocal testCases = {8, 24, 52, 100, 1020, 1024, 10000}\nprint(\"Input\", \"Output\")\nfor _, case in pairs(testCases) do print(case, countShuffles(case)) end"} {"title": "Perfect totient numbers", "language": "Lua", "task": "Generate and show here, the first twenty Perfect totient numbers.\n\n\n;Related task:\n::* [[Totient function]]\n\n\n;Also see:\n::* the OEIS entry for perfect totient numbers.\n::* mrob list of the first 54\n\n", "solution": "local function phi(n)\n assert(type(n) == 'number', 'n must be a number!')\n local result, i = n, 2\n while i <= n do\n if n % i == 0 then\n\t while n % i == 0 do n = n // i end\n\t result = result - (result // i)\n end\n if i == 2 then i = 1 end\n i = i + 2\n end\n if n > 1 then result = result - (result // n) end\n return result\nend\n\nlocal function phi_iter(n)\n assert(type(n) == 'number', 'n must be a number!')\n if n == 2 then\n return phi(n) + 0\n else\n return phi(n) + phi_iter(phi(n))\n end\nend\n\nlocal i, count = 2, 0\nwhile count ~= 20 do\n if i == phi_iter(i) then\n io.write(i, ' ')\n count = count + 1\n end\n i = i + 1\nend\n"} {"title": "Perlin noise", "language": "Lua", "task": "The '''computer graphics, most notably to procedurally generate textures or heightmaps. \n\nThe Perlin noise is basically a pseudo-random mapping of \\R^d into \\R with an integer d which can be arbitrarily large but which is usually 2, 3, or 4.\n\nEither by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.\n\n\n''Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.''\n\n", "solution": "local p = {\n\t151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n\t140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n\t247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n\t57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,\n\t74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n\t60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n\t65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n\t200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n\t52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n\t207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n\t119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n\t129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n\t218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n\t81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n\t184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n\t222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180\n}\n\n-- extending for easy access\nfor i = 1, #p do\n\tp[i+256]=p[i]\nend\n\nlocal function fade (t)\n--\tfade graph: https://www.desmos.com/calculator/d5cgqlrmem\n\treturn t*t*t*(t*(t*6-15)+10)\nend\n\nlocal function lerp (t, a, b)\n\treturn a+t*(b-a)\nend\n\nlocal function grad (hash, x, y, z)\n\tlocal h = hash%16\n\tlocal cases = {\n\t\t x+y,\n\t\t-x+y,\n\t\t x-y,\n\t\t-x-y,\n\t\n\t\t x+z,\n\t\t-x+z,\n\t\t x-z,\n\t\t-x-z,\n\n\t\t y+z,\n\t\t-y+z,\n\t\t y-z,\n\t\t-y-z,\n\t\n\t\t y+x,\n\t\t-y+z,\n\t\t y-x,\n\t\t-y-z,\n\t}\n\treturn cases[h+1]\nend\n\nlocal function noise (x,y,z)\n\tlocal a, b, c = math.floor(x)%256, math.floor(y)%256, math.floor(z)%256 -- values in range [0, 255]\n\tlocal xx, yy, zz = x%1, y%1, z%1\n\tlocal u, v, w = fade (xx), fade (yy), fade (zz)\n\tlocal a0 = p[a+1]+b\n\tlocal a1, a2 = p[a0+1]+c, p[a0+2]+c\n\tlocal b0 = p[a+2]+b\n\tlocal b1, b2 = p[b0+1]+c, p[b0+2]+c\n\tlocal k1 = grad(p[a1+1], xx, yy, zz)\n\tlocal k2 = grad(p[b1+1], xx-1, yy, zz)\n\tlocal k3 = grad(p[a2+1], xx, yy-1, zz)\n\tlocal k4 = grad(p[b2+1], xx-1, yy-1, zz)\n\tlocal k5 = grad(p[a1+2], xx, yy, zz-1)\n\tlocal k6 = grad(p[b1+2], xx-1, yy, zz-1)\n\tlocal k7 = grad(p[a2+2], xx, yy-1, zz-1)\n\tlocal k8 = grad(p[b2+2], xx-1, yy-1, zz-1)\n\treturn lerp(w, \n\t\tlerp(v, lerp(u, k1, k2), lerp(u, k3, k4)),\n\t\tlerp(v, lerp(u, k5, k6), lerp(u, k7, k8)))\nend\n\nprint (noise(3.14, 42, 7)) -- \t\t 0.136919958784\nprint (noise(1.4142, 1.2589, 2.718)) -- -0.17245663814988"} {"title": "Permutations/Derangements", "language": "Lua", "task": "A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.\n\nFor example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).\n\nThe number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. \nThere are various ways to calculate !''n''.\n\n\n;Task:\n# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer). \n# Generate ''and show'' all the derangements of 4 integers using the above routine.\n# Create a function that calculates the subfactorial of ''n'', !''n''.\n# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.\n\n\n;Optional stretch goal:\n* Calculate !''20'' \n\n\n;Related tasks:\n* [[Anagrams/Deranged anagrams]]\n* [[Best shuffle]]\n* [[Left_factorials]]\n\n\n\n", "solution": "-- Return an iterator to produce every permutation of list\nfunction permute (list)\n local function perm (list, n)\n if n == 0 then coroutine.yield(list) end\n for i = 1, n do\n list[i], list[n] = list[n], list[i]\n perm(list, n - 1)\n list[i], list[n] = list[n], list[i]\n end\n end\n return coroutine.wrap(function() perm(list, #list) end)\nend\n\n-- Return a copy of table t (wouldn't work for a table of tables)\nfunction copy (t)\n if not t then return nil end\n local new = {}\n for k, v in pairs(t) do new[k] = v end\n return new\nend\n\n-- Return true if no value in t1 can be found at the same index of t2\nfunction noMatches (t1, t2)\n for k, v in pairs(t1) do\n if t2[k] == v then return false end\n end\n return true\nend\n\n-- Return a table of all derangements of table t\nfunction derangements (t)\n local orig = copy(t)\n local nextPerm, deranged = permute(t), {}\n local numList, keep = copy(nextPerm())\n while numList do\n if noMatches(numList, orig) then table.insert(deranged, numList) end\n numList = copy(nextPerm())\n end\n return deranged\nend\n\n-- Return the subfactorial of n\nfunction subFact (n)\n if n < 2 then\n return 1 - n\n else\n return (subFact(n - 1) + subFact(n - 2)) * (n - 1)\n end\nend\n\n-- Return a table of the numbers 1 to n\nfunction listOneTo (n)\n local t = {}\n for i = 1, n do t[i] = i end\n return t\nend\n\n-- Main procedure\nprint(\"Derangements of [1,2,3,4]\")\nfor k, v in pairs(derangements(listOneTo(4))) do print(\"\", unpack(v)) end\nprint(\"\\n\\nSubfactorial vs counted derangements\\n\")\nprint(\"\\tn\\t| subFact(n)\\t| Derangements\")\nprint(\" \" .. string.rep(\"-\", 42))\nfor i = 0, 9 do\n io.write(\"\\t\" .. i .. \"\\t| \" .. subFact(i))\n if string.len(subFact(i)) < 5 then io.write(\"\\t\") end\n print(\"\\t| \" .. #derangements(listOneTo(i)))\nend\nprint(\"\\n\\nThe subfactorial of 20 is \" .. subFact(20))"} {"title": "Permutations by swapping", "language": "Lua from C++", "task": "Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. \n\nAlso generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. \n\nShow the permutations and signs of three items, in order of generation ''here''.\n\nSuch data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.\n\nNote: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus-Johnson-Trotter algorithm\n* Johnson-Trotter Algorithm Listing All Permutations\n* Heap's algorithm\n* Tintinnalogia\n\n\n;Related tasks:\n* [[Matrix arithmetic]\n* [[Gray code]]\n\n", "solution": "_JT={}\nfunction JT(dim)\n local n={ values={}, positions={}, directions={}, sign=1 }\n setmetatable(n,{__index=_JT})\n for i=1,dim do\n n.values[i]=i\n n.positions[i]=i\n n.directions[i]=-1\n end\n return n\nend\n\nfunction _JT:largestMobile()\n for i=#self.values,1,-1 do\n local loc=self.positions[i]+self.directions[i]\n if loc >= 1 and loc <= #self.values and self.values[loc] < i then\n return i\n end\n end\n return 0\nend\n\nfunction _JT:next()\n local r=self:largestMobile()\n if r==0 then return false end\n local rloc=self.positions[r]\n local lloc=rloc+self.directions[r]\n local l=self.values[lloc]\n self.values[lloc],self.values[rloc] = self.values[rloc],self.values[lloc]\n self.positions[l],self.positions[r] = self.positions[r],self.positions[l]\n self.sign=-self.sign\n for i=r+1,#self.directions do self.directions[i]=-self.directions[i] end\n return true\nend \n\n-- test\n\nperm=JT(4)\nrepeat\n print(unpack(perm.values))\nuntil not perm:next()"} {"title": "Phrase reversals", "language": "Lua", "task": "Given a string of space separated words containing the following phrase:\n rosetta code phrase reversal\n\n:# Reverse the characters of the string.\n:# Reverse the characters of each individual word in the string, maintaining original word order within the string.\n:# Reverse the order of each word of the string, maintaining the order of characters in each word.\n\nShow your output here.\n \n\n\n", "solution": "-- Return a copy of table t in which each string is reversed\nfunction reverseEach (t)\n local rev = {}\n for k, v in pairs(t) do rev[k] = v:reverse() end\n return rev\nend\n\n-- Return a reversed copy of table t\nfunction tabReverse (t)\n local revTab = {}\n for i, v in ipairs(t) do revTab[#t - i + 1] = v end\n return revTab\nend\n\n-- Split string str into a table on space characters\nfunction wordSplit (str)\n local t = {}\n for word in str:gmatch(\"%S+\") do table.insert(t, word) end\n return t\nend\n\n-- Main procedure\nlocal str = \"rosetta code phrase reversal\"\nlocal tab = wordSplit(str)\nprint(\"1. \" .. str:reverse())\nprint(\"2. \" .. table.concat(reverseEach(tab), \" \"))\nprint(\"3. \" .. table.concat(tabReverse(tab), \" \"))"} {"title": "Pig the dice game", "language": "lua 5.1", "task": "The game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach '''100''' points or more. \nPlay is taken in turns. On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.\n\n\n;Task:\nCreate a program to score for, and simulate dice throws for, a two-person game. \n\n\n;Related task:\n* [[Pig the dice game/Player]]\n\n", "solution": "local numPlayers = 2\nlocal maxScore = 100\nlocal scores = { }\nfor i = 1, numPlayers do\n\tscores[i] = 0 -- total safe score for each player\nend\nmath.randomseed(os.time())\nprint(\"Enter a letter: [h]old or [r]oll?\")\nlocal points = 0 -- points accumulated in current turn\nlocal p = 1 -- start with first player\nwhile true do\n\tio.write(\"\\nPlayer \"..p..\", your score is \".. scores[p]..\", with \".. points..\" temporary points. \")\n\tlocal reply = string.sub(string.lower(io.read(\"*line\")), 1, 1)\n\tif reply == 'r' then\n\t\tlocal roll = math.random(6)\n\t\tio.write(\"You rolled a \" .. roll)\n\t\tif roll == 1 then\n\t\t\tprint(\". Too bad. :(\")\n\t\t\tp = (p % numPlayers) + 1\n\t\t\tpoints = 0\n\t\telse\n\t\t\tpoints = points + roll\n\t\tend\n\telseif reply == 'h' then\n\t\tscores[p] = scores[p] + points\n\t\tif scores[p] >= maxScore then\n\t\t\tprint(\"Player \"..p..\", you win with a score of \"..scores[p])\n\t\t\tbreak\n\t\tend\n\t\tprint(\"Player \"..p..\", your new score is \" .. scores[p])\n\t\tp = (p % numPlayers) + 1\n\t\tpoints = 0\n\tend\nend\n"} {"title": "Plasma effect", "language": "Lua from C++", "task": "The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.\n\n\n;Task\nCreate a plasma effect.\n\n\n;See also\n* Computer Graphics Tutorial (lodev.org)\n* Plasma (bidouille.org)\n\n", "solution": "_ = love.graphics\np1, p2, points = {}, {}, {}\n\nfunction hypotenuse( a, b )\n return a * a + b * b\nend\nfunction love.load()\n size = _.getWidth()\n currentTime, doub, half = 0, size * 2, size / 2\n local b1, b2\n \n for j = 0, size * 2 do\n for i = 0, size * 2 do\n b1 = math.floor( 128 + 127 * ( math.cos( math.sqrt( hypotenuse( size - j , size - i ) ) / 64 ) ) )\n b2 = math.floor( ( math.sin( ( math.sqrt( 128.0 + hypotenuse( size - i, size - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90 )\n table.insert( p1, b1 ); table.insert( p2, b2 )\n end\n end\nend\nfunction love.draw()\n local a, c1, c2, c3, s1, s2, s3\n currentTime = currentTime + math.random( 2 ) * 3\n local x1 = math.floor( half + ( half - 2 ) * math.sin( currentTime / 47 ) )\n local x2 = math.floor( half + ( half / 7 ) * math.sin( -currentTime / 149 ) )\n local x3 = math.floor( half + ( half - 3 ) * math.sin( -currentTime / 157 ) )\n local y1 = math.floor( half + ( half / 11 ) * math.cos( currentTime / 71 ) )\n local y2 = math.floor( half + ( half - 5 ) * math.cos( -currentTime / 181 ) )\n local y3 = math.floor( half + ( half / 23 ) * math.cos( -currentTime / 137 ) )\n s1 = y1 * doub + x1; s2 = y2 * doub + x2; s3 = y3 * doub + x3\n for j = 0, size do\n for i = 0, size do\n a = p2[s1] + p1[s2] + p2[s3]\n c1 = a * 2; c2 = a * 4; c3 = a * 8\n table.insert( points, { i, j, c1, c2, c3, 255 } )\n s1 = s1 + 1; s2 = s2 + 1; s3 = s3 + 1;\n end\n s1 = s1 + size; s2 = s2 + size; s3 = s3 + size\n end\n _.points( points ) \nend\n"} {"title": "Poker hand analyser", "language": "Lua", "task": "Create a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' (two of diamonds).\n\n\n\nFaces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or \nalternatively, the unicode card-suit characters: \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2 2 2 k q: three-of-a-kind\n 2 5 7 8 9: high-card\n a 2 3 4 5: straight\n 2 3 2 3 3: full-house\n 2 7 2 3 3: two-pair\n 2 7 7 7 7: four-of-a-kind \n 10 j q k a: straight-flush\n 4 4 k 5 10: one-pair\n q 10 7 6 q: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2 2 k q: three-of-a-kind\n joker 5 7 8 9: straight\n joker 2 3 4 5: straight\n joker 3 2 3 3: four-of-a-kind\n joker 7 2 3 3: three-of-a-kind\n joker 7 7 7 7: five-of-a-kind\n joker j q k A: straight-flush\n joker 4 k 5 10: one-pair\n joker k 7 6 4: flush\n joker 2 joker 4 5: straight\n joker Q joker A 10: straight\n joker Q joker A 10: straight-flush\n joker 2 2 joker q: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "-- Check whether t is a valid poker hand\nfunction valid (t)\n if #t ~= 5 then return false end\n for k, v in pairs(t) do\n for key, card in pairs(t) do\n if v.value == card.value and\n v.suit == card.suit and\n k ~= key\n then\n return false\n end\n end\n end\n return true\nend\n\n-- Return numerical value of a single card\nfunction cardValue (card)\n local val = card:sub(1, -2)\n local n = tonumber(val)\n if n then return n end\n if val == \"j\" then return 11 end\n if val == \"q\" then return 12 end\n if val == \"k\" then return 13 end\n if val == \"a\" then return 1 end\n error(\"Invalid card value: \" .. val)\nend\n\n-- Detect whether hand t is a straight\nfunction straight (t)\n table.sort(t, function (a, b) return a.value < b.value end)\n local ace, thisValue, lastValue = false\n for i = 2, #t do\n thisValue, lastValue = t[i].value, t[i-1].value\n if lastValue == 1 then ace = i - 1 end\n if thisValue ~= lastValue + 1 then\n if ace then\n t[ace].value = 14\n return straight(t)\n else\n return false\n end\n end\n end\n return true\nend\n\n-- Detect whether hand t is a flush\nfunction isFlush (t)\n local suit = t[1].suit\n for card = 2, #t do\n if t[card].suit ~= suit then return false end\n end\n return true\nend\n\n-- Return a table of the count of each card value in hand t\nfunction countValues (t)\n local countTab, maxCount = {}, 0\n for k, v in pairs(t) do\n if countTab[v.value] then\n countTab[v.value] = countTab[v.value] + 1\n else\n countTab[v.value] = 1\n end\n end\n return countTab\nend\n\n-- Find the highest value in t\nfunction highestCount (t)\n local maxCount = 0\n for k, v in pairs(t) do\n if v > maxCount then maxCount = v end\n end\n return maxCount\nend\n\n-- Detect full-house and two-pair using the value counts in t\nfunction twoTypes (t)\n local threes, twos = 0, 0\n for k, v in pairs(t) do\n if v == 3 then threes = threes + 1 end\n if v == 2 then twos = twos + 1 end\n end\n return threes, twos\nend\n\n-- Return the rank of a poker hand represented as a string\nfunction rank (cards)\n local hand = {}\n for card in cards:gmatch(\"%S+\") do\n table.insert(hand, {value = cardValue(card), suit = card:sub(-1, -1)})\n end\n if not valid(hand) then return \"invalid\" end\n local st, fl = straight(hand), isFlush(hand)\n if st and fl then return \"straight-flush\" end\n local valCount = countValues(hand)\n local highCount = highestCount(valCount)\n if highCount == 4 then return \"four-of-a-kind\" end\n local n3, n2 = twoTypes(valCount)\n if n3 == 1 and n2 == 1 then return \"full-house\" end\n if fl then return \"flush\" end\n if st then return \"straight\" end\n if highCount == 3 then return \"three-of-a-kind\" end\n if n3 == 0 and n2 == 2 then return \"two-pair\" end\n if highCount == 2 then return \"one-pair\" end\n return \"high-card\"\nend\n\n-- Main procedure\nlocal testCases = {\n \"2h 2d 2c kc qd\", -- three-of-a-kind\n \"2h 5h 7d 8c 9s\", -- high-card\n \"ah 2d 3c 4c 5d\", -- straight\n \"2h 3h 2d 3c 3d\", -- full-house\n \"2h 7h 2d 3c 3d\", -- two-pair\n \"2h 7h 7d 7c 7s\", -- four-of-a-kind \n \"10h jh qh kh ah\",-- straight-flush\n \"4h 4s ks 5d 10s\",-- one-pair\n \"qc 10c 7c 6c 4c\" -- flush\n}\nfor _, case in pairs(testCases) do print(case, \": \" .. rank(case)) end"} {"title": "Population count", "language": "Lua", "task": "The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.\n\n''Population count'' is also known as:\n::::* ''pop count''\n::::* ''popcount'' \n::::* ''sideways sum''\n::::* ''bit summation'' \n::::* ''Hamming weight'' \n\n\nFor example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.\n\n\n''Evil numbers'' are non-negative integers that have an ''even'' population count.\n\n''Odious numbers'' are positive integers that have an ''odd'' population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with '''0''' (zero indexed).\n:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').\n:* display the 1st thirty ''evil'' numbers.\n:* display the 1st thirty ''odious'' numbers.\n* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.\n\n", "solution": "-- Take decimal number, return binary string\nfunction dec2bin (n)\n local bin, bit = \"\"\n while n > 0 do\n bit = n % 2\n n = math.floor(n / 2)\n bin = bit .. bin\n end\n return bin\nend\n \n-- Take decimal number, return population count as number\nfunction popCount (n)\n local bin, count = dec2bin(n), 0\n for pos = 1, bin:len() do\n if bin:sub(pos, pos) == \"1\" then count = count + 1 end\n end\n return count\nend\n\n-- Implement task requirements\nfunction firstThirty (mode)\n local numStr, count, n, remainder = \"\", 0, 0\n if mode == \"Evil\" then remainder = 0 else remainder = 1 end\n while count < 30 do\n if mode == \"3^x\" then\n numStr = numStr .. popCount(3 ^ count) .. \" \"\n count = count + 1\n else\n if popCount(n) % 2 == remainder then\n numStr = numStr .. n .. \" \"\n count = count + 1\n end\n n = n + 1\n end\n end\n print(mode .. \":\" , numStr)\nend\n\n-- Main procedure\nfirstThirty(\"3^x\")\nfirstThirty(\"Evil\")\nfirstThirty(\"Odious\")"} {"title": "Pragmatic directives", "language": "Lua", "task": "Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).\n\n\n;Task:\nList any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.\n\n", "solution": "ffi = require(\"ffi\")\nffi.cdef[[\n #pragma pack(1)\n typedef struct { char c; int i; } foo;\n #pragma pack(4)\n typedef struct { char c; int i; } bar;\n]]\nprint(ffi.sizeof(ffi.new(\"foo\")))\nprint(ffi.sizeof(ffi.new(\"bar\")))"} {"title": "Priority queue", "language": "Lua", "task": "A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.\n\n\n;Task:\nCreate a priority queue. The queue must support at least two operations:\n:# Insertion. An element is added to the queue with a priority (a numeric value).\n:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.\n\n\nOptionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.\n\n\nTo test your implementation, insert a number of elements into the queue, each with some random priority. \n\nThen dequeue them sequentially; now the elements should be sorted by priority. \n\nYou can use the following task/priority items as input data:\n '''Priority''' '''Task'''\n ---------- ----------------\n 3 Clear drains\n 4 Feed cat\n 5 Make tea\n 1 Solve RC tasks\n 2 Tax return\n\n\nThe implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. \n\nYou may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.\n\n", "solution": "PriorityQueue = {\n __index = {\n put = function(self, p, v)\n local q = self[p]\n if not q then\n q = {first = 1, last = 0}\n self[p] = q\n end\n q.last = q.last + 1\n q[q.last] = v\n end,\n pop = function(self)\n for p, q in pairs(self) do\n if q.first <= q.last then\n local v = q[q.first]\n q[q.first] = nil\n q.first = q.first + 1\n return p, v\n else\n self[p] = nil\n end\n end\n end\n },\n __call = function(cls)\n return setmetatable({}, cls)\n end\n}\n\nsetmetatable(PriorityQueue, PriorityQueue)\n\n-- Usage:\npq = PriorityQueue()\n\ntasks = {\n {3, 'Clear drains'},\n {4, 'Feed cat'},\n {5, 'Make tea'},\n {1, 'Solve RC tasks'},\n {2, 'Tax return'}\n}\n\nfor _, task in ipairs(tasks) do\n print(string.format(\"Putting: %d - %s\", unpack(task)))\n pq:put(unpack(task))\nend\n\nfor prio, task in pq.pop, pq do\n print(string.format(\"Popped: %d - %s\", prio, task))\nend"} {"title": "Pseudo-random numbers/Middle-square method", "language": "Lua", "task": "{{Wikipedia|Middle-square method|en}}\n; The Method:\nTo generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. \n; Pseudo code:\n\nvar seed = 675248\nfunction random()\n var s = str(seed * seed) 'str: turn a number into string\n do while not len(s) = 12\n s = \"0\" + s 'add zeroes before the string\n end do\n seed = val(mid(s, 4, 6)) 'mid: string variable, start, length\n 'val: turn a string into number\n return seed\nend function\n\n; Middle-square method use:\n\nfor i = 1 to 5\n print random()\nend for\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers (6 digits) as shown above.\n\n* Show the first five integers generated with the seed 675248 as shown above.\n\n* Show your output here, on this page.\n\n", "solution": "seed = 675248\n\nfunction rnd ()\n local s = tostring(seed * seed)\n while #s ~= 12 do\n s = \"0\" .. s\n end\n seed = tonumber(s:sub(4, 9))\n return seed\nend\n\nfor i = 1, 5 do\n print(rnd())\nend\n"} {"title": "Pseudo-random numbers/PCG32", "language": "Lua from C", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n:'''|''' Bitwise or operator\n::https://en.wikipedia.org/wiki/Bitwise_operation#OR\n::Bitwise comparison gives 1 if any of corresponding bits are 1\n:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111\n\n\n;PCG32 Generator (pseudo-code):\n\nPCG32 has two unsigned 64-bit integers of internal state:\n# '''state''': All 2**64 values may be attained.\n# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).\n\nValues of sequence allow 2**63 ''different'' sequences of random numbers from the same state.\n\nThe algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-\n\nconst N<-U64 6364136223846793005\nconst inc<-U64 (seed_sequence << 1) | 1\nstate<-U64 ((inc+seed_state)*N+inc\ndo forever\n xs<-U32 (((state>>18)^state)>>27)\n rot<-INT (state>>59)\n OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))\n state<-state*N+inc\nend do\n\nNote that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers using the above.\n\n* Show that the first five integers generated with the seed 42, 54\nare: 2707161783 2068313097 3122475824 2211639955 3215226955\n\n \n\n* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005\n\n* Show your output here, on this page.\n\n\n", "solution": "function uint32(n)\n return n & 0xffffffff\nend\n \nfunction uint64(n)\n return n & 0xffffffffffffffff\nend\n \nN = 6364136223846793005\nstate = 0x853c49e6748fea9b\ninc = 0xda3e39cb94b95bdb\n \nfunction pcg32_seed(seed_state, seed_sequence)\n state = 0\n inc = (seed_sequence << 1) | 1\n pcg32_int()\n state = state + seed_state\n pcg32_int()\nend\n \nfunction pcg32_int()\n local old = state\n state = uint64(old * N + inc)\n local shifted = uint32(((old >> 18) ~ old) >> 27)\n local rot = uint32(old >> 59)\n return uint32((shifted >> rot) | (shifted << ((~rot + 1) & 31)))\nend\n \nfunction pcg32_float()\n return 1.0 * pcg32_int() / (1 << 32)\nend\n \n-------------------------------------------------------------------\n \npcg32_seed(42, 54)\nprint(pcg32_int())\nprint(pcg32_int())\nprint(pcg32_int())\nprint(pcg32_int())\nprint(pcg32_int())\nprint()\n \ncounts = { 0, 0, 0, 0, 0 }\npcg32_seed(987654321, 1)\nfor i=1,100000 do\n local j = math.floor(pcg32_float() * 5.0) + 1\n counts[j] = counts[j] + 1\nend\n \nprint(\"The counts for 100,000 repetitions are:\")\nfor i=1,5 do\n print(\" \" .. (i - 1) .. \": \" .. counts[i])\nend"} {"title": "Pseudo-random numbers/Xorshift star", "language": "Lua from C", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n;Xorshift_star Generator (pseudo-code):\n\n /* Let u64 denote an unsigned 64 bit integer type. */\n /* Let u32 denote an unsigned 32 bit integer type. */\n \n class Xorshift_star\n u64 state /* Must be seeded to non-zero initial value */\n u64 const = HEX '2545F4914F6CDD1D'\n \n method seed(u64 num):\n state = num\n end method\n \n method next_int():\n u64 x = state\n x = x ^ (x >> 12)\n x = x ^ (x << 25)\n x = x ^ (x >> 27)\n state = x\n u32 answer = ((x * const) >> 32)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / (1 << 32)\n end method\n \n end class\n \n:;Xorshift use:\n\n random_gen = instance Xorshift_star\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 3540625527 */\n print(random_gen.next_int()) /* 2750739987 */\n print(random_gen.next_int()) /* 4037983143 */\n print(random_gen.next_int()) /* 1993361440 */\n print(random_gen.next_int()) /* 3809424708 */\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers genrated with the seed 1234567\nare as shown above \n\n* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007\n\n* Show your output here, on this page.\n\n\n\n", "solution": "function create()\n local g = {\n magic = 0x2545F4914F6CDD1D,\n state = 0,\n seed = function(self, num)\n self.state = num\n end,\n next_int = function(self)\n local x = self.state\n x = x ~ (x >> 12)\n x = x ~ (x << 25)\n x = x ~ (x >> 27)\n self.state = x\n local answer = (x * self.magic) >> 32\n return answer\n end,\n next_float = function(self)\n return self:next_int() / (1 << 32)\n end\n }\n return g\nend\n\nlocal g = create()\ng:seed(1234567)\nprint(g:next_int())\nprint(g:next_int())\nprint(g:next_int())\nprint(g:next_int())\nprint(g:next_int())\nprint()\n\nlocal counts = {[0]=0, [1]=0, [2]=0, [3]=0, [4]=0}\ng:seed(987654321)\nfor i=1,100000 do\n local j = math.floor(g:next_float() * 5.0)\n counts[j] = counts[j] + 1\nend\nfor i,v in pairs(counts) do\n print(i..': '..v)\nend"} {"title": "Pythagorean quadruples", "language": "Lua", "task": "One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): \n\n\n:::::::: a2 + b2 + c2 = d2 \n\n\nAn example:\n\n:::::::: 22 + 32 + 62 = 72 \n\n::::: which is:\n\n:::::::: 4 + 9 + 36 = 49 \n\n\n;Task:\n\nFor positive integers up '''2,200''' (inclusive), for all values of '''a''', \n'''b''', '''c''', and '''d''', \nfind (and show here) those values of '''d''' that ''can't'' be represented.\n\nShow the values of '''d''' on one line of output (optionally with a title).\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]]. \n* [[Pythagorean triples]].\n\n\n;Reference:\n:* the Wikipedia article: Pythagorean quadruple.\n\n", "solution": "-- initialize\nlocal N = 2200\nlocal ar = {}\nfor i=1,N do\n ar[i] = false\nend\n\n-- process\nfor a=1,N do\n for b=a,N do\n if (a % 2 ~= 1) or (b % 2 ~= 1) then\n local aabb = a * a + b * b\n for c=b,N do\n local aabbcc = aabb + c * c\n local d = math.floor(math.sqrt(aabbcc))\n if (aabbcc == d * d) and (d <= N) then\n ar[d] = true\n end\n end\n end\n end\n -- print('done with a='..a)\nend\n\n-- print\nfor i=1,N do\n if not ar[i] then\n io.write(i..\" \")\n end\nend\nprint()"} {"title": "Quaternion type", "language": "Lua", "task": "complex numbers.\n\nA complex number has a real and complex part, sometimes written as a + bi, \nwhere a and b stand for real numbers, and i stands for the square root of minus 1.\n\nAn example of a complex number might be -3 + 2i, \nwhere the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, i, j, and k. \n\nA quaternion might be written as a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* ii = jj = kk = ijk = -1, or more simply,\n:::* ii = jj = kk = ijk = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: q1 and q2: q1q2 q2q1. \n\nAn example of a quaternion might be 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. \n\nSo the example above would be written as (1, 2, 3, 4) \n\n\n;Task:\nGiven the three quaternions and their components: \n q = (1, 2, 3, 4) = (a, b, c, d)\n q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)\n q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) \nAnd a wholly real number r = 7. \n\n\nCreate functions (or classes) to perform simple maths with quaternions including computing:\n# The norm of a quaternion: = \\sqrt{a^2 + b^2 + c^2 + d^2} \n# The negative of a quaternion: = (-a, -b, -c, -d) \n# The conjugate of a quaternion: = ( a, -b, -c, -d) \n# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) \n# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) \n# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) \n# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) \n# Show that, for the two quaternions q1 and q2: q1q2 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* [[Vector products]]\n* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.\n\n", "solution": "Quaternion = {}\n\nfunction Quaternion.new( a, b, c, d )\n local q = { a = a or 1, b = b or 0, c = c or 0, d = d or 0 }\n\n local metatab = {}\n setmetatable( q, metatab )\n metatab.__add = Quaternion.add\n metatab.__sub = Quaternion.sub\n metatab.__unm = Quaternion.unm\n metatab.__mul = Quaternion.mul\n\n return q\nend\n\nfunction Quaternion.add( p, q )\n if type( p ) == \"number\" then\n\treturn Quaternion.new( p+q.a, q.b, q.c, q.d )\n elseif type( q ) == \"number\" then\n\treturn Quaternion.new( p.a+q, p.b, p.c, p.d )\n else\n\treturn Quaternion.new( p.a+q.a, p.b+q.b, p.c+q.c, p.d+q.d )\n end\nend\n\nfunction Quaternion.sub( p, q )\n if type( p ) == \"number\" then\n\treturn Quaternion.new( p-q.a, q.b, q.c, q.d )\n elseif type( q ) == \"number\" then\n\treturn Quaternion.new( p.a-q, p.b, p.c, p.d )\n else\n\treturn Quaternion.new( p.a-q.a, p.b-q.b, p.c-q.c, p.d-q.d )\n end\nend\n\nfunction Quaternion.unm( p )\n return Quaternion.new( -p.a, -p.b, -p.c, -p.d )\nend\n\nfunction Quaternion.mul( p, q )\n if type( p ) == \"number\" then\n\treturn Quaternion.new( p*q.a, p*q.b, p*q.c, p*q.d )\n elseif type( q ) == \"number\" then\n\treturn Quaternion.new( p.a*q, p.b*q, p.c*q, p.d*q )\n else\n\treturn Quaternion.new( p.a*q.a - p.b*q.b - p.c*q.c - p.d*q.d,\n p.a*q.b + p.b*q.a + p.c*q.d - p.d*q.c,\n \t\t\t p.a*q.c - p.b*q.d + p.c*q.a + p.d*q.b,\n\t\t\t p.a*q.d + p.b*q.c - p.c*q.b + p.d*q.a )\n end\nend\n\nfunction Quaternion.conj( p )\n return Quaternion.new( p.a, -p.b, -p.c, -p.d )\nend\n\nfunction Quaternion.norm( p )\n return math.sqrt( p.a^2 + p.b^2 + p.c^2 + p.d^2 )\nend\n\nfunction Quaternion.print( p )\n print( string.format( \"%f + %fi + %fj + %fk\\n\", p.a, p.b, p.c, p.d ) )\nend"} {"title": "Quine", "language": "Lua", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA '''quine''' (named after Willard Van Orman Quine) is also known as:\n::* ''self-reproducing automata'' (1972)\n::* ''self-replicating program'' or ''self-replicating computer program''\n::* ''self-reproducing program'' or ''self-reproducing computer program''\n::* ''self-copying program'' or ''self-copying computer program''\n\n\n\nIt is named after the philosopher and logician \nwho studied self-reference and quoting in natural language, \nas for example in the paradox \"'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation.\"\n\n\"Source\" has one of two meanings. It can refer to the text-based program source. \nFor languages in which program source is represented as a data structure, \"source\" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.\n\nThe usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.\n\n\n;Task:\nWrite a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.\n\nThere are several difficulties that one runs into when writing a quine, mostly dealing with quoting:\n* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.\n** Some languages have a function for getting the \"source code representation\" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.\n** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.\n* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. \"\\n\"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.\n** If the language has a way of getting the \"source code representation\", it usually handles the escaping of characters, so this is not a problem.\n** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.\n** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.\n\n\n'''Next to the Quines presented here, many other versions can be found on the Quine page.'''\n\n\n;Related task:\n:* print itself.\n\n", "solution": "s=[[io.write('s=[','[',s,']','];',s)]];io.write('s=[','[',s,']','];',s)"} {"title": "Quoting constructs", "language": "Lua", "task": "Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.\n\nShow examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?\n\nThis is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, '''NOT''' just a link to [See the language docs].\n\nNote: This is primarily for quoting constructs for data to be \"embedded\" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.\n", "solution": "s1 = \"This is a double-quoted 'string' with embedded single-quotes.\"\ns2 = 'This is a single-quoted \"string\" with embedded double-quotes.'\ns3 = \"this is a double-quoted \\\"string\\\" with escaped double-quotes.\"\ns4 = 'this is a single-quoted \\'string\\' with escaped single-quotes.'\ns5 = [[This is a long-bracket \"'string'\" with embedded single- and double-quotes.]]\ns6 = [=[This is a level 1 long-bracket ]]string[[ with [[embedded]] long-brackets.]=]\ns7 = [==[This is a level 2 long-bracket ]=]string[=[ with [=[embedded]=] level 1 long-brackets, etc.]==]\ns8 = [[This is\na long-bracket string\nwith embedded\nline feeds]]\ns9 = \"any \\0 form \\1 of \\2 string \\3 may \\4 contain \\5 raw \\6 binary \\7 data \\xDB\"\nprint(s1)\nprint(s2)\nprint(s3)\nprint(s4)\nprint(s5)\nprint(s6)\nprint(s7)\nprint(s8)\nprint(s9) -- with audible \"bell\" from \\7 if supported by os\nprint(\"some raw binary:\", #s9, s9:byte(5), s9:byte(12), s9:byte(17))"} {"title": "Random number generator (included)", "language": "Lua", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "Lua's math.random() is an interface to the C rand() function provided by the OS libc; its implementation varies by platform.\n\n"} {"title": "Range expansion", "language": "Lua", "task": "{{:Range extraction/Format}}\n\n\n;Task:\nExpand the range description: \n -6,-3--1,3-5,7-11,14,15,17-20 \nNote that the second element above, \nis the '''range from minus 3 to ''minus'' 1'''. \n\n\n;Related task:\n* [[Range extraction]]\n\n", "solution": "function range(i, j)\n local t = {}\n for n = i, j, i0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* A005132, The On-Line Encyclopedia of Integer Sequences.\n* The Slightly Spooky Recaman Sequence, Numberphile video.\n* Recaman's sequence, on Wikipedia.\n\n", "solution": "local a = {[0]=0}\nlocal used = {[0]=true}\nlocal used1000 = {[0]=true}\nlocal foundDup = false\nlocal n = 1\n\nwhile n<=15 or not foundDup or #used1000<1001 do\n local nxt = a[n - 1] - n\n if nxt<1 or used[nxt] ~= nil then\n nxt = nxt + 2 * n\n end\n local alreadyUsed = used[nxt] ~= nil\n table.insert(a, nxt)\n if not alreadyUsed then\n used[nxt] = true\n if 0<=nxt and nxt<=1000 then\n used1000[nxt] = true\n end\n end\n if n==14 then\n io.write(\"The first 15 terms of the Recaman sequence are:\")\n for k=0,#a do\n io.write(\" \"..a[k])\n end\n print()\n end\n if not foundDup and alreadyUsed then\n print(\"The first duplicated term is a[\"..n..\"] = \"..nxt)\n foundDup = true\n end\n if #used1000 == 1001 then\n print(\"Terms up to a[\"..n..\"] are needed to generate 0 to 1000\")\n end\n n = n + 1\nend"} {"title": "Remove lines from a file", "language": "Lua", "task": "Remove a specific line or a number of lines from a file. \n\nThis should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). \n\nFor the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2\n\nEmpty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. \n\nAn appropriate message should appear if an attempt is made to remove lines beyond the end of the file.\n\n", "solution": "function remove( filename, starting_line, num_lines )\n local fp = io.open( filename, \"r\" )\n if fp == nil then return nil end\n\n content = {}\n i = 1;\n for line in fp:lines() do\n if i < starting_line or i >= starting_line + num_lines then\n\t content[#content+1] = line\n\tend\n\ti = i + 1\n end\n\n if i > starting_line and i < starting_line + num_lines then\n\tprint( \"Warning: Tried to remove lines after EOF.\" )\n end\n\n fp:close()\n fp = io.open( filename, \"w+\" )\n\n for i = 1, #content do\n\tfp:write( string.format( \"%s\\n\", content[i] ) )\n end\n\n fp:close()\nend"} {"title": "Repeat", "language": "Lua", "task": "Write a procedure which accepts as arguments another procedure and a positive integer. \n\nThe latter procedure is executed a number of times equal to the accepted integer.\n\n", "solution": "function myFunc ()\n print(\"Sure looks like a function in here...\")\nend\n\nfunction rep (func, times)\n for count = 1, times do\n func()\n end\nend\n\nrep(myFunc, 4)\n"} {"title": "Reverse words in a string", "language": "Lua", "task": "Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! would be shown reversed as: Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. \n\nYou may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string (or one just containing spaces) would be the result.\n\n'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. \n\n(You can consider the ten strings as ten lines, and the tokens as words.)\n\n\n;Input data\n\n (ten lines within the box)\n line\n +----------------------------------------+\n 1 | ---------- Ice and Fire ------------ |\n 2 | | <--- a blank line here.\n 3 | fire, in end will world the say Some |\n 4 | ice. in say Some |\n 5 | desire of tasted I've what From |\n 6 | fire. favor who those with hold I |\n 7 | | <--- a blank line here.\n 8 | ... elided paragraph last ... |\n 9 | | <--- a blank line here.\n 10 | Frost Robert ----------------------- |\n +----------------------------------------+\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "function table.reverse(a)\n local res = {}\n for i = #a, 1, -1 do\n res[#res+1] = a[i]\n end\n return res\nend\n\nfunction splittokens(s)\n local res = {}\n for w in s:gmatch(\"%S+\") do\n res[#res+1] = w\n end\n return res\nend\n\nfor line, nl in s:gmatch(\"([^\\n]-)(\\n)\") do\n print(table.concat(table.reverse(splittokens(line)), ' '))\nend"} {"title": "Roman numerals/Decode", "language": "Lua", "task": "Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. \n\nYou don't need to validate the form of the Roman numeral.\n\nModern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, \nstarting with the leftmost decimal digit and skipping any '''0'''s (zeroes). \n\n'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and \n'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).\n \nThe Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.\n\n", "solution": "function ToNumeral( roman )\n local Num = { [\"M\"] = 1000, [\"D\"] = 500, [\"C\"] = 100, [\"L\"] = 50, [\"X\"] = 10, [\"V\"] = 5, [\"I\"] = 1 }\n local numeral = 0 \n \n local i = 1\n local strlen = string.len(roman)\n while i < strlen do\n local z1, z2 = Num[ string.sub(roman,i,i) ], Num[ string.sub(roman,i+1,i+1) ]\n if z1 < z2 then\n numeral = numeral + ( z2 - z1 )\n i = i + 2\n else\n numeral = numeral + z1\n i = i + 1 \n end \n end\n \n if i <= strlen then numeral = numeral + Num[ string.sub(roman,i,i) ] end\n \n return numeral \nend\n\nprint( ToNumeral( \"MCMXC\" ) )\nprint( ToNumeral( \"MMVIII\" ) )\nprint( ToNumeral( \"MDCLXVI\" ) )"} {"title": "Roman numerals/Encode", "language": "Lua", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "romans = {\n{1000, \"M\"},\n{900, \"CM\"}, {500, \"D\"}, {400, \"CD\"}, {100, \"C\"},\n{90, \"XC\"}, {50, \"L\"}, {40, \"XL\"}, {10, \"X\"},\n{9, \"IX\"}, {5, \"V\"}, {4, \"IV\"}, {1, \"I\"} }\n\nk = io.read() + 0\nfor _, v in ipairs(romans) do --note that this is -not- ipairs.\n val, let = unpack(v)\n while k >= val do\n k = k - val\n\tio.write(let)\n end\nend\nprint()"} {"title": "Runge-Kutta method", "language": "Lua", "task": "Given the example Differential equation:\n:y'(t) = t \\times \\sqrt {y(t)}\nWith initial condition:\n:t_0 = 0 and y_0 = y(t_0) = y(0) = 1\nThis equation has an exact solution:\n:y(t) = \\tfrac{1}{16}(t^2 +4)^2\n\n\n;Task\nDemonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.\n* Solve the given differential equation over the range t = 0 \\ldots 10 with a step value of \\delta t=0.1 (101 total points, the first being given)\n* Print the calculated values of y at whole numbered t's (0.0, 1.0, \\ldots 10.0) along with error as compared to the exact solution.\n\n\n;Method summary\nStarting with a given y_n and t_n calculate:\n:\\delta y_1 = \\delta t\\times y'(t_n, y_n)\\quad\n:\\delta y_2 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_1)\n:\\delta y_3 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_2)\n:\\delta y_4 = \\delta t\\times y'(t_n + \\delta t , y_n + \\delta y_3)\\quad\nthen:\n:y_{n+1} = y_n + \\tfrac{1}{6} (\\delta y_1 + 2\\delta y_2 + 2\\delta y_3 + \\delta y_4)\n:t_{n+1} = t_n + \\delta t\\quad\n\n", "solution": "local df = function (t, y)\n-- derivative of function by value y at time t\n\treturn t*y^0.5\nend\n\nlocal dt = 0.1\nlocal y = 1\n\nprint (\"t\", \"realY\"..' ', \"y\", '\t\t'..\"error\")\nprint (\"---\", \"-------\"..' ', \"---------------\", '\t'..\"--------------------\")\n\nfor i = 0, 100 do\n\tlocal t = i*dt\n\tif t%1 == 0 then\n\t\tlocal realY = (t*t+4)^2/16\n\t\tprint (t, realY..' ', y, '\t'..realY-y)\n\tend\n\tlocal dy1 = df(t, y)\n\tlocal dy2 = df(t+dt/2, y+dt/2*dy1)\n\tlocal dy3 = df(t+dt/2, y+dt/2*dy2)\n\tlocal dy4 = df(t+dt, y+dt*dy3)\n\ty = y + dt*(dy1+2*dy2+2*dy3+dy4)/6\nend"} {"title": "Runtime evaluation", "language": "Lua", "task": "Demonstrate a language's ability for programs to execute code written in the language provided at runtime. \n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].\n\n", "solution": "f = loadstring(s) -- load a string as a function. Returns a function.\n\none = loadstring\"return 1\" -- one() returns 1\n\ntwo = loadstring\"return ...\" -- two() returns the arguments passed to it"} {"title": "Runtime evaluation", "language": "Lua 5.2", "task": "Demonstrate a language's ability for programs to execute code written in the language provided at runtime. \n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].\n\n", "solution": "> f = load(\"return 42\")\n> f()\n42\n> n = load(\"return 42\")()\n> n\n42"} {"title": "Runtime evaluation/In an environment", "language": "Lua", "task": "Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.\n\nDo so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": "code = loadstring\"return x^2\" --this doesn't really need to be input, does it?\nval1 = setfenv(code, {x = io.read() + 0})()\nval2 = setfenv(code, {x = io.read() + 0})()\nprint(val2 - val1)\n"} {"title": "Runtime evaluation/In an environment", "language": "Lua 5.2", "task": "Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.\n\nDo so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": "env = {}\nf = load(\"return x\", nil, nil, env)\nenv.x = tonumber(io.read()) -- user enters 2\na = f()\nenv.x = tonumber(io.read()) -- user enters 3\nb = f()\nprint(a + b) --> outputs 5"} {"title": "Sailors, coconuts and a monkey problem", "language": "Lua from C", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "function valid(n,nuts)\n local k = n\n local i = 0\n while k ~= 0 do\n if (nuts % n) ~= 1 then\n return false\n end\n k = k - 1\n nuts = nuts - 1 - math.floor(nuts / n)\n end\n return nuts ~= 0 and (nuts % n == 0)\nend\n\nfor n=2, 9 do\n local x = 0\n while not valid(n, x) do\n x = x + 1\n end\n print(n..\": \"..x)\nend"} {"title": "Same fringe", "language": "Lua", "task": "Write a routine that will compare the leaves (\"fringe\") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.\n\nAny solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.\n\nAny representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).\n\n", "solution": "local type, insert, remove = type, table.insert, table.remove\n\nNone = {} -- a unique object for a truncated branch (i.e. empty subtree)\nfunction isbranch(node) return type(node) == 'table' and #node == 2 end\nfunction left(node) return node[1] end\nfunction right(node) return node[2] end\n\nfunction fringeiter(tree)\n local agenda = {tree}\n local function push(item) insert(agenda, item) end\n local function pop() return remove(agenda) end\n return function()\n while #agenda > 0 do\n node = pop()\n if isbranch(node) then\n push(right(node))\n push(left(node))\n elseif node == None then\n -- continue\n else\n return node\n end\n end\n end\nend\n\nfunction same_fringe(atree, btree)\n local anext = fringeiter(atree or None)\n local bnext = fringeiter(btree or None)\n local pos = 0\n repeat\n local aitem, bitem = anext(), bnext()\n pos = pos + 1\n if aitem ~= bitem then\n return false, string.format(\"at position %d, %s ~= %s\", pos, aitem, bitem)\n end\n until not aitem\n return true\nend\n\nt1 = {1, {2, {3, {4, {5, None}}}}}\nt2 = {{1,2}, {{3, 4}, 5}}\nt3 = {{{1,2}, 3}, 4}\n\nfunction compare_fringe(label, ta, tb)\n local equal, nonmatch = same_fringe(ta, tb)\n io.write(label .. \": \")\n if equal then\n print(\"same fringe\")\n else\n print(nonmatch)\n end\nend\n\ncompare_fringe(\"(t1, t2)\", t1, t2)\ncompare_fringe(\"(t1, t3)\", t1, t3)\n"} {"title": "Self-describing numbers", "language": "Lua", "task": "{{task}}There are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example, '''2020''' is a four-digit self describing number:\n\n* position 0 has value 2 and there are two 0s in the number;\n* position 1 has value 0 and there are no 1s in the number;\n* position 2 has value 2 and there are two 2s;\n* position 3 has value 0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.\n\n\n;Task Description\n# Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n# As an optional stretch goal - generate and display the set of self-describing numbers.\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-referential sequence]]\n* [[Spelling of ordinal numbers]]\n\n", "solution": "function Is_self_describing( n )\n local s = tostring( n )\n\n local t = {}\n for i = 0, 9 do t[i] = 0 end\n\n for i = 1, s:len() do\n\tlocal idx = tonumber( s:sub(i,i) )\n t[idx] = t[idx] + 1\n end\n\n for i = 1, s:len() do\n if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end\n end\n\n return true\nend\n\nfor i = 1, 999999999 do\n print( Is_self_describing( i ) )\nend"} {"title": "Semordnilap", "language": "Lua", "task": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: ''lager'' and ''regal''\n \n;Task\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\n\n\n", "solution": "#!/usr/bin/env lua\n-- allow dictionary file and sample size to be specified on command line\nlocal dictfile = arg[1] or \"unixdict.txt\"\nlocal sample_size = arg[2] or 5;\n\n-- read dictionary\nlocal f = assert(io.open(dictfile, \"r\"))\nlocal dict = {}\nfor line in f:lines() do\n dict[line] = line:reverse()\nend\nf:close()\n\n-- find the semordnilaps\nlocal semordnilaps = {}\nfor fwd, rev in pairs(dict) do\n if dict[rev] and fwd < rev then\n table.insert(semordnilaps, {fwd,rev})\n end\nend\n\n-- print the report\nprint(\"There are \" .. #semordnilaps .. \" semordnilaps in \" .. dictfile .. \". Here are \" .. sample_size .. \":\")\n\nmath.randomseed( os.time() )\nfor i = 1, sample_size do\n local j\n repeat \n j = math.random(1,#semordnilaps)\n until semordnilaps[j]\n local f, r = unpack(semordnilaps[j])\n semordnilaps[j] = nil\n print(f .. \" -> \" .. r)\nend"} {"title": "Set consolidation", "language": "Lua", "task": "Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n;'''Example 1:'''\n:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n;'''Example 2:'''\n:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n;'''Example 3:'''\n:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n;'''Example 4:'''\n:The consolidation of the five sets:\n::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n:Is the two sets:\n::{A, C, B, D}, and {G, F, I, H, K}\n\n'''See also'''\n* Connected component (graph theory)\n* [[Range consolidation]]\n\n", "solution": "-- SUPPORT:\nfunction T(t) return setmetatable(t, {__index=table}) end\nfunction S(t) local s=T{} for k,v in ipairs(t) do s[v]=v end return s end\ntable.each = function(t,f,...) for _,v in pairs(t) do f(v,...) end end\ntable.copy = function(t) local s=T{} for k,v in pairs(t) do s[k]=v end return s end\ntable.keys = function(t) local s=T{} for k,_ in pairs(t) do s[#s+1]=k end return s end\ntable.intersects = function(t1,t2) for k,_ in pairs(t1) do if t2[k] then return true end end return false end\ntable.union = function(t1,t2) local s=t1:copy() for k,_ in pairs(t2) do s[k]=k end return s end\ntable.dump = function(t) print('{ '..table.concat(t, ', ')..' }') end\n\n-- TASK:\ntable.consolidate = function(t)\n for a = #t, 1, -1 do\n local seta = t[a]\n for b = #t, a+1, -1 do\n local setb = t[b]\n if setb and seta:intersects(setb) then\n t[a], t[b] = seta:union(setb), nil\n end\n end\n end\n return t\nend\n\n-- TESTING:\nexamples = {\n T{ S{\"A\",\"B\"}, S{\"C\",\"D\"} },\n T{ S{\"A\",\"B\"}, S{\"B\",\"D\"} },\n T{ S{\"A\",\"B\"}, S{\"C\",\"D\"}, S{\"D\",\"B\"} },\n T{ S{\"H\",\"I\",\"K\"}, S{\"A\",\"B\"}, S{\"C\",\"D\"}, S{\"D\",\"B\"}, S{\"F\",\"G\",\"H\"} },\n}\nfor i,example in ipairs(examples) do\n print(\"Given input sets:\")\n example:each(function(set) set:keys():dump() end)\n print(\"Consolidated output sets:\")\n example:consolidate():each(function(set) set:keys():dump() end)\n print(\"\")\nend"} {"title": "Set of real numbers", "language": "Lua", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "function createSet(low,high,rt)\n local l,h = tonumber(low), tonumber(high)\n if l and h then\n local t = {low=l, high=h}\n\n if type(rt) == \"string\" then\n if rt == \"open\" then\n t.contains = function(d) return low< d and d< high end\n elseif rt == \"closed\" then\n t.contains = function(d) return low<=d and d<=high end\n elseif rt == \"left\" then\n t.contains = function(d) return low< d and d<=high end\n elseif rt == \"right\" then\n t.contains = function(d) return low<=d and d< high end\n else\n error(\"Unknown range type: \"..rt)\n end\n elseif type(rt) == \"function\" then\n t.contains = rt\n else\n error(\"Unable to find a range type or predicate\")\n end\n\n t.union = function(o)\n local l2 = math.min(l, o.low)\n local h2 = math.min(h, o.high)\n local p = function(d) return t.contains(d) or o.contains(d) end\n return createSet(l2, h2, p)\n end\n\n t.intersect = function(o)\n local l2 = math.min(l, o.low)\n local h2 = math.min(h, o.high)\n local p = function(d) return t.contains(d) and o.contains(d) end\n return createSet(l2, h2, p)\n end\n\n t.subtract = function(o)\n local l2 = math.min(l, o.low)\n local h2 = math.min(h, o.high)\n local p = function(d) return t.contains(d) and not o.contains(d) end\n return createSet(l2, h2, p)\n end\n\n t.length = function()\n if h <= l then return 0.0 end\n local p = l\n local count = 0\n local interval = 0.00001\n repeat\n if t.contains(p) then count = count + 1 end\n p = p + interval\n until p>=high\n return count * interval\n end\n\n t.empty = function()\n if l == h then\n return not t.contains(low)\n end\n return t.length() == 0.0\n end\n\n return t\n else\n error(\"Either '\"..low..\"' or '\"..high..\"' is not a number\")\n end\nend\n\nlocal a = createSet(0.0, 1.0, \"left\")\nlocal b = createSet(0.0, 2.0, \"right\")\nlocal c = createSet(1.0, 2.0, \"left\")\nlocal d = createSet(0.0, 3.0, \"right\")\nlocal e = createSet(0.0, 1.0, \"open\")\nlocal f = createSet(0.0, 1.0, \"closed\")\nlocal g = createSet(0.0, 0.0, \"closed\")\n\nfor i=0,2 do\n print(\"(0, 1] union [0, 2) contains \"..i..\" is \"..tostring(a.union(b).contains(i)))\n print(\"[0, 2) intersect (1, 2] contains \"..i..\" is \"..tostring(b.intersect(c).contains(i)))\n print(\"[0, 3) - (0, 1) contains \"..i..\" is \"..tostring(d.subtract(e).contains(i)))\n print(\"[0, 3) - [0, 1] contains \"..i..\" is \"..tostring(d.subtract(f).contains(i)))\n print()\nend\n\nprint(\"[0, 0] is empty is \"..tostring(g.empty()))\nprint()\n\nlocal aa = createSet(\n 0.0, 10.0,\n function(x) return (0.0 0.5 end\n)\nlocal bb = createSet(\n 0.0, 10.0,\n function(x) return (0.0 0.5 end\n)\nlocal cc = aa.subtract(bb)\nprint(\"Approx length of A - B is \"..cc.length())"} {"title": "Shoelace formula for polygonal area", "language": "Lua", "task": "Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:\n\nabs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -\n (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])\n ) / 2\n(Where abs returns the absolute value)\n\n;Task:\nWrite a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:\n (3,4), (5,11), (12,8), (9,5), and (5,6) \n\n\nShow the answer here, on this page.\n\n", "solution": "function shoeArea(ps)\n local function ssum(acc, p1, p2, ...)\n if not p2 or not p1 then\n return math.abs(0.5 * acc)\n else\n return ssum(acc + p1[1]*p2[2]-p1[2]*p2[1], p2, ...)\n end\n end\n return ssum(0, ps[#ps], table.unpack(ps))\nend\n\nlocal p = {{3,4}, {5,11}, {12,8}, {9,5}, {5,6}}\nprint(shoeArea(p))-- 30 "} {"title": "Show ASCII table", "language": "Lua from Go", "task": "Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.\n\n\n\n", "solution": "-- map of character values to desired representation\nlocal chars = setmetatable({[32] = \"Spc\", [127] = \"Del\"}, {__index = function(_, k) return string.char(k) end})\n\n-- row iterator\nlocal function iter(s,a) \n a = (a or s) + 16\n if a <= 127 then return a, chars[a] end \nend\n\n-- print loop\nfor i = 0, 15 do \n for j, repr in iter, i+16 do \n io.write((\"%3d : %3s \"):format(j, repr))\n end\n io.write\"\\n\"\nend"} {"title": "Sierpinski pentagon", "language": "Lua", "task": "Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.\n\n\n;See also\n* Sierpinski pentagon\n\n", "solution": "Bitmap.chaosgame = function(self, n, r, niters)\n local w, h, vertices = self.width, self.height, {}\n for i = 1, n do\n vertices[i] = {\n x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n),\n y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n)\n }\n end\n local x, y = w/2, h/2\n for i = 1, niters do\n local v = math.random(n)\n x = x + r * (vertices[v].x - x)\n y = y + r * (vertices[v].y - y)\n self:set(x,y,0xFFFFFFFF)\n end\nend\n\nlocal bitmap = Bitmap(128, 128)\nbitmap:chaosgame(5, 1/((1+math.sqrt(5))/2), 1e6)\nbitmap:render({[0x000000]='..', [0xFFFFFFFF]='\u2588\u2588'})"} {"title": "Smith numbers", "language": "Lua", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as ''joke'' numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: [Smith number].\n* from MathWorld: [Smith number]. \n* from OEIS A6753: [OEIS sequence A6753].\n* from OEIS A104170: [Number of Smith numbers below 10^n]. \n* from The Prime pages: [Smith numbers].\n\n", "solution": "-- Returns a boolean indicating whether n is prime\nfunction isPrime (n)\n if n < 2 then return false end\n if n < 4 then return true end\n if n % 2 == 0 then return false end\n for d = 3, math.sqrt(n), 2 do\n if n % d == 0 then return false end\n end\n return true\nend\n\n-- Returns a table of the prime factors of n\nfunction primeFactors (n)\n local pfacs, divisor = {}, 1\n if n < 1 then return pfacs end\n while not isPrime(n) do\n while not isPrime(divisor) do divisor = divisor + 1 end\n while n % divisor == 0 do\n n = n / divisor\n table.insert(pfacs, divisor)\n end\n divisor = divisor + 1\n if n == 1 then return pfacs end\n end\n table.insert(pfacs, n)\n return pfacs\nend\n\n-- Returns the sum of the digits of n\nfunction sumDigits (n)\n local sum, nStr = 0, tostring(n)\n for digit = 1, nStr:len() do\n sum = sum + tonumber(nStr:sub(digit, digit))\n end\n return sum\nend\n\n-- Returns a boolean indicating whether n is a Smith number\nfunction isSmith (n)\n if isPrime(n) then return false end\n local sumFacs = 0\n for _, v in ipairs(primeFactors(n)) do\n sumFacs = sumFacs + sumDigits(v)\n end\n return sumFacs == sumDigits(n)\nend\n\n-- Main procedure\nfor n = 1, 10000 do\n if isSmith(n) then io.write(n .. \"\\t\") end\nend"} {"title": "Solve a Holy Knight's tour", "language": "Lua", "task": "Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "local p1, p1W = \".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..\", 8\nlocal p2, p2W = \".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....\", 13\nlocal puzzle, movesCnt, wid = {}, 0, 0\nlocal moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 }, \n { -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } }\n\nfunction isValid( x, y )\n return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 )\nend\nfunction solve( x, y, s )\n if s > movesCnt then return true end\n local test, a, b\n for i = 1, #moves do\n test = false\n a = x + moves[i][1]; b = y + moves[i][2]\n if isValid( a, b ) then\n puzzle[a + b * wid - wid] = s\n if solve( a, b, s + 1 ) then return true end\n puzzle[a + b * wid - wid] = 0\n end\n end\n return false\nend\nfunction printSolution()\n local lp\n for j = 1, wid do\n for i = 1, wid do\n lp = puzzle[i + j * wid - wid]\n if lp == -1 then io.write( \" \" )\n else io.write( string.format( \" %.2d\", lp ) )\n end\n end\n print()\n end\n print( \"\\n\" )\nend\nlocal sx, sy\nfunction fill( pz, w )\n puzzle = {}; wid = w; movesCnt = #pz\n local lp\n for i = 1, #pz do\n lp = pz:sub( i, i )\n if lp == \"x\" then\n table.insert( puzzle, 0 )\n elseif lp == \".\" then\n table.insert( puzzle, -1 ); movesCnt = movesCnt - 1\n else \n table.insert( puzzle, 1 )\n sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid )\n end\n end\nend\n-- [[ entry point ]] --\nprint( \"\\n\\n\" ); fill( p1, p1W );\nif solve( sx, sy, 2 ) then printSolution() end\nprint( \"\\n\\n\" ); fill( p2, p2W );\nif solve( sx, sy, 2 ) then printSolution() end\n"} {"title": "Split a character string based on change of character", "language": "Lua", "task": "Split a (character) string into comma (plus a blank) delimited\nstrings based on a change of character (left to right).\n\nShow the output here (use the 1st example below).\n\n\nBlanks should be treated as any other character (except\nthey are problematic to display clearly). The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "function charSplit (inStr)\n local outStr, nextChar = inStr:sub(1, 1)\n for pos = 2, #inStr do\n nextChar = inStr:sub(pos, pos)\n if nextChar ~= outStr:sub(#outStr, #outStr) then\n outStr = outStr .. \", \"\n end\n outStr = outStr .. nextChar\n end\n return outStr\nend\n\nprint(charSplit(\"gHHH5YY++///\\\\\"))"} {"title": "Square-free integers", "language": "Lua", "task": "Write a function to test if a number is ''square-free''.\n\n\nA ''square-free'' is an integer which is divisible by no perfect square other\nthan '''1''' (unity).\n\nFor this task, only positive square-free numbers will be used.\n\n\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n::* '''1''' ---> '''145''' (inclusive)\n::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)\n\n\n(One trillion = 1,000,000,000,000)\n\n\nShow here (on this page) the count of square-free integers from:\n::* '''1''' ---> one hundred (inclusive)\n::* '''1''' ---> one thousand (inclusive)\n::* '''1''' ---> ten thousand (inclusive)\n::* '''1''' ---> one hundred thousand (inclusive)\n::* '''1''' ---> one million (inclusive)\n\n\n;See also:\n:* the Wikipedia entry: square-free integer\n\n", "solution": "function squareFree (n)\n for root = 2, math.sqrt(n) do\n if n % (root * root) == 0 then return false end\n end\n return true\nend\n\nfunction run (lo, hi, showValues)\n io.write(\"From \" .. lo .. \" to \" .. hi)\n io.write(showValues and \":\\n\" or \" = \")\n local count = 0\n for i = lo, hi do\n if squareFree(i) then\n if showValues then\n io.write(i, \"\\t\")\n else\n count = count + 1\n end\n end\n end\n print(showValues and \"\\n\" or count)\nend\n\nlocal testCases = {\n {1, 145, true},\n {1000000000000, 1000000000145, true},\n {1, 100},\n {1, 1000},\n {1, 10000},\n {1, 100000},\n {1, 1000000}\n}\nfor _, example in pairs(testCases) do run(unpack(example)) end"} {"title": "Square but not cube", "language": "Lua", "task": "Show the first '''30''' positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.\n\n", "solution": "function nthroot (x, n)\n local r = 1\n for i = 1, 16 do\n r = (((n - 1) * r) + x / (r ^ (n - 1))) / n\n end\n return r\nend\n\nlocal i, count, sq, cbrt = 0, 0\nwhile count < 30 do\n i = i + 1\n sq = i * i\n -- The next line should say nthroot(sq, 3), right? But this works. Maths, eh?\n cbrt = nthroot(i, 3)\n if cbrt == math.floor(cbrt) then\n print(sq .. \" is square and cube\")\n else\n print(sq)\n count = count + 1\n end\nend"} {"title": "Stair-climbing puzzle", "language": "Lua", "task": "From Chung-Chieh Shan (LtU):\n\nYour stair-climbing robot has a very simple low-level API: the \"step\" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The \"step\" function detects what happens and returns a boolean flag: true on success, false on failure. \n\nWrite a function \"step_up\" that climbs one step up [from the initial position] (by repeating \"step\" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make \"step_up\"? Can you avoid using variables (even immutable ones) and numbers?\n\nHere's a pseudo-code of a simple recursive solution without using variables:\n\nfunc step_up()\n{\n if not step() {\n step_up();\n step_up();\n }\n}\n\nInductive proof that step_up() steps up one step, if it terminates:\n* Base case (if the step() call returns true): it stepped up one step. QED\n* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED\n\n\nThe second (tail) recursion above can be turned into an iteration, as follows:\n\nfunc step_up()\n{\n while not step() {\n step_up();\n }\n}\n\n", "solution": "function step_up()\n while not step() do step_up() end\nend\n"} {"title": "Statistics/Normal distribution", "language": "Lua", "task": "The derive normally distributed random numbers from a uniform generator.\n\n\n;The task:\n# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.\n# Mention any native language support for the generation of normally distributed random numbers.\n\n\n;Reference:\n* You may refer to code in [[Statistics/Basic]] if available.\n\n", "solution": "function gaussian (mean, variance)\n return math.sqrt(-2 * variance * math.log(math.random())) *\n math.cos(2 * math.pi * math.random()) + mean\nend\n \nfunction mean (t)\n local sum = 0\n for k, v in pairs(t) do\n sum = sum + v\n end\n return sum / #t\nend\n \nfunction std (t)\n local squares, avg = 0, mean(t)\n for k, v in pairs(t) do\n squares = squares + ((avg - v) ^ 2)\n end\n local variance = squares / #t\n return math.sqrt(variance)\nend\n \nfunction showHistogram (t) \n local lo = math.ceil(math.min(unpack(t)))\n local hi = math.floor(math.max(unpack(t)))\n local hist, barScale = {}, 200\n for i = lo, hi do\n hist[i] = 0\n for k, v in pairs(t) do\n if math.ceil(v - 0.5) == i then\n hist[i] = hist[i] + 1\n end\n end\n io.write(i .. \"\\t\" .. string.rep('=', hist[i] / #t * barScale))\n print(\" \" .. hist[i])\n end\nend\n \nmath.randomseed(os.time())\nlocal t, average, variance = {}, 50, 10\nfor i = 1, 1000 do\n table.insert(t, gaussian(average, variance))\nend \nprint(\"Mean:\", mean(t) .. \", expected \" .. average)\nprint(\"StdDev:\", std(t) .. \", expected \" .. math.sqrt(variance) .. \"\\n\")\nshowHistogram(t)"} {"title": "Stern-Brocot sequence", "language": "Lua", "task": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].\n\n# The first and second members of the sequence are both 1:\n#* 1, 1\n# Start by considering the second member of the sequence\n# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n#* 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* --- Expanding another loop we get: ---\n#*\n# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n#* 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1, 3, 2\n# Consider the next member of the series, (the fourth member i.e. 1)\n\n\n;The task is to:\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\n\n;Related tasks:\n:* [[Fusc sequence]].\n:* [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "-- Task 1\nfunction sternBrocot (n)\n local sbList, pos, c = {1, 1}, 2\n repeat\n c = sbList[pos]\n table.insert(sbList, c + sbList[pos - 1])\n table.insert(sbList, c)\n pos = pos + 1\n until #sbList >= n\n return sbList\nend\n\n-- Return index in table 't' of first value matching 'v'\nfunction findFirst (t, v)\n for key, value in pairs(t) do\n if v then\n if value == v then return key end\n else\n if value ~= 0 then return key end\n end\n end\n return nil\nend\n\n-- Return greatest common divisor of 'x' and 'y'\nfunction gcd (x, y)\n if y == 0 then\n return math.abs(x)\n else\n return gcd(y, x % y)\n end\nend\n\n-- Check GCD of adjacent values in 't' up to 1000 is always 1\nfunction task5 (t)\n for pos = 1, 1000 do\n if gcd(t[pos], t[pos + 1]) ~= 1 then return \"FAIL\" end\n end\n return \"PASS\"\nend\n\n-- Main procedure\nlocal sb = sternBrocot(10000)\nio.write(\"Task 2: \")\nfor n = 1, 15 do io.write(sb[n] .. \" \") end\nprint(\"\\n\\nTask 3:\")\nfor i = 1, 10 do print(\"\\t\" .. i, findFirst(sb, i)) end\nprint(\"\\nTask 4: \" .. findFirst(sb, 100)) \nprint(\"\\nTask 5: \" .. task5(sb))"} {"title": "Strip control codes and extended characters from a string", "language": "Lua", "task": "Strip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* a string with control codes stripped (but extended characters not stripped)\n:* a string with control codes and extended characters stripped\n\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127. \n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\n\n", "solution": "function Strip_Control_Codes( str )\n local s = \"\"\n for i in str:gmatch( \"%C+\" ) do\n \ts = s .. i\n end\n return s\nend\n\nfunction Strip_Control_and_Extended_Codes( str )\n local s = \"\"\n for i = 1, str:len() do\n\tif str:byte(i) >= 32 and str:byte(i) <= 126 then\n \t s = s .. str:sub(i,i)\n\tend\n end\n return s\nend\n\nq = \"\"\nfor i = 0, 255 do\n\tq = q .. string.char(i)\nend\n\nprint( Strip_Control_Codes(q) )\nprint( Strip_Control_and_Extended_Codes(q) )"} {"title": "Subleq", "language": "Lua", "task": "One-Instruction Set Computer (OISC). \n\nIt is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. \n\n;Task\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:\n::::* simple numeric values \n::::* memory addresses \n::::* characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine. \n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.\n:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.\n:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.\n:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.\n:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.\n:# If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).\n\nFor purposes of this task, show the output of your solution when fed the below \"Hello, world!\" program. \n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\nstart:\n 0f 11 ff subleq (zero), (message), -1\n 11 ff ff subleq (message), -1, -1 ; output character at message\n 10 01 ff subleq (neg1), (start+1), -1\n 10 03 ff subleq (neg1), (start+3), -1\n 0f 0f 00 subleq (zero), (zero), start\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n\n", "solution": "function subleq (prog)\n local mem, p, A, B, C = {}, 0\n for word in prog:gmatch(\"%S+\") do\n mem[p] = tonumber(word)\n p = p + 1\n end\n p = 0\n repeat\n A, B, C = mem[p], mem[p + 1], mem[p + 2]\n if A == -1 then\n mem[B] = io.read()\n elseif B == -1 then\n io.write(string.char(mem[A]))\n else\n mem[B] = mem[B] - mem[A]\n if mem[B] <= 0 then p = C end\n end\n p = p + 3\n until not mem[mem[p]]\nend\n\nsubleq(\"15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\")"} {"title": "Substring/Top and tail", "language": "Lua", "task": "The task is to demonstrate how to remove the first and last characters from a string. \n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. \n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. \n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n", "solution": "print (string.sub(\"knights\",2)) -- remove the first character\nprint (string.sub(\"knights\",1,-2)) -- remove the last character\nprint (string.sub(\"knights\",2,-2)) -- remove the first and last characters"} {"title": "Sum and product puzzle", "language": "Lua from C++", "task": "* Wikipedia: Sum and Product Puzzle\n\n", "solution": "function print_count(t)\n local cnt = 0\n for k,v in pairs(t) do\n cnt = cnt + 1\n end\n print(cnt .. ' candidates')\nend\n\nfunction make_pair(a,b)\n local t = {}\n table.insert(t, a) -- 1\n table.insert(t, b) -- 2\n return t\nend\n\nfunction setup()\n local candidates = {}\n for x = 2, 98 do\n for y = x + 1, 98 do\n if x + y <= 100 then\n local p = make_pair(x, y)\n table.insert(candidates, p)\n end\n end\n end\n return candidates\nend\n\nfunction remove_by_sum(candidates, sum)\n for k,v in pairs(candidates) do\n local s = v[1] + v[2]\n if s == sum then\n table.remove(candidates, k)\n end\n end\nend\n\nfunction remove_by_prod(candidates, prod)\n for k,v in pairs(candidates) do\n local p = v[1] * v[2]\n if p == prod then\n table.remove(candidates, k)\n end\n end\nend\n\nfunction statement1(candidates)\n local unique = {}\n for k,v in pairs(candidates) do\n local prod = v[1] * v[2]\n if unique[prod] ~= nil then\n unique[prod] = unique[prod] + 1\n else\n unique[prod] = 1\n end\n end\n\n local done\n repeat\n done = true\n for k,v in pairs(candidates) do\n local prod = v[1] * v[2]\n if unique[prod] == 1 then\n local sum = v[1] + v[2]\n remove_by_sum(candidates, sum)\n done = false\n break\n end\n end\n until done\nend\n\nfunction statement2(candidates)\n local unique = {}\n for k,v in pairs(candidates) do\n local prod = v[1] * v[2]\n if unique[prod] ~= nil then\n unique[prod] = unique[prod] + 1\n else\n unique[prod] = 1\n end\n end\n\n local done\n repeat\n done = true\n for k,v in pairs(candidates) do\n local prod = v[1] * v[2]\n if unique[prod] > 1 then\n remove_by_prod(candidates, prod)\n done = false\n break\n end\n end\n until done\nend\n\nfunction statement3(candidates)\n local unique = {}\n for k,v in pairs(candidates) do\n local sum = v[1] + v[2]\n if unique[sum] ~= nil then\n unique[sum] = unique[sum] + 1\n else\n unique[sum] = 1\n end\n end\n\n local done\n repeat\n done = true\n for k,v in pairs(candidates) do\n local sum = v[1] + v[2]\n if unique[sum] > 1 then\n remove_by_sum(candidates, sum)\n done = false\n break\n end\n end\n until done\nend\n\nfunction main()\n local candidates = setup()\n print_count(candidates)\n\n statement1(candidates)\n print_count(candidates)\n\n statement2(candidates)\n print_count(candidates)\n\n statement3(candidates)\n print_count(candidates)\n\n for k,v in pairs(candidates) do\n local sum = v[1] + v[2]\n local prod = v[1] * v[2]\n print(\"a=\" .. v[1] .. \", b=\" .. v[2] .. \"; S=\" .. sum .. \", P=\" .. prod)\n end\nend\n\nmain()"} {"title": "Sum digits of an integer", "language": "Lua", "task": "Take a Natural Number in a given base and return the sum of its digits:\n:* '''1'''10 sums to '''1'''\n:* '''1234'''10 sums to '''10'''\n:* '''fe'''16 sums to '''29'''\n:* '''f0e'''16 sums to '''29'''\n\n", "solution": "function sum_digits(n, base)\n sum = 0\n while n > 0.5 do\n m = math.floor(n / base)\n digit = n - m * base\n sum = sum + digit\n n = m\n end\n return sum\nend\n\nprint(sum_digits(1, 10))\nprint(sum_digits(1234, 10))\nprint(sum_digits(0xfe, 16))\nprint(sum_digits(0xf0e, 16))"} {"title": "Sum multiples of 3 and 5", "language": "Lua from Tcl", "task": "The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. \n\nShow output for ''n'' = 1000.\n\nThis is is the same as Project Euler problem 1.\n\n'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.\n\n", "solution": "function tri (n) return n * (n + 1) / 2 end\n\nfunction sum35 (n)\n\tn = n - 1\n\treturn\t(\t3 * tri(math.floor(n / 3)) + \n\t\t\t5 * tri(math.floor(n / 5)) - \n\t\t\t15 * tri(math.floor(n / 15))\n\t\t)\nend\n\nprint(sum35(1000))\nprint(sum35(1e+20))\n"} {"title": "Sum to 100", "language": "Lua from C", "task": "Find solutions to the ''sum to one hundred'' puzzle.\n\n\nAdd (insert) the mathematical\noperators '''+''' or '''-''' (plus\nor minus) before any of the digits in the\ndecimal numeric string '''123456789''' such that the\nresulting mathematical expression adds up to a\nparticular sum (in this iconic case, '''100''').\n\n\nExample: \n 123 + 4 - 5 + 67 - 89 = 100 \n\nShow all output here.\n\n\n:* Show all solutions that sum to '''100''' \n:* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++)\n:* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task\n:* Show the ten highest numbers that can be expressed using the rules for this task (extra credit)\n\n++ (where ''infinity'' would be a relatively small 123,456,789)\n\n\nAn example of a sum that can't be expressed (within the rules of this task) is: '''5074'''\n(which, of course, isn't the lowest positive sum that can't be expressed).\n\n", "solution": "local expressionsLength = 0\nfunction compareExpressionBySum(a, b)\n return a.sum - b.sum\nend\n\nlocal countSumsLength = 0\nfunction compareCountSumsByCount(a, b)\n return a.counts - b.counts\nend\n\nfunction evaluate(code)\n local value = 0\n local number = 0\n local power = 1\n for k=9,1,-1 do\n number = power*k + number\n local mod = code % 3\n if mod == 0 then\n -- ADD\n value = value + number\n number = 0\n power = 1\n elseif mod == 1 then\n -- SUB\n value = value - number\n number = 0\n power = 1\n elseif mod == 2 then\n -- JOIN\n power = 10 * power\n else\n print(\"This should not happen.\")\n end\n code = math.floor(code / 3)\n end\n return value\nend\n\nfunction printCode(code)\n local a = 19683\n local b = 6561\n local s = \"\"\n for k=1,9 do\n local temp = math.floor((code % a) / b)\n if temp == 0 then\n -- ADD\n if k>1 then\n s = s .. '+'\n end\n elseif temp == 1 then\n -- SUB\n s = s .. '-'\n end\n a = b\n b = math.floor(b/3)\n s = s .. tostring(k)\n end\n print(\"\\t\"..evaluate(code)..\" = \"..s)\nend\n\n-- Main\nlocal nexpr = 13122\n\nprint(\"Show all solutions that sum to 100\")\nfor i=0,nexpr-1 do\n if evaluate(i) == 100 then\n printCode(i)\n end\nend\nprint()\n\nprint(\"Show the sum that has the maximum number of solutions\")\nlocal nbest = -1\nfor i=0,nexpr-1 do\n local test = evaluate(i)\n if test>0 then\n local ntest = 0\n for j=0,nexpr-1 do\n if evaluate(j) == test then\n ntest = ntest + 1\n end\n if ntest > nbest then\n best = test\n nbest = ntest\n end\n end\n end\nend\nprint(best..\" has \"..nbest..\" solutions\\n\")\n\nprint(\"Show the lowest positive number that can't be expressed\")\nlocal code = -1\nfor i=0,123456789 do\n for j=0,nexpr-1 do\n if evaluate(j) == i then\n code = j\n break\n end\n end\n if evaluate(code) ~= i then\n code = i\n break\n end\nend\nprint(code..\"\\n\")\n\nprint(\"Show the ten highest numbers that can be expressed\")\nlocal limit = 123456789 + 1\nfor i=1,10 do\n local best=0\n for j=0,nexpr-1 do\n local test = evaluate(j)\n if (testbest) then\n best = test\n end\n end\n for j=0,nexpr-1 do\n if evaluate(j) == best then\n printCode(j)\n end\n end\n limit = best\nend"} {"title": "Summarize and say sequence", "language": "Lua", "task": "There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:\n 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...\nThe terms generated grow in length geometrically and never converge.\n\nAnother way to generate a self-referential sequence is to summarize the previous term.\n\nCount how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.\n 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... \nSort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.\n\nDepending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)\n\n\n;Task:\nFind all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. \n\nSeed Value(s): 9009 9090 9900\n\nIterations: 21 \n\nSequence: (same for all three seeds except for first element)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-describing numbers]]\n* [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "-- Return the next term in the self-referential sequence\nfunction findNext (nStr)\n local nTab, outStr, pos, count = {}, \"\", 1, 1\n for i = 1, #nStr do nTab[i] = nStr:sub(i, i) end\n table.sort(nTab, function (a, b) return a > b end)\n while pos <= #nTab do\n if nTab[pos] == nTab[pos + 1] then\n count = count + 1\n else\n outStr = outStr .. count .. nTab[pos]\n count = 1\n end\n pos = pos + 1\n end\n return outStr\nend\n\n-- Return boolean indicating whether table t contains string s\nfunction contains (t, s)\n for k, v in pairs(t) do\n if v == s then return true end\n end\n return false\nend\n\n-- Return the sequence generated by the given seed term\nfunction buildSeq (term)\n local sequence = {}\n repeat\n table.insert(sequence, term)\n if not nextTerm[term] then nextTerm[term] = findNext(term) end\n term = nextTerm[term]\n until contains(sequence, term)\n return sequence\nend\n\n-- Main procedure\nnextTerm = {}\nlocal highest, seq, hiSeq = 0\nfor i = 1, 10^6 do\n seq = buildSeq(tostring(i))\n if #seq > highest then\n highest = #seq\n hiSeq = {seq}\n elseif #seq == highest then\n table.insert(hiSeq, seq)\n end\nend\nio.write(\"Seed values: \")\nfor _, v in pairs(hiSeq) do io.write(v[1] .. \" \") end\nprint(\"\\n\\nIterations: \" .. highest)\nprint(\"\\nSample sequence:\")\nfor _, v in pairs(hiSeq[1]) do print(v) end"} {"title": "Superellipse", "language": "Lua", "task": "A superellipse is a geometric figure defined as the set of all points (x, y) with \n\n\n::: \\left|\\frac{x}{a}\\right|^n\\! + \\left|\\frac{y}{b}\\right|^n\\! = 1,\n\nwhere ''n'', ''a'', and ''b'' are positive numbers.\n\n\n;Task\nDraw a superellipse with n = 2.5, and a = b = 200\n\n", "solution": "local abs,cos,floor,pi,pow,sin = math.abs,math.cos,math.floor,math.pi,math.pow,math.sin\nlocal bitmap = {\n init = function(self, w, h, value)\n self.w, self.h, self.pixels = w, h, {}\n for y=1,h do self.pixels[y]={} end\n self:clear(value)\n end,\n clear = function(self, value)\n for y=1,self.h do\n for x=1,self.w do\n self.pixels[y][x] = value or \" \"\n end\n end\n end,\n set = function(self, x, y, value)\n x,y = floor(x+0.5),floor(y+0.5)\n if x>0 and y>0 and x<=self.w and y<=self.h then\n self.pixels[y][x] = value or \"#\"\n end\n end,\n superellipse = function(self, ox, oy, n, a, b, c)\n local function sgn(n) return n>=0 and 1 or -1 end\n for t = 0, 1, 0.002 do\n local theta = t * 2 * pi\n local x = ox + a * pow(abs(cos(theta)), 2/n) * sgn(cos(theta))\n local y = oy + b * pow(abs(sin(theta)), 2/n) * sgn(sin(theta))\n self:set(x, y, c)\n end\n end,\n render = function(self)\n for y=1,self.h do\n print(table.concat(self.pixels[y]))\n end\n end,\n}\n\nbitmap:init(80, 60, \"..\")\nbitmap:superellipse(40, 30, 2.5, 38, 28, \"[]\")\nbitmap:render()"} {"title": "Tau function", "language": "Lua from Java", "task": "Given a positive integer, count the number of its positive divisors.\n\n\n;Task\nShow the result for the first '''100''' positive integers.\n\n\n;Related task\n* [[Tau number]]\n\n", "solution": "function divisorCount(n)\n local total = 1\n -- Deal with powers of 2 first\n while (n & 1) == 0 do\n total = total + 1\n n = math.floor(n / 2)\n end\n -- Odd prime factors up tot eh square root\n local p = 3\n while p * p <= n do\n local count = 1\n while n % p == 0 do\n count = count + 1\n n = n / p\n end\n total = total * count\n p = p + 2\n end\n -- If n > 1 then it's prime\n if n > 1 then\n total = total * 2\n end\n return total\nend\n\nlimit = 100\nprint(\"Count of divisors for the first \" .. limit .. \" positive integers:\")\nfor n=1,limit do\n io.write(string.format(\"%3d\", divisorCount(n)))\n if n % 20 == 0 then\n print()\n end\nend"} {"title": "Temperature conversion", "language": "Lua", "task": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: \nRankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n \n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\n\n;Task\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. \n\n\n;Example:\n\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n\n", "solution": "function convert_temp(k)\n local c = k - 273.15\n local r = k * 1.8\n local f = r - 459.67\n return k, c, r, f\nend\n\nprint(string.format([[\nKelvin: %.2f K\nCelcius: %.2f \u00b0C\nRankine: %.2f \u00b0R\nFahrenheit: %.2f \u00b0F\n]],convert_temp(21.0)))"} {"title": "Terminal control/Coloured text", "language": "Lua", "task": "Display a word in various colours on the terminal. \n\nThe system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.\n\n\nOptionally demonstrate:\n* How the system should determine if the terminal supports colour\n* Setting of the background colour\n* How to cause blinking or flashing (if supported by the terminal)\n\n", "solution": "print(\"Normal \\027[1mBold\\027[0m \\027[4mUnderline\\027[0m \\027[7mInverse\\027[0m\")\ncolors = { 30,31,32,33,34,35,36,37,90,91,92,93,94,95,96,97 }\nfor _,bg in ipairs(colors) do\n for _,fg in ipairs(colors) do\n io.write(\"\\027[\"..fg..\";\"..(bg+10)..\"mX\")\n end\n print(\"\\027[0m\") -- be nice, reset\nend"} {"title": "Test integerness", "language": "Lua", "task": "{| class=\"wikitable\"\n|-\n! colspan=2 | Input\n! colspan=2 | Output\n! rowspan=2 | Comment\n|-\n! Type\n! Value\n! exact\n! tolerance = 0.00001\n|-\n| rowspan=3 | decimal\n| 25.000000\n| colspan=2 | true\n| \n|-\n| 24.999999\n| false\n| true\n| \n|-\n| 25.000100\n| colspan=2 | false\n| \n|-\n| rowspan=4 | floating-point\n| -2.1e120\n| colspan=2 | true\n| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.\n|-\n| -5e-2\n| colspan=2 | false\n| \n|-\n| NaN\n| colspan=2 | false\n| \n|-\n| Inf\n| colspan=2 | false\n| This one is debatable. If your code considers it an integer, that's okay too.\n|-\n| rowspan=2 | complex\n| 5.0+0.0i\n| colspan=2 | true\n| \n|-\n| 5-5i\n| colspan=2 | false\n| \n|}\n\n(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)\n\n\n", "solution": "function isInt (x) return type(x) == \"number\" and x == math.floor(x) end\n\nprint(\"Value\\tInteger?\")\nprint(\"=====\\t========\")\nlocal testCases = {2, 0, -1, 3.5, \"String!\", true}\nfor _, input in pairs(testCases) do print(input, isInt(input)) end"} {"title": "Textonyms", "language": "Lua", "task": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n\n;Task:\nWrite a program that finds textonyms in a list of words such as \n[[Textonyms/wordlist]] or \nunixdict.txt.\n\nThe task should produce a report:\n\n There are #{0} words in #{1} which can be represented by the digit key mapping.\n They require #{2} digit combinations to represent them.\n #{3} digit combinations represent Textonyms.\n\nWhere:\n #{0} is the number of words in the list which can be represented by the digit key mapping.\n #{1} is the URL of the wordlist being used.\n #{2} is the number of digit combinations required to represent the words in #{0}.\n #{3} is the number of #{2} which represent more than one word.\n\nAt your discretion show a couple of examples of your solution displaying Textonyms. \n\nE.G.:\n\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n\n;Extra credit:\nUse a word list and keypad mapping other than English.\n\n\n\n", "solution": "-- Global variables\nhttp = require(\"socket.http\")\nkeys = {\"VOICEMAIL\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"}\ndictFile = \"http://www.puzzlers.org/pub/wordlists/unixdict.txt\"\n\n-- Return the sequence of keys required to type a given word\nfunction keySequence (str)\n local sequence, noMatch, letter = \"\"\n for pos = 1, #str do\n letter = str:sub(pos, pos)\n for i, chars in pairs(keys) do\n noMatch = true\n if chars:match(letter) then\n sequence = sequence .. tostring(i)\n noMatch = false\n break\n end\n end\n if noMatch then return nil end\n end\n return tonumber(sequence)\nend\n\n-- Generate table of words grouped by key sequence\nfunction textonyms (dict)\n local combTable, keySeq = {}\n for word in dict:gmatch(\"%S+\") do\n keySeq = keySequence(word)\n if keySeq then\n if combTable[keySeq] then\n table.insert(combTable[keySeq], word)\n else\n combTable[keySeq] = {word}\n end\n end\n end\n return combTable\nend\n\n-- Analyse sequence table and print details\nfunction showReport (keySeqs)\n local wordCount, seqCount, tCount = 0, 0, 0\n for seq, wordList in pairs(keySeqs) do\n wordCount = wordCount + #wordList\n seqCount = seqCount + 1\n if #wordList > 1 then tCount = tCount + 1 end\n end\n print(\"There are \" .. wordCount .. \" words in \" .. dictFile)\n print(\"which can be represented by the digit key mapping.\")\n print(\"They require \" .. seqCount .. \" digit combinations to represent them.\")\n print(tCount .. \" digit combinations represent Textonyms.\")\nend\n\n-- Main procedure\nshowReport(textonyms(http.request(dictFile)))"} {"title": "The Name Game", "language": "Lua from C#", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "function printVerse(name)\n local sb = string.lower(name)\n sb = sb:gsub(\"^%l\", string.upper)\n local x = sb\n local x0 = x:sub(1,1)\n\n local y\n if x0 == 'A' or x0 == 'E' or x0 == 'I' or x0 == 'O' or x0 == 'U' then\n y = string.lower(x)\n else\n y = x:sub(2)\n end\n\n local b = \"b\" .. y\n local f = \"f\" .. y\n local m = \"m\" .. y\n\n if x0 == 'B' then\n b = y\n elseif x0 == 'F' then\n f = y\n elseif x0 == 'M' then\n m = y\n end\n\n print(x .. \", \" .. x .. \", bo-\" .. b)\n print(\"Banana-fana fo-\" .. f)\n print(\"Fee-fi-mo-\" .. m)\n print(x .. \"!\")\n print()\n\n return nil\nend\n\nlocal nameList = { \"Gary\", \"Earl\", \"Billy\", \"Felix\", \"Mary\", \"Steve\" }\nfor _,name in pairs(nameList) do\n printVerse(name)\nend"} {"title": "The Twelve Days of Christmas", "language": "Lua", "task": "Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found here. \n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n", "solution": "local days = {\n 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',\n 'tenth', 'eleventh', 'twelfth',\n}\n\nlocal gifts = {\n \"A partridge in a pear tree\",\n \"Two turtle doves\",\n \"Three french hens\",\n \"Four calling birds\",\n \"Five golden rings\",\n \"Six geese a-laying\",\n \"Seven swans a-swimming\",\n \"Eight maids a-milking\",\n \"Nine ladies dancing\",\n \"Ten lords a-leaping\",\n \"Eleven pipers piping\",\n \"Twelve drummers drumming\",\n}\n\nlocal verses = {}\n\nfor i = 1, 12 do\n local lines = {}\n lines[1] = \"On the \" .. days[i] .. \" day of Christmas, my true love gave to me\"\n \n local j = i\n local k = 2\n repeat\n lines[k] = gifts[j]\n k = k + 1\n j = j - 1\n until j == 0\n \n verses[i] = table.concat(lines, '\\n')\nend\n\nprint(table.concat(verses, '\\n\\n'))\n"} {"title": "Thue-Morse", "language": "Lua", "task": "Create a Thue-Morse sequence.\n\n\n;See also\n* YouTube entry: The Fairest Sharing Sequence Ever\n* YouTube entry: Math and OCD - My story with the Thue-Morse sequence\n* Task: [[Fairshare between two and more]]\n\n", "solution": "ThueMorse = {sequence = \"0\"}\n\nfunction ThueMorse:show ()\n print(self.sequence)\nend\n\nfunction ThueMorse:addBlock ()\n local newBlock = \"\"\n for bit = 1, self.sequence:len() do\n if self.sequence:sub(bit, bit) == \"1\" then\n newBlock = newBlock .. \"0\"\n else\n newBlock = newBlock .. \"1\"\n end\n end\n self.sequence = self.sequence .. newBlock\nend\n\nfor i = 1, 5 do\n ThueMorse:show()\n ThueMorse:addBlock()\nend"} {"title": "Top rank per group", "language": "Lua", "task": "Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "solution": "--Employee Class\nlocal EmployeeMethods = {\n \n}\nlocal EmployeeMetamethods = {\n __index=EmployeeMethods,\n __tostring=function(self)\n return (\"%s %s %s %s\"):format(self.Name,self.EmployeeId,self.Salary,self.DepartmentName)\n end,\n __metatable=\"Locked\",\n}\nlocal EmployeeBase = {}\n\nEmployeeBase.new = function(Name,EmployeeId,Salary,DepartmentName)\n return setmetatable({\n Name=Name,\n EmployeeId=EmployeeId,\n Salary=Salary,\n DepartmentName=DepartmentName,\n },EmployeeMetamethods)\nend\n\n--Department Class\nlocal DepartmentMethods = {\n NewEmployee=function(self,Employee)\n table.insert(self.__Employees,Employee)\n end,\n CalculateHighestSalaries=function(self,Amount)\n local Highest = {}\n local EL = #self.__Employees\n table.sort(self.__Employees,function(a,b)\n return a.Salary > b.Salary\n end)\n for i=1,Amount do\n if i>EL then\n break \n end\n table.insert(Highest,self.__Employees[i])\n end\n return Highest\n end,\n}\nlocal DepartmentMetamethods = {\n __index=DepartmentMethods,\n __tostring=function(self)\n return (\"Department %s\"):format(self.Name)\n end,\n __metatable=\"Locked\",\n}\nlocal DepartmentBase = {\n __Departments={},\n}\n\nDepartmentBase.new = function(Name)\n local Department = DepartmentBase.__Departments[Name]\n if Department then return Department end\n Department = setmetatable({\n __Employees={},\n Name=Name,\n },DepartmentMetamethods)\n DepartmentBase.__Departments[Name] = Department\n return Department\nend\n\n--Main Program\n\nlocal Employees = {\n EmployeeBase.new(\"Tyler Bennett\",\"E10297\",32000,\"D101\"),\n EmployeeBase.new(\"John Rappl\",\"E21437\",47000,\"D050\"),\n EmployeeBase.new(\"George Woltman\",\"E00127\",53500,\"D101\"),\n EmployeeBase.new(\"Adam Smith\",\"E63535\",18000,\"D202\"),\n EmployeeBase.new(\"Claire Buckman\",\"E39876\",27800,\"D202\"),\n EmployeeBase.new(\"David McClellan\",\"E04242\",41500,\"D101\"),\n EmployeeBase.new(\"Rich Holcomb\",\"E01234\",49500,\"D202\"),\n EmployeeBase.new(\"Nathan Adams\",\"E41298\",21900,\"D050\"),\n EmployeeBase.new(\"Richard Potter\",\"E43128\",15900,\"D101\"),\n EmployeeBase.new(\"David Motsinger\",\"E27002\",19250,\"D202\"),\n EmployeeBase.new(\"Tim Sampair\",\"E03033\",27000,\"D101\"),\n EmployeeBase.new(\"Kim Arlich\",\"E10001\",57000,\"D190\"),\n EmployeeBase.new(\"Timothy Grove\",\"E16398\",29900,\"D190\"),\n}\n\nfor _,Employee in next,Employees do\n local Department = DepartmentBase.new(Employee.DepartmentName)\n Department:NewEmployee(Employee)\nend\n\nfor _,Department in next,DepartmentBase.__Departments do\n local Highest = Department:CalculateHighestSalaries(2)\n print(Department)\n for _,Employee in next,Highest do\n print(\"\\t\"..tostring(Employee))\n end\nend"} {"title": "Topswops", "language": "Lua", "task": "Topswops is a card game created by John Conway in the 1970's.\n\n\nAssume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. \n\nA round is composed of reversing the first m cards where m is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. \n\n\nFor our example the swaps produce:\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n\nFor a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.\n\n\nFor a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.\n\n\n;Task:\nThe task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.\n\n\n;Note:\nTopswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.\n\n\n;Related tasks:\n* [[Number reversal game]]\n* [[Sorting algorithms/Pancake sort]]\n\n", "solution": "-- Return an iterator to produce every permutation of list\nfunction permute (list)\n local function perm (list, n)\n if n == 0 then coroutine.yield(list) end\n for i = 1, n do\n list[i], list[n] = list[n], list[i]\n perm(list, n - 1)\n list[i], list[n] = list[n], list[i]\n end\n end\n return coroutine.wrap(function() perm(list, #list) end)\nend\n \n-- Perform one topswop round on table t\nfunction swap (t)\n local new, limit = {}, t[1]\n for i = 1, #t do\n if i <= limit then\n new[i] = t[limit - i + 1]\n else\n new[i] = t[i]\n end\n end\n return new\nend\n \n-- Find the most swaps needed for any starting permutation of n cards\nfunction topswops (n)\n local numTab, highest, count = {}, 0\n for i = 1, n do numTab[i] = i end\n for numList in permute(numTab) do\n count = 0\n while numList[1] ~= 1 do\n numList = swap(numList)\n count = count + 1\n end\n if count > highest then highest = count end\n end\n return highest\nend\n \n-- Main procedure\nfor i = 1, 10 do print(i, topswops(i)) end"} {"title": "Trabb Pardo\u2013Knuth algorithm", "language": "Lua", "task": "The TPK algorithm is an early example of a programming chrestomathy. \nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. \nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n '''ask''' for 11 numbers to be read into a sequence ''S''\n '''reverse''' sequence ''S''\n '''for each''' ''item'' '''in''' sequence ''S''\n ''result'' ''':=''' '''call''' a function to do an ''operation''\n '''if''' ''result'' overflows\n '''alert''' user\n '''else'''\n '''print''' ''result''\n\nThe task is to implement the algorithm:\n# Use the function: f(x) = |x|^{0.5} + 5x^3\n# The overflow condition is an answer of greater than 400.\n# The 'user alert' should not stop processing of other items of the sequence.\n# Print a prompt before accepting '''eleven''', textual, numeric inputs.\n# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.\n# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).\n\n", "solution": "function f (x) return math.abs(x)^0.5 + 5*x^3 end\n\nfunction reverse (t)\n local rev = {}\n for i, v in ipairs(t) do rev[#t - (i-1)] = v end\n return rev\nend\n\nlocal sequence, result = {}\nprint(\"Enter 11 numbers...\")\nfor n = 1, 11 do\n io.write(n .. \": \")\n sequence[n] = io.read()\nend\nfor _, x in ipairs(reverse(sequence)) do\n result = f(x)\n if result > 400 then print(\"Overflow!\") else print(result) end\nend"} {"title": "Truncate a file", "language": "Lua", "task": "Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).\n\n\nTruncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be \"binary safe\", leaving the contents of the untruncated part of the file unchanged.\n\nIf the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. \n\nOn some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. \n\nThis task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.\n\n", "solution": "function truncate (filename, length)\n local inFile = io.open(filename, 'r')\n if not inFile then\n error(\"Specified filename does not exist\")\n end\n local wholeFile = inFile:read(\"*all\")\n inFile:close()\n if length >= wholeFile:len() then\n error(\"Provided length is not less than current file length\")\n end\n local outFile = io.open(filename, 'w')\n outFile:write(wholeFile:sub(1, length))\n outFile:close()\nend"} {"title": "URL decoding", "language": "Lua", "task": "This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* The encoded string \"http%3A%2F%2Ffoo%20bar%2F\" should be reverted to the unencoded form \"http://foo bar/\".\n\n* The encoded string \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" should revert to the unencoded form \"google.com/search?q=`Abdu'l-Baha\".\n\n* The encoded string \"%25%32%35\" should revert to the unencoded form \"%25\" and '''not''' \"%\".\n\n", "solution": "function decodeChar(hex)\n\treturn string.char(tonumber(hex,16))\nend\n\nfunction decodeString(str)\n\tlocal output, t = string.gsub(str,\"%%(%x%x)\",decodeChar)\n\treturn output\nend\n\n-- will print \"http://foo bar/\"\nprint(decodeString(\"http%3A%2F%2Ffoo%20bar%2F\"))"} {"title": "URL encoding", "language": "Lua", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "function encodeChar(chr)\n\treturn string.format(\"%%%X\",string.byte(chr))\nend\n\nfunction encodeString(str)\n\tlocal output, t = string.gsub(str,\"[^%w]\",encodeChar)\n\treturn output\nend\n\n-- will print \"http%3A%2F%2Ffoo%20bar%2F\"\nprint(encodeString(\"http://foo bar/\"))"} {"title": "UTF-8 encode and decode", "language": "Lua 5.3", "task": "As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.\n\nThe goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.\n\nDemonstrate the functionality of your encoder and decoder on the following five characters:\n\n\nCharacter Name Unicode UTF-8 encoding (hex)\n---------------------------------------------------------------------------------\nA LATIN CAPITAL LETTER A U+0041 41\no LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\nZh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\nEUR EURO SIGN U+20AC E2 82 AC\n MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "-- Accept an integer representing a codepoint.\n-- Return the values of the individual octets.\nfunction encode (codepoint)\n local codepoint_str = utf8.char(codepoint)\n local result = {}\n\n for i = 1, #codepoint_str do\n result[#result + 1] = string.unpack(\"B\", codepoint_str, i)\n end\n\n return table.unpack(result)\nend\n\n-- Accept a variable number of octets.\n-- Return the corresponding Unicode character.\nfunction decode (...)\n local len = select(\"#\", ...) -- the number of octets\n local fmt = string.rep(\"B\", len)\n\n return string.pack(fmt, ...)\nend\n\n-- Run the given test cases.\nfunction test_encode_decode ()\n -- \"A\", \"\u00f6\", \"\u0416\", \"\u20ac\", \"\ud834\udd1e\"\n local tests = {tonumber(\"41\", 16), tonumber(\"f6\", 16), tonumber(\"416\", 16),\n tonumber(\"20ac\", 16), tonumber(\"1d11e\", 16)}\n\n for i, test in ipairs(tests) do\n print(\"Char: \", test)\n print(\"Encoding: \", encode(test))\n print(\"Decoding: \", decode(encode(test)))\n end\nend\n"} {"title": "Unbias a random generator", "language": "Lua", "task": "Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.\n\n;Task details:\n* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.\n* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.\n* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).\n\n\nThe actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.\n\nThis task is an implementation of Von Neumann debiasing, first described in a 1951 paper.\n\n", "solution": "local function randN(n)\n return function()\n if math.random() < 1/n then return 1 else return 0 end\n end\nend\n\nlocal function unbiased(n)\n local biased = randN (n)\n return function()\n local a, b = biased(), biased()\n while a==b do\n a, b = biased(), biased()\n end\n return a\n end\nend\n\nlocal function demonstrate (samples)\n for n = 3, 6 do\n biased = randN(n)\n unbias = unbiased(n)\n local bcounts = {[0]=0,[1]=0}\n local ucounts = {[0]=0,[1]=0}\n for i=1, samples do\n local bnum = biased()\n local unum = unbias()\n bcounts[bnum] = bcounts[bnum]+1\n ucounts[unum] = ucounts[unum]+1\n end\n print(string.format(\"N = %d\",n),\n \"# 0\", \"# 1\",\n \"% 0\", \"% 1\")\n print(\"biased\", bcounts[0], bcounts[1],\n bcounts[0] / samples * 100,\n bcounts[1] / samples * 100)\n print(\"unbias\", ucounts[0], ucounts[1],\n ucounts[0] / samples * 100,\n ucounts[1] / samples * 100)\n end\nend\n\ndemonstrate(100000)\n"} {"title": "Unicode strings", "language": "Lua", "task": "As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend. \n\nIt is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. \n\nHow well prepared is your programming language for Unicode? \n\n\n;Task:\nDiscuss and demonstrate its unicode awareness and capabilities. \n\n\nSome suggested topics:\n:* How easy is it to present Unicode strings in source code? \n:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n:* How well can the language communicate with the rest of the world? \n:* Is it good at input/output with Unicode?\n:* Is it convenient to manipulate Unicode strings in the language?\n:* How broad/deep does the language support Unicode? \n:* What encodings (e.g. UTF-8, UTF-16, etc) can be used? \n:* Does it support normalization?\n\n\n;Note:\nThis task is a bit unusual in that it encourages general discussion rather than clever coding.\n\n\n;See also:\n* [[Unicode variable names]]\n* [[Terminal control/Display an extended character]]\n\n", "solution": "By default, Lua doesn't support Unicode. Most string methods will work properly on the ASCII range only like [[String case#Lua|case transformation]]. But there is a [https://www.lua.org/manual/5.4/manual.html#6.5 utf8] module that add some very basic support with a very limited number of functions. For example, this module brings a new [[String length#Lua|length method]] adapted for UTF-8. But there is no method to transform the case of Unicode string correctly. So globally the Unicode support is very limited and not by default.\n\n"} {"title": "Universal Turing machine", "language": "Lua", "task": "One of the foundational mathematical constructs behind computer science \nis the universal Turing Machine. \n\n\n(Alan Turing introduced the idea of such a machine in 1936-1937.)\n\nIndeed one way to definitively prove that a language \nis turing-complete \nis to implement a universal Turing machine in it.\n\n\n;Task:\nSimulate such a machine capable \nof taking the definition of any other Turing machine and executing it. \n \nOf course, you will not have an infinite tape, \nbut you should emulate this as much as is possible. \n\nThe three permissible actions on the tape are \"left\", \"right\" and \"stay\".\n\nTo test your universal Turing machine (and prove your programming language \nis Turing complete!), you should execute the following two Turing machines \nbased on the following definitions.\n\n\n'''Simple incrementer'''\n* '''States:''' q0, qf\n* '''Initial state:''' q0\n* '''Terminating states:''' qf\n* '''Permissible symbols:''' B, 1\n* '''Blank symbol:''' B\n* '''Rules:'''\n** (q0, 1, 1, right, q0)\n** (q0, B, 1, stay, qf)\n\n\nThe input for this machine should be a tape of 1 1 1\n\n\n'''Three-state busy beaver'''\n* '''States:''' a, b, c, halt\n* '''Initial state:''' a\n* '''Terminating states:''' halt\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (a, 0, 1, right, b)\n** (a, 1, 1, left, c)\n** (b, 0, 1, left, a)\n** (b, 1, 1, right, b)\n** (c, 0, 1, left, b)\n** (c, 1, 1, stay, halt)\n\n\nThe input for this machine should be an empty tape.\n\n\n'''Bonus:'''\n\n'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''\n* '''States:''' A, B, C, D, E, H\n* '''Initial state:''' A\n* '''Terminating states:''' H\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (A, 0, 1, right, B)\n** (A, 1, 1, left, C)\n** (B, 0, 1, right, C)\n** (B, 1, 1, right, B)\n** (C, 0, 1, right, D)\n** (C, 1, 0, left, E)\n** (D, 0, 1, left, A)\n** (D, 1, 1, left, D)\n** (E, 0, 1, stay, H)\n** (E, 1, 0, left, A)\n\n\nThe input for this machine should be an empty tape.\n\nThis machine runs for more than 47 millions steps.\n\n", "solution": "-- Machine definitions\nlocal incrementer = {\n name = \"Simple incrementer\",\n initState = \"q0\",\n endState = \"qf\",\n blank = \"B\",\n rules = {\n {\"q0\", \"1\", \"1\", \"right\", \"q0\"},\n {\"q0\", \"B\", \"1\", \"stay\", \"qf\"}\n }\n}\n\nlocal threeStateBB = {\n name = \"Three-state busy beaver\",\n initState = \"a\",\n endState = \"halt\",\n blank = \"0\",\n rules = {\n {\"a\", \"0\", \"1\", \"right\", \"b\"},\n {\"a\", \"1\", \"1\", \"left\", \"c\"},\n {\"b\", \"0\", \"1\", \"left\", \"a\"},\n {\"b\", \"1\", \"1\", \"right\", \"b\"},\n {\"c\", \"0\", \"1\", \"left\", \"b\"},\n {\"c\", \"1\", \"1\", \"stay\", \"halt\"}\n }\n}\n\nlocal fiveStateBB = {\n name = \"Five-state busy beaver\",\n initState = \"A\",\n endState = \"H\",\n blank = \"0\",\n rules = {\n {\"A\", \"0\", \"1\", \"right\", \"B\"},\n {\"A\", \"1\", \"1\", \"left\", \"C\"},\n {\"B\", \"0\", \"1\", \"right\", \"C\"},\n {\"B\", \"1\", \"1\", \"right\", \"B\"},\n {\"C\", \"0\", \"1\", \"right\", \"D\"},\n {\"C\", \"1\", \"0\", \"left\", \"E\"},\n {\"D\", \"0\", \"1\", \"left\", \"A\"},\n {\"D\", \"1\", \"1\", \"left\", \"D\"},\n {\"E\", \"0\", \"1\", \"stay\", \"H\"},\n {\"E\", \"1\", \"0\", \"left\", \"A\"}\n }\n}\n\n-- Display a representation of the tape and machine state on the screen\nfunction show (state, headPos, tape)\n local leftEdge = 1\n while tape[leftEdge - 1] do leftEdge = leftEdge - 1 end\n io.write(\" \" .. state .. \"\\t| \")\n for pos = leftEdge, #tape do\n if pos == headPos then io.write(\"[\" .. tape[pos] .. \"] \") else io.write(\" \" .. tape[pos] .. \" \") end\n end\n print()\nend\n\n-- Simulate a turing machine\nfunction UTM (machine, tape, countOnly)\n local state, headPos, counter = machine.initState, 1, 0\n print(\"\\n\\n\" .. machine.name)\n print(string.rep(\"=\", #machine.name) .. \"\\n\")\n if not countOnly then print(\" State\", \"| Tape [head]\\n---------------------\") end\n repeat\n if not tape[headPos] then tape[headPos] = machine.blank end\n if not countOnly then show(state, headPos, tape) end\n for _, rule in ipairs(machine.rules) do\n if rule[1] == state and rule[2] == tape[headPos] then\n tape[headPos] = rule[3]\n if rule[4] == \"left\" then headPos = headPos - 1 end\n if rule[4] == \"right\" then headPos = headPos + 1 end\n state = rule[5]\n break\n end\n end\n counter = counter + 1\n until state == machine.endState\n if countOnly then print(\"Steps taken: \" .. counter) else show(state, headPos, tape) end\nend\n\n-- Main procedure\nUTM(incrementer, {\"1\", \"1\", \"1\"})\nUTM(threeStateBB, {})\nUTM(fiveStateBB, {}, \"countOnly\")"} {"title": "Validate International Securities Identification Number", "language": "Lua", "task": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. \n\n\n;Task:\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, ''and'' the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n;Details:\nThe format of an ISIN is as follows:\n\n\n\n+------------- a 2-character ISO country code (A-Z)\n| +----------- a 9-character security code (A-Z, 0-9)\n| | +-- a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.\n# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)\n\n\n;Test cases:\n:::: {| class=\"wikitable\"\n! ISIN\n! Validity\n! Comment\n|-\n| US0378331005 || valid || \n|-\n| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.\n|-\n| U50378331005 || not valid || The substitution typo is caught by the format constraint.\n|-\n| US03378331005 || not valid || The duplication typo is caught by the format constraint.\n|-\n| AU0000XVGZA3 || valid || \n|-\n| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.\n|-\n| FR0000988040 || valid || \n|}\n\n(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* Interactive online ISIN validator\n* Wikipedia article: International Securities Identification Number\n\n", "solution": "function luhn (n)\n local revStr, s1, s2, digit, mod = n:reverse(), 0, 0\n for pos = 1, #revStr do\n digit = tonumber(revStr:sub(pos, pos))\n if pos % 2 == 1 then\n s1 = s1 + digit\n else\n digit = digit * 2\n if digit > 9 then\n mod = digit % 10\n digit = mod + ((digit - mod) / 10)\n end\n s2 = s2 + digit\n end\n end\n return (s1 + s2) % 10 == 0\nend\n\nfunction checkISIN (inStr)\n if #inStr ~= 12 then return false end\n local numStr = \"\"\n for pos = 1, #inStr do\n numStr = numStr .. tonumber(inStr:sub(pos, pos), 36)\n end\n return luhn(numStr)\nend\n\nlocal testCases = {\n \"US0378331005\",\n \"US0373831005\",\n \"US0373831005\",\n \"US03378331005\",\n \"AU0000XVGZA3\",\n \"AU0000VXGZA3\",\n \"FR0000988040\"\n}\nfor _, ISIN in pairs(testCases) do print(ISIN, checkISIN(ISIN)) end"} {"title": "Van Eck sequence", "language": "Lua", "task": "The sequence is generated by following this pseudo-code:\n\nA: The first term is zero.\n Repeatedly apply:\n If the last term is *new* to the sequence so far then:\nB: The next term is zero.\n Otherwise:\nC: The next term is how far back this last term occured previously.\n\n\n\n;Example:\nUsing A:\n:0\nUsing B:\n:0 0\nUsing C:\n:0 0 1\nUsing B:\n:0 0 1 0\nUsing C: (zero last occurred two steps back - before the one)\n:0 0 1 0 2\nUsing B:\n:0 0 1 0 2 0\nUsing C: (two last occurred two steps back - before the zero)\n:0 0 1 0 2 0 2 2\nUsing C: (two last occurred one step back)\n:0 0 1 0 2 0 2 2 1\nUsing C: (one last appeared six steps back)\n:0 0 1 0 2 0 2 2 1 6\n...\n\n\n;Task:\n# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.\n# Use it to display here, on this page:\n:# The first ten terms of the sequence.\n:# Terms 991 - to - 1000 of the sequence.\n\n\n;References:\n* Don't Know (the Van Eck Sequence) - Numberphile video.\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "-- Return a table of the first n values of the Van Eck sequence\nfunction vanEck (n)\n local seq, foundAt = {0}\n while #seq < n do\n foundAt = nil\n for pos = #seq - 1, 1, -1 do\n if seq[pos] == seq[#seq] then\n foundAt = pos\n break\n end\n end\n if foundAt then\n table.insert(seq, #seq - foundAt)\n else\n table.insert(seq, 0)\n end\n end\n return seq\nend\n\n-- Show the set of values in table t from key numbers lo to hi\nfunction showValues (t, lo, hi)\n for i = lo, hi do\n io.write(t[i] .. \" \")\n end\n print()\nend\n\n-- Main procedure\nlocal sequence = vanEck(1000)\nshowValues(sequence, 1, 10)\nshowValues(sequence, 991, 1000)"} {"title": "Van der Corput sequence", "language": "Lua", "task": "When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.\n\nSo in the following table:\n 0.\n 1.\n 10.\n 11.\n ...\nthe binary number \"10\" is 1 \\times 2^1 + 0 \\times 2^0.\n\nYou can also have binary digits to the right of the \"point\", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. \nThe weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.\n\nIf you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.\n\n .0\n .1\n .01\n .11\n ...\n\nThe third member of the sequence, binary 0.01, is therefore 0 \\times 2^{-1} + 1 \\times 2^{-2} or 1/4.\n\n Monte Carlo simulations. \nThis sequence is also a superset of the numbers representable by the \"fraction\" field of an old IEEE floating point standard. In that standard, the \"fraction\" field represented the fractional part of a binary number beginning with \"1.\" e.g. 1.101001101.\n\n'''Hint'''\n\nA ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:\n>>> def base10change(n, base):\n\tdigits = []\n\twhile n:\n\t\tn,remainder = divmod(n, base)\n\t\tdigits.insert(0, remainder)\n\treturn digits\n\n>>> base10change(11, 2)\n[1, 0, 1, 1]\nthe above showing that 11 in decimal is 1\\times 2^3 + 0\\times 2^2 + 1\\times 2^1 + 1\\times 2^0.\nReflected this would become .1101 or 1\\times 2^{-1} + 1\\times 2^{-2} + 0\\times 2^{-3} + 1\\times 2^{-4}\n\n\n;Task description:\n* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.\n* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).\n\n* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.\n\n\n\n;See also:\n* The Basic Low Discrepancy Sequences\n* [[Non-decimal radices/Convert]]\n* Van der Corput sequence\n\n", "solution": "function vdc(n, base)\n local digits = {}\n while n ~= 0 do\n local m = math.floor(n / base)\n table.insert(digits, n - m * base)\n n = m\n end\n m = 0\n for p, d in pairs(digits) do\n m = m + math.pow(base, -p) * d\n end\n return m\nend"} {"title": "Vector products", "language": "Lua", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). \n\nIf you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.\n\nGiven the vectors:\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \nthen the following common vector products are defined:\n* '''The dot product''' (a scalar quantity)\n:::: A * B = a1b1 + a2b2 + a3b3 \n* '''The cross product''' (a vector quantity)\n:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) \n* '''The scalar triple product''' (a scalar quantity)\n:::: A * (B x C) \n* '''The vector triple product''' (a vector quantity)\n:::: A x (B x C) \n\n\n;Task:\nGiven the three vectors: \n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n# Create a named function/subroutine/method to compute the dot product of two vectors.\n# Create a function to compute the cross product of two vectors.\n# Optionally create a function to compute the scalar triple product of three vectors.\n# Optionally create a function to compute the vector triple product of three vectors.\n# Compute and display: a * b\n# Compute and display: a x b\n# Compute and display: a * (b x c), the scalar triple product.\n# Compute and display: a x (b x c), the vector triple product.\n\n\n;References:\n* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.\n* Wikipedia dot product. \n* Wikipedia cross product. \n* Wikipedia triple product.\n\n\n;Related tasks:\n* [[Dot product]]\n* [[Quaternion type]]\n\n", "solution": "Vector = {} \nfunction Vector.new( _x, _y, _z )\n return { x=_x, y=_y, z=_z }\nend\n\nfunction Vector.dot( A, B )\n return A.x*B.x + A.y*B.y + A.z*B.z\nend\n\nfunction Vector.cross( A, B )\n return { x = A.y*B.z - A.z*B.y,\n y = A.z*B.x - A.x*B.z,\n z = A.x*B.y - A.y*B.x }\nend\n\nfunction Vector.scalar_triple( A, B, C )\n return Vector.dot( A, Vector.cross( B, C ) )\nend\n\nfunction Vector.vector_triple( A, B, C )\n return Vector.cross( A, Vector.cross( B, C ) )\nend\n\n\nA = Vector.new( 3, 4, 5 )\nB = Vector.new( 4, 3, 5 )\nC = Vector.new( -5, -12, -13 )\n\nprint( Vector.dot( A, B ) )\n\nr = Vector.cross(A, B )\nprint( r.x, r.y, r.z )\n\nprint( Vector.scalar_triple( A, B, C ) )\n\nr = Vector.vector_triple( A, B, C )\nprint( r.x, r.y, r.z )"} {"title": "Video display modes", "language": "Lua", "task": "The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.\n", "solution": "print(\"\\33[?3h\") -- 132-column text\nprint(\"\\33[?3l\") -- 80-column text"} {"title": "Visualize a tree", "language": "Lua from C#", "task": "A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n\n", "solution": "function makeTree(v,ac)\n if type(ac) == \"table\" then\n return {value=v,children=ac}\n else\n return {value=v}\n end\nend\n\nfunction printTree(t,last,prefix)\n if last == nil then\n printTree(t, false, '')\n else\n local current = ''\n local next = ''\n\n if last then\n current = prefix .. '\\\\-' .. t.value\n next = prefix .. ' '\n else\n current = prefix .. '|-' .. t.value\n next = prefix .. '| '\n end\n\n print(current:sub(3))\n if t.children ~= nil then\n for k,v in pairs(t.children) do\n printTree(v, k == #t.children, next)\n end\n end\n end\nend\n\nprintTree(\n makeTree('A', {\n makeTree('B0', {\n makeTree('C1'),\n makeTree('C2', {\n makeTree('D', {\n makeTree('E1'),\n makeTree('E2'),\n makeTree('E3')\n })\n }),\n makeTree('C3', {\n makeTree('F1'),\n makeTree('F2'),\n makeTree('F3', {makeTree('G')}),\n makeTree('F4', {\n makeTree('H1'),\n makeTree('H2')\n })\n })\n }),\n makeTree('B1',{\n makeTree('K1'),\n makeTree('K2', {\n makeTree('L1', {makeTree('M')}),\n makeTree('L2'),\n makeTree('L3')\n }),\n makeTree('K3')\n })\n })\n)"} {"title": "Vogel's approximation method", "language": "Lua from Kotlin", "task": "Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them \"A\", \"B\", \"C\", \"D\", and \"E\". They estimate that:\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called \"W\", \"X\", \"Y\", and \"Z\".\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.\n\nRepeat until all supply and demand is met:\n\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\nFinally calculate the cost of your solution. In the example given it is PS3100:\n\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n\nThe optimal solution determined by GLPK is PS3100:\n\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n\n;Cf.\n* Transportation problem\n\n", "solution": "function initArray(n,v)\n local tbl = {}\n for i=1,n do\n table.insert(tbl,v)\n end\n return tbl\nend\n\nfunction initArray2(m,n,v)\n local tbl = {}\n for i=1,m do\n table.insert(tbl,initArray(n,v))\n end\n return tbl\nend\n\nsupply = {50, 60, 50, 50}\ndemand = {30, 20, 70, 30, 60}\ncosts = {\n {16, 16, 13, 22, 17},\n {14, 14, 13, 19, 15},\n {19, 19, 20, 23, 50},\n {50, 12, 50, 15, 11}\n}\n\nnRows = table.getn(supply)\nnCols = table.getn(demand)\n\nrowDone = initArray(nRows, false)\ncolDone = initArray(nCols, false)\nresults = initArray2(nRows, nCols, 0)\n\nfunction diff(j,le,isRow)\n local min1 = 100000000\n local min2 = min1\n local minP = -1\n for i=1,le do\n local done = false\n if isRow then\n done = colDone[i]\n else\n done = rowDone[i]\n end\n if not done then\n local c = 0\n if isRow then\n c = costs[j][i]\n else\n c = costs[i][j]\n end\n if c < min1 then\n min2 = min1\n min1 = c\n minP = i\n elseif c < min2 then\n min2 = c\n end\n end\n end\n return {min2 - min1, min1, minP}\nend\n\nfunction maxPenalty(len1,len2,isRow)\n local md = -100000000\n local pc = -1\n local pm = -1\n local mc = -1\n\n for i=1,len1 do\n local done = false\n if isRow then\n done = rowDone[i]\n else\n done = colDone[i]\n end\n if not done then\n local res = diff(i, len2, isRow)\n if res[1] > md then\n md = res[1] -- max diff\n pm = i -- pos of max diff\n mc = res[2] -- min cost\n pc = res[3] -- pos of min cost\n end\n end\n end\n\n if isRow then\n return {pm, pc, mc, md}\n else\n return {pc, pm, mc, md}\n end\nend\n\nfunction nextCell()\n local res1 = maxPenalty(nRows, nCols, true)\n local res2 = maxPenalty(nCols, nRows, false)\n if res1[4] == res2[4] then\n if res1[3] < res2[3] then\n return res1\n else\n return res2\n end\n else\n if res1[4] > res2[4] then\n return res2\n else\n return res1\n end\n end\nend\n\nfunction main()\n local supplyLeft = 0\n for i,v in pairs(supply) do\n supplyLeft = supplyLeft + v\n end\n local totalCost = 0\n while supplyLeft > 0 do\n local cell = nextCell()\n local r = cell[1]\n local c = cell[2]\n local q = math.min(demand[c], supply[r])\n demand[c] = demand[c] - q\n if demand[c] == 0 then\n colDone[c] = true\n end\n supply[r] = supply[r] - q\n if supply[r] == 0 then\n rowDone[r] = true\n end\n results[r][c] = q\n supplyLeft = supplyLeft - q\n totalCost = totalCost + q * costs[r][c]\n end\n\n print(\" A B C D E\")\n local labels = {'W','X','Y','Z'}\n for i,r in pairs(results) do\n io.write(labels[i])\n for j,c in pairs(r) do\n io.write(string.format(\" %2d\", c))\n end\n print()\n end\n print(\"Total Cost = \" .. totalCost)\nend\n\nmain()"} {"title": "Voronoi diagram", "language": "Lua from Python", "task": "A Voronoi diagram is a diagram consisting of a number of sites. \n\nEach Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.\n\n\n;Task:\nDemonstrate how to generate and display a Voroni diagram. \n\n\nSee algo [[K-means++ clustering]].\n\n", "solution": "function love.load( )\n\tlove.math.setRandomSeed( os.time( ) ) --set the random seed\n\tkeys = { } --an empty table where we will store key presses\n\tnumber_cells = 50 --the number of cells we want in our diagram\n\t--draw the voronoi diagram to a canvas\n\tvoronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )\nend\n\nfunction hypot( x, y )\n\treturn math.sqrt( x*x + y*y )\nend\n\nfunction generateVoronoi( width, height, num_cells )\n\tcanvas = love.graphics.newCanvas( width, height )\n\tlocal imgx = canvas:getWidth( )\n\tlocal imgy = canvas:getHeight( )\n\tlocal nx = { }\n\tlocal ny = { }\n\tlocal nr = { }\n\tlocal ng = { }\n\tlocal nb = { }\n\tfor a = 1, num_cells do\n\ttable.insert( nx, love.math.random( 0, imgx ) )\n\ttable.insert( ny, love.math.random( 0, imgy ) )\n\ttable.insert( nr, love.math.random( 0, 1 ) )\n\ttable.insert( ng, love.math.random( 0, 1 ) )\n\ttable.insert( nb, love.math.random( 0, 1 ) )\n\tend\n\tlove.graphics.setColor( { 1, 1, 1 } )\n\tlove.graphics.setCanvas( canvas )\n\tfor y = 1, imgy do\n\tfor x = 1, imgx do\n\t\t\tdmin = hypot( imgx-1, imgy-1 )\n\t\tj = -1\n\t\tfor i = 1, num_cells do\n\t\td = hypot( nx[i]-x, ny[i]-y )\n\t\tif d < dmin then\n\t \t dmin = d\n\t\t\tj = i\n\t\tend\n\t\tend\n\t\tlove.graphics.setColor( { nr[j], ng[j], nb[j] } )\n\t\tlove.graphics.points( x, y )\n\tend\n\tend\n\t--reset color\n\tlove.graphics.setColor( { 1, 1, 1 } )\n\t--draw points\n\tfor b = 1, num_cells do\n\tlove.graphics.points( nx[b], ny[b] )\n\tend\n\tlove.graphics.setCanvas( )\n\treturn canvas\nend\n\n--RENDER\nfunction love.draw( )\n\t--reset color\n\tlove.graphics.setColor( { 1, 1, 1 } )\n\t--draw diagram\n\tlove.graphics.draw( voronoiDiagram )\n\t--draw drop shadow text\n\tlove.graphics.setColor( { 0, 0, 0 } )\n\tlove.graphics.print( \"space: regenerate\\nesc: quit\", 1, 1 )\n\t--draw text\n\tlove.graphics.setColor( { 0.7, 0.7, 0 } )\n\tlove.graphics.print( \"space: regenerate\\nesc: quit\" )\nend\n\n--CONTROL\nfunction love.keyreleased( key )\n\tif key == 'space' then\n\tvoronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )\n\telseif key == 'escape' then\n\tlove.event.quit( )\n\tend\nend\n"} {"title": "Water collected between towers", "language": "Lua from C#", "task": "In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, \ncompletely filling all convex enclosures in the chart with water. \n\n \n9 ## 9 ## \n8 ## 8 ## \n7 ## ## 7 #### \n6 ## ## ## 6 ###### \n5 ## ## ## #### 5 ########## \n4 ## ## ######## 4 ############ \n3 ###### ######## 3 ############## \n2 ################ ## 2 ##################\n1 #################### 1 ####################\n \n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n\nSee, also:\n\n* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.\n\n\n\n", "solution": "function waterCollected(i,tower)\n local length = 0\n for _ in pairs(tower) do\n length = length + 1\n end\n\n local wu = 0\n repeat\n local rht = length - 1\n while rht >= 0 do\n if tower[rht + 1] > 0 then\n break\n end\n rht = rht - 1\n end\n if rht < 0 then\n break\n end\n\n local bof = 0\n local col = 0\n while col <= rht do\n if tower[col + 1] > 0 then\n tower[col + 1] = tower[col + 1] - 1\n bof = bof + 1\n elseif bof > 0 then\n wu = wu + 1\n end\n col = col + 1\n end\n if bof < 2 then\n break\n end\n until false\n if wu == 0 then\n print(string.format(\"Block %d does not hold any water.\", i))\n else\n print(string.format(\"Block %d holds %d water units.\", i, wu))\n end\nend\n\nfunction main()\n local towers = {\n {1, 5, 3, 7, 2},\n {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},\n {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},\n {5, 5, 5, 5},\n {5, 6, 7, 8},\n {8, 7, 7, 6},\n {6, 7, 10, 7, 6}\n }\n\n for i,tbl in pairs(towers) do\n waterCollected(i,tbl)\n end\nend\n\nmain()"} {"title": "Weird numbers", "language": "Lua from C#", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* MathWorld: weird number\n\n", "solution": "function make(n, d)\n local a = {}\n for i=1,n do\n table.insert(a, d)\n end\n return a\nend\n\nfunction reverse(t)\n local n = #t\n local i = 1\n while i < n do\n t[i],t[n] = t[n],t[i]\n i = i + 1\n n = n - 1\n end\nend\n\nfunction tail(list)\n return { select(2, unpack(list)) }\nend\n\nfunction divisors(n)\n local divs = {}\n table.insert(divs, 1)\n\n local divs2 = {}\n\n local i = 2\n while i * i <= n do\n if n % i == 0 then\n local j = n / i\n table.insert(divs, i)\n if i ~= j then\n table.insert(divs2, j)\n end\n end\n i = i + 1\n end\n\n reverse(divs)\n for i,v in pairs(divs) do\n table.insert(divs2, v)\n end\n return divs2\nend\n\nfunction abundant(n, divs)\n local sum = 0\n for i,v in pairs(divs) do\n sum = sum + v\n end\n return sum > n\nend\n\nfunction semiPerfect(n, divs)\n if #divs > 0 then\n local h = divs[1]\n local t = tail(divs)\n if n < h then\n return semiPerfect(n, t)\n else\n return n == h\n or semiPerfect(n - h, t)\n or semiPerfect(n, t)\n end\n else\n return false\n end\nend\n\nfunction sieve(limit)\n -- false denotes abundant and not semi-perfect.\n -- Only interested in even numbers >= 2\n local w = make(limit, false)\n local i = 2\n while i < limit do\n if not w[i] then\n local divs = divisors(i)\n if not abundant(i, divs) then\n w[i] = true\n elseif semiPerfect(i, divs) then\n local j = i\n while j < limit do\n w[j] = true\n j = j + i\n end\n end\n end\n i = i + 1\n end\n return w\nend\n\nfunction main()\n local w = sieve(17000)\n local count = 0\n local max = 25\n print(\"The first 25 weird numbers:\")\n local n = 2\n while count < max do\n if not w[n] then\n io.write(n, ' ')\n count = count + 1\n end\n n = n + 2\n end\n print()\nend\n\nmain()"} {"title": "Word frequency", "language": "lua 5.3", "task": "Given a text file and an integer '''n''', print/display the '''n''' most\ncommon words in the file (and the number of their occurrences) in decreasing frequency.\n\n\nFor the purposes of this task:\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a ''letter'' is. \n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like '''well-dressed''' as either one word or two. \n* The word '''it's''' could also be one or two words as you see fit. \n* You may also choose not to support non US-ASCII characters. \n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences. \n* Treat '''color''' and '''colour''' as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*McIlroy's program\n\n\n\n\n", "solution": "-- This program takes two optional command line arguments. The first (arg[1])\n-- specifies the input file, or defaults to standard input. The second\n-- (arg[2]) specifies the number of results to show, or defaults to 10.\n\n-- in freq, each key is a word and each value is its count\nlocal freq = {}\nfor line in io.lines(arg[1]) do\n\t-- %a stands for any letter\n\tfor word in string.gmatch(string.lower(line), \"%a+\") do\n\t\tif not freq[word] then\n\t\t\tfreq[word] = 1\n\t\telse\n\t\t\tfreq[word] = freq[word] + 1\n\t\tend\n\tend\nend\n\n-- in array, each entry is an array whose first value is the count and whose\n-- second value is the word\nlocal array = {}\nfor word, count in pairs(freq) do\n\ttable.insert(array, {count, word})\nend\ntable.sort(array, function (a, b) return a[1] > b[1] end)\n\nfor i = 1, arg[2] or 10 do\n\tio.write(string.format('%7d %s\\n', array[i][1] , array[i][2]))\nend\n"} {"title": "Word wrap", "language": "Lua", "task": "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "function splittokens(s)\n local res = {}\n for w in s:gmatch(\"%S+\") do\n res[#res+1] = w\n end\n return res\nend\n\nfunction textwrap(text, linewidth)\n if not linewidth then\n linewidth = 75\n end\n\n local spaceleft = linewidth\n local res = {}\n local line = {}\n\n for _, word in ipairs(splittokens(text)) do\n if #word + 1 > spaceleft then\n table.insert(res, table.concat(line, ' '))\n line = {word}\n spaceleft = linewidth - #word\n else\n table.insert(line, word)\n spaceleft = spaceleft - (#word + 1)\n end\n end\n\n table.insert(res, table.concat(line, ' '))\n return table.concat(res, '\\n')\nend\n\nlocal example1 = [[\nEven today, with proportional fonts and complex layouts,\nthere are still cases where you need to wrap text at a\nspecified column. The basic task is to wrap a paragraph\nof text in a simple way in your language. If there is a\nway to do this that is built-in, trivial, or provided in\na standard library, show that. Otherwise implement the\nminimum length greedy algorithm from Wikipedia.\n]]\n\nprint(textwrap(example1))\nprint()\nprint(textwrap(example1, 60))"} {"title": "World Cup group stage", "language": "Lua from C++", "task": "It's World Cup season (or at least it was when this page was created)! \n\nThe World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams. \n\nFor the first part of the World Cup tournament the teams play in \"group stage\" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage. \n\nEach game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. \n:::* A win is worth three points.\n:::* A draw/tie is worth one point. \n:::* A loss is worth zero points.\n\n\n;Task:\n:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. \n:* Calculate the standings points for each team with each combination of outcomes. \n:* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.\n\n\nDon't worry about tiebreakers as they can get complicated. We are basically looking to answer the question \"if a team gets x standings points, where can they expect to end up in the group standings?\".\n\n''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''\n\n", "solution": "function array1D(a, d)\n local m = {}\n for i=1,a do\n table.insert(m, d)\n end\n return m\nend\n\nfunction array2D(a, b, d)\n local m = {}\n for i=1,a do\n table.insert(m, array1D(b, d))\n end\n return m\nend\n\nfunction fromBase3(num)\n local out = 0\n for i=1,#num do\n local c = num:sub(i,i)\n local d = tonumber(c)\n out = 3 * out + d\n end\n return out\nend\n\nfunction toBase3(num)\n local ss = \"\"\n while num > 0 do\n local rem = num % 3\n num = math.floor(num / 3)\n ss = ss .. tostring(rem)\n end\n return string.reverse(ss)\nend\n\ngames = { \"12\", \"13\", \"14\", \"23\", \"24\", \"34\" }\n\nresults = \"000000\"\nfunction nextResult()\n if results == \"222222\" then\n return false\n end\n\n local res = fromBase3(results)\n results = string.format(\"%06s\", toBase3(res + 1))\n\n return true\nend\n\npoints = array2D(4, 10, 0)\n\nrepeat\n local records = array1D(4, 0)\n\n for i=1,#games do\n if results:sub(i,i) == '2' then\n local j = tonumber(games[i]:sub(1,1))\n records[j] = records[j] + 3\n elseif results:sub(i,i) == '1' then\n local j = tonumber(games[i]:sub(1,1))\n records[j] = records[j] + 1\n j = tonumber(games[i]:sub(2,2))\n records[j] = records[j] + 1\n elseif results:sub(i,i) == '0' then\n local j = tonumber(games[i]:sub(2,2))\n records[j] = records[j] + 3\n end\n end\n\n table.sort(records)\n for i=1,#records do\n points[i][records[i]+1] = points[i][records[i]+1] + 1\n end\nuntil not nextResult()\n\nprint(\"POINTS 0 1 2 3 4 5 6 7 8 9\")\nprint(\"-------------------------------------------------------------\")\nplaces = { \"1st\", \"2nd\", \"3rd\", \"4th\" }\nfor i=1,#places do\n io.write(places[i] .. \" place\")\n local row = points[i]\n for j=1,#row do\n io.write(string.format(\"%5d\", points[5 - i][j]))\n end\n print()\nend"} {"title": "Write float arrays to a text file", "language": "Lua", "task": "Write two equal-sized numerical arrays 'x' and 'y' to \na two-column text file named 'filename'.\n\nThe first column of the file contains values from an 'x'-array with a \ngiven 'xprecision', the second -- values from 'y'-array with 'yprecision'.\n\nFor example, considering:\n x = {1, 2, 3, 1e11};\n y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; \n /* sqrt(x) */\n xprecision = 3;\n yprecision = 5;\n\nThe file should look like:\n 1 1\n 2 1.4142\n 3 1.7321\n 1e+011 3.1623e+005\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "filename = \"file.txt\"\n\nx = { 1, 2, 3, 1e11 }\ny = { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 };\nxprecision = 3;\nyprecision = 5;\n\nfstr = \"%.\"..tostring(xprecision)..\"f \"..\"%.\"..tostring(yprecision)..\"f\\n\"\n\nfp = io.open( filename, \"w+\" )\n\nfor i = 1, #x do\n fp:write( string.format( fstr, x[i], y[i] ) )\nend\n\nio.close( fp )"} {"title": "Write language name in 3D ASCII", "language": "Lua", "task": "Write/display a language's name in '''3D''' ASCII. \n\n\n(We can leave the definition of \"3D ASCII\" fuzzy, \nso long as the result is interesting or amusing, \nnot a cheap hack to satisfy the task.)\n\n\n;Related tasks:\n* draw a sphere\n* draw a cuboid\n* draw a rotating cube\n* draw a Deathstar\n\n", "solution": "io.write(\" /$$\\n\")\nio.write(\"| $$\\n\")\nio.write(\"| $$ /$$ /$$ /$$$$$$\\n\")\nio.write(\"| $$ | $$ | $$ |____ $$\\n\")\nio.write(\"| $$ | $$ | $$ /$$$$$$$\\n\")\nio.write(\"| $$ | $$ | $$ /$$__ $$\\n\")\nio.write(\"| $$$$$$$$| $$$$$$/| $$$$$$$\\n\")\nio.write(\"|________/ \\______/ \\_______/\\n\")"} {"title": "Yellowstone sequence", "language": "Lua from Java", "task": "The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:\n\nFor n <= 3,\n\n a(n) = n\n\nFor n >= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first '''30''' Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* Greatest common divisor.\n:* Plot coordinate pairs.\n\n\n;See also:\n:* The OEIS entry: A098550 The Yellowstone permutation.\n:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "function gcd(a, b)\n if b == 0 then\n return a\n end\n return gcd(b, a % b)\nend\n\nfunction printArray(a)\n io.write('[')\n for i,v in pairs(a) do\n if i > 1 then\n io.write(', ')\n end\n io.write(v)\n end\n io.write(']')\n return nil\nend\n\nfunction removeAt(a, i)\n local na = {}\n for j,v in pairs(a) do\n if j ~= i then\n table.insert(na, v)\n end\n end\n return na\nend\n\nfunction yellowstone(sequenceCount)\n local yellow = {1, 2, 3}\n local num = 4\n local notYellow = {}\n local yellowSize = 3\n while yellowSize < sequenceCount do\n local found = -1\n for i,test in pairs(notYellow) do\n if gcd(yellow[yellowSize - 1], test) > 1 and gcd(yellow[yellowSize - 0], test) == 1 then\n found = i\n break\n end\n end\n if found >= 0 then\n table.insert(yellow, notYellow[found])\n notYellow = removeAt(notYellow, found)\n yellowSize = yellowSize + 1\n else\n while true do\n if gcd(yellow[yellowSize - 1], num) > 1 and gcd(yellow[yellowSize - 0], num) == 1 then\n table.insert(yellow, num)\n yellowSize = yellowSize + 1\n num = num + 1\n break\n end\n table.insert(notYellow, num)\n num = num + 1\n end\n end\n end\n return yellow\nend\n\nfunction main()\n print(\"First 30 values in the yellowstone sequence:\")\n printArray(yellowstone(30))\n print()\nend\n\nmain()"} {"title": "Zeckendorf number representation", "language": "Lua", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "-- Return the distinct Fibonacci numbers not greater than 'n'\nfunction fibsUpTo (n)\n local fibList, last, current, nxt = {}, 1, 1\n while current <= n do\n table.insert(fibList, current)\n nxt = last + current\n last = current\n current = nxt \n end\n return fibList\nend\n\n-- Return the Zeckendorf representation of 'n'\nfunction zeckendorf (n)\n local fib, zeck = fibsUpTo(n), \"\"\n for pos = #fib, 1, -1 do\n if n >= fib[pos] then\n zeck = zeck .. \"1\"\n n = n - fib[pos]\n else\n zeck = zeck .. \"0\"\n end\n end\n if zeck == \"\" then return \"0\" end\n return zeck\nend\n\n-- Main procedure\nprint(\" n\\t| Zeckendorf(n)\")\nprint(string.rep(\"-\", 23))\nfor n = 0, 20 do\n print(\" \" .. n, \"| \" .. zeckendorf(n))\nend"} {"title": "Zhang-Suen thinning algorithm", "language": "Lua", "task": "This is an algorithm used to thin a black and white i.e. one bit per pixel images. \n\nFor example, with an input image of:\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \nIt produces the thinned output:\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n\n;Algorithm:\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours. \n\nThe neighbours are, in order, arranged as:\n\n\n P9 P2 P3 \n P8 P1 P4 \n P7 P6 P5 \n\n\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\n\n;Step 1:\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\n\n;Step 2:\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and '''P8''' is white\n* (4) At least one of '''P2''' and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\n\n;Iteration:\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\n\n;Task:\n# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. \n\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n\n;Reference:\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen\n\n", "solution": "function zhangSuenThin(img)\n local dirs={\n { 0,-1},\n { 1,-1},\n { 1, 0},\n { 1, 1},\n { 0, 1},\n {-1, 1},\n {-1, 0},\n {-1,-1},\n { 0,-1},\n }\n\n local black=1\n local white=0\n\n function A(x, y)\n local c=0\n local current=img[y+dirs[1][2]][x+dirs[1][1]]\n for i=2,#dirs do\n local to_compare=img[y+dirs[i][2]][x+dirs[i][1]]\n if current==white and to_compare==black then\n c=c+1\n end\n current=to_compare\n end\n return c\n end\n\n function B(x, y)\n local c=0\n for i=2,#dirs do\n local value=img[y+dirs[i][2]][x+dirs[i][1]]\n if value==black then\n c=c+1\n end\n end\n return c\n end\n\n function common_step(x, y)\n if img[y][x]~=black or x<=1 or x>=#img[y] or y<=1 or y>=#img then\n return false\n end\n\n local b_value=B(x, y)\n if b_value<2 or b_value>6 then\n return false\n end\n\n local a_value=A(x, y)\n if a_value~=1 then\n return false\n end\n return true\n end\n\n function step_one(x, y)\n if not common_step(x, y) then\n return false\n end\n local p2=img[y+dirs[1][2]][x+dirs[1][1]]\n local p4=img[y+dirs[3][2]][x+dirs[3][1]]\n local p6=img[y+dirs[5][2]][x+dirs[5][1]]\n local p8=img[y+dirs[7][2]][x+dirs[7][1]]\n\n if p4==white or p6==white or p2==white and p8==white then\n return true\n end\n return false\n end\n\n function step_two(x, y)\n if not common_step(x, y) then\n return false\n end\n local p2=img[y+dirs[1][2]][x+dirs[1][1]]\n local p4=img[y+dirs[3][2]][x+dirs[3][1]]\n local p6=img[y+dirs[5][2]][x+dirs[5][1]]\n local p8=img[y+dirs[7][2]][x+dirs[7][1]]\n\n if p2==white or p8==white or p4==white and p6==white then\n return true\n end\n return false\n end\n\n function convert(to_do)\n for k,v in pairs(to_do) do\n img[v[2]][v[1]]=white\n end\n end\n\n function do_step_on_all(step)\n local to_convert={}\n for y=1,#img do\n for x=1,#img[y] do\n if step(x, y) then\n table.insert(to_convert, {x,y})\n end\n end\n end\n convert(to_convert)\n return #to_convert>0\n end\n\n local continue=true\n while continue do\n continue=false\n if do_step_on_all(step_one) then\n continue=true\n end\n\n if do_step_on_all(step_two) then\n continue=true\n end\n end\n\n for y=1,#img do\n for x=1,#img[y] do\n io.write(img[y][x]==black and '#' or ' ')\n end\n io.write('\\n')\n end\nend\n\nlocal image = {\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},\n {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,0,0},\n {0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0},\n {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0},\n {0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0},\n {0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n}\n\nzhangSuenThin(image)\n"}