title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Find the last Sunday of each month | Lua | 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).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
;Related tasks
* [[Day of the week]]
* [[Five weekends]]
* [[Last Friday of each month]]
| function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
function dayOfWeek (y, m, d)
local t = os.time({year = y, month = m, day = d})
return os.date("%A", t)
end
function lastWeekdays (wday, year)
local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if isLeapYear(year) then monthLength[2] = 29 end
for month = 1, 12 do
day = monthLength[month]
while dayOfWeek(year, month, day) ~= wday do day = day - 1 end
print(year .. "-" .. month .. "-" .. day)
end
end
lastWeekdays("Sunday", tonumber(arg[1])) |
Find the missing permutation | Lua | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed.
;Task:
Find that missing permutation.
;Methods:
* Obvious method:
enumerate all permutations of '''A''', '''B''', '''C''', and '''D''',
and then look for the missing permutation.
* alternate method:
Hint: if all permutations were shown above, how many
times would '''A''' appear in each position?
What is the ''parity'' of this number?
* another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter '''A''', '''B''', '''C''', and '''D''' from each
column cause the total value for each column to be unique?
;Related task:
* [[Permutations]])
| local permute, tablex = require("pl.permute"), require("pl.tablex")
local permList, pStr = {
"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
}
for perm in permute.iter({"A","B","C","D"}) do
pStr = table.concat(perm)
if not tablex.find(permList, pStr) then print(pStr) end
end |
First-class functions/Use numbers analogously | Lua | In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write 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:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create 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:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying 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.
'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
| -- This function returns another function that
-- keeps n1 and n2 in scope, ie. a closure.
function multiplier (n1, n2)
return function (m)
return n1 * n2 * m
end
end
-- Multiple assignment a-go-go
local x, xi, y, yi = 2.0, 0.5, 4.0, 0.25
local z, zi = x + y, 1.0 / ( x + y )
local nums, invs = {x, y, z}, {xi, yi, zi}
-- 'new_function' stores the closure and then has the 0.5 applied to it
-- (this 0.5 isn't in the task description but everyone else used it)
for k, v in pairs(nums) do
new_function = multiplier(v, invs[k])
print(v .. " * " .. invs[k] .. " * 0.5 = " .. new_function(0.5))
end
|
Fivenum | Lua | 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.
For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.
;Task:
Given an array of numbers, compute the five-number summary.
;Note:
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
| function slice(tbl, low, high)
local copy = {}
for i=low or 1, high or #tbl do
copy[#copy+1] = tbl[i]
end
return copy
end
-- assumes that tbl is sorted
function median(tbl)
m = math.floor(#tbl / 2) + 1
if #tbl % 2 == 1 then
return tbl[m]
end
return (tbl[m-1] + tbl[m]) / 2
end
function fivenum(tbl)
table.sort(tbl)
r0 = tbl[1]
r2 = median(tbl)
r4 = tbl[#tbl]
m = math.floor(#tbl / 2)
if #tbl % 2 == 1 then
low = m
else
low = m - 1
end
r1 = median(slice(tbl, nil, low+1))
r3 = median(slice(tbl, low+2, nil))
return r0, r1, r2, r3, r4
end
x1 = {
{15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},
{36.0, 40.0, 7.0, 39.0, 41.0, 15.0},
{
0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,
-0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,
-0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,
0.75775634, 0.32566578
}
}
for i,x in ipairs(x1) do
print(fivenum(x))
end |
Fixed length records | Lua | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These 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.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
;Task:
Write 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.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
'''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.
These 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''.
;Sample data:
To 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.
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 RT MARGIN
prompt$ 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.
prompt$ 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.
;Bonus round:
Forth 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).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also 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.
The COBOL example uses forth.txt and forth.blk filenames.
| -- prep: convert given sample text to fixed length "infile.dat"
local sample = [[
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 RT MARGIN]]
local txtfile = io.open("sample.txt", "w")
txtfile:write(sample)
txtfile:close()
os.execute("dd if=sample.txt of=infile.dat cbs=80 conv=block > /dev/null 2>&1")
-- task: convert fixed length "infile.dat" to fixed length "outfile.dat" (reversed lines)
local infile = io.open("infile.dat", "rb")
local outfile = io.open("outfile.dat", "wb")
while true do
local line = infile:read(80)
if not line then break end
outfile:write(string.reverse(line))
end
infile:close()
outfile:close()
-- output:
os.execute("dd if=outfile.dat cbs=80 conv=unblock") |
Flatten a list | Lua | Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
;Related task:
* [[Tree traversal]]
| function flatten(list)
if type(list) ~= "table" then return {list} end
local flat_list = {}
for _, elem in ipairs(list) do
for _, val in ipairs(flatten(elem)) do
flat_list[#flat_list + 1] = val
end
end
return flat_list
end
test_list = {{1}, 2, {{3,4}, 5}, {{{}}}, {{{6}}}, 7, 8, {}}
print(table.concat(flatten(test_list), ",")) |
Flipping bits game | Lua | The game:
Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.
;Task:
Create a program to score for the Flipping bits game.
# The game should create an original random target configuration and a starting configuration.
# Ensure that the starting position is ''never'' the target position.
# 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).
# The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a '''3x3''' array of bits.
| target, board, moves, W, H = {}, {}, 0, 3, 3
function getIndex( i, j ) return i + j * W - W end
function flip( d, r )
function invert( a ) if a == 1 then return 0 end return 1 end
local idx
if d == 1 then
for i = 1, W do
idx = getIndex( i, r )
board[idx] = invert( board[idx] )
end
else
for i = 1, H do
idx = getIndex( r, i )
board[idx] = invert( board[idx] )
end
end
moves = moves + 1
end
function createTarget()
target, board = {}, {}
local idx
for j = 1, H do
for i = 1, W do
idx = getIndex( i, j )
if math.random() < .5 then target[idx] = 0
else target[idx] = 1
end
board[idx] = target[idx]
end
end
for i = 1, 103 do
if math.random() < .5 then flip( 1, math.random( H ) )
else flip( 2, math.random( W ) )
end
end
moves = 0
end
function getUserInput()
io.write( "Input row and/or column: " ); local r = io.read()
local a
for i = 1, #r do
a = string.byte( r:sub( i, i ):lower() )
if a >= 48 and a <= 57 then flip( 2, a - 48 ) end
if a >= 97 and a <= string.byte( 'z' ) then flip( 1, a - 96 ) end
end
end
function solved()
local idx
for j = 1, H do
for i = 1, W do
idx = getIndex( i, j )
if target[idx] ~= board[idx] then return false end
end
end
return true
end
function display()
local idx
io.write( "\nTARGET\n " )
for i = 1, W do io.write( string.format( "%d ", i ) ) end; print()
for j = 1, H do
io.write( string.format( "%s ", string.char( 96 + j ) ) )
for i = 1, W do
idx = getIndex( i, j )
io.write( string.format( "%d ", target[idx] ) )
end; io.write( "\n" )
end
io.write( "\nBOARD\n " )
for i = 1, W do io.write( string.format( "%d ", i ) ) end; print()
for j = 1, H do
io.write( string.format( "%s ", string.char( 96 + j ) ) )
for i = 1, W do
idx = getIndex( i, j )
io.write( string.format( "%d ", board[idx] ) )
end; io.write( "\n" )
end
io.write( string.format( "Moves: %d\n", moves ) )
end
function play()
while true do
createTarget()
repeat
display()
getUserInput()
until solved()
display()
io.write( "Very well!\nPlay again(Y/N)? " );
if io.read():lower() ~= "y" then return end
end
end
--[[entry point]]--
math.randomseed( os.time() )
play()
|
Floyd's triangle | Lua | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
* the first row is '''1''' (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
;Task:
:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).
:# 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.
| function print_floyd(rows)
local c = 1
local h = rows*(rows-1)/2
for i=1,rows do
local s = ""
for j=1,i do
for k=1, #tostring(h+j)-#tostring(c) do
s = s .. " "
end
if j ~= 1 then s = s .. " " end
s = s .. tostring(c)
c = c + 1
end
print(s)
end
end
print_floyd(5)
print_floyd(14) |
Four bit adder | Lua | "''Simulate''" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two gate. ;
Finally a half adder can be made using an ''xor'' gate and an ''and'' gate.
The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.
'''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If 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.
Instead 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.
{|
|+Schematics of the "constructive blocks"
!(Xor gate with ANDs, ORs and NOTs)
! (A half adder)
! (A full adder)
! (A 4-bit adder)
|-
|Xor gate done with ands, ors and nots
|A half adder
|A full adder
|A 4-bit adder
|}
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It 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.
To test the implementation, show the sum of two four-bit numbers (in binary).
| -- Build XOR from AND, OR and NOT
function xor (a, b) return (a and not b) or (b and not a) end
-- Can make half adder now XOR exists
function halfAdder (a, b) return xor(a, b), a and b end
-- Full adder is two half adders with carry outputs OR'd
function fullAdder (a, b, cIn)
local ha0s, ha0c = halfAdder(cIn, a)
local ha1s, ha1c = halfAdder(ha0s, b)
local cOut, s = ha0c or ha1c, ha1s
return cOut, s
end
-- Carry bits 'ripple' through adders, first returned value is overflow
function fourBitAdder (a3, a2, a1, a0, b3, b2, b1, b0) -- LSB-first
local fa0c, fa0s = fullAdder(a0, b0, false)
local fa1c, fa1s = fullAdder(a1, b1, fa0c)
local fa2c, fa2s = fullAdder(a2, b2, fa1c)
local fa3c, fa3s = fullAdder(a3, b3, fa2c)
return fa3c, fa3s, fa2s, fa1s, fa0s -- Return as MSB-first
end
-- Take string of noughts and ones, convert to native boolean type
function toBool (bitString)
local boolList, bit = {}
for digit = 1, 4 do
bit = string.sub(string.format("%04d", bitString), digit, digit)
if bit == "0" then table.insert(boolList, false) end
if bit == "1" then table.insert(boolList, true) end
end
return boolList
end
-- Take list of booleans, convert to string of binary digits (variadic)
function toBits (...)
local bStr = ""
for i, bool in pairs{...} do
if bool then bStr = bStr .. "1" else bStr = bStr .. "0" end
end
return bStr
end
-- Little driver function to neaten use of the adder
function add (n1, n2)
local A, B = toBool(n1), toBool(n2)
local v, s0, s1, s2, s3 = fourBitAdder( A[1], A[2], A[3], A[4],
B[1], B[2], B[3], B[4] )
return toBits(s0, s1, s2, s3), v
end
-- Main procedure (usage examples)
print("SUM", "OVERFLOW\n")
print(add(0001, 0001)) -- 1 + 1 = 2
print(add(0101, 1010)) -- 5 + 10 = 15
print(add(0000, 1111)) -- 0 + 15 = 15
print(add(0001, 1111)) -- 1 + 15 = 16 (causes overflow) |
Four is magic | Lua | 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.
Continue 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.
Continue 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.
For 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.'''
'''Three is five, five is four, four is magic.'''
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
;Some task guidelines:
:* You may assume the input will only contain integer numbers.
:* 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'''.)
:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)
:* 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'''.
:* 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'''.
:* 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'''.
:* 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.")
:* The output can either be the return value from the function, or be displayed from within the function.
:* You are encouraged, though not mandated to use proper sentence capitalization.
:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.
:* 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.
You 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.
If 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.)
Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.
;Related tasks:
:* [[Four is the number of_letters in the ...]]
:* [[Look-and-say sequence]]
:* [[Number names]]
:* [[Self-describing numbers]]
:* [[Summarize and say sequence]]
:* [[Spelling of ordinal numbers]]
:* [[De Bruijn sequences]]
| -- Four is magic, in Lua, 6/16/2020 db
local oneslist = { [0]="", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
local teenlist = { [0]="ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }
local tenslist = { [0]="", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }
local lionlist = { [0]="", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion" }
local abs, floor = math.abs, math.floor
local function numname(num)
if (num == 0) then return "zero" end
local absnum, lion, result = abs(num), 0, ""
local function dashed(s) return s=="" and s or "-"..s end
local function spaced(s) return s=="" and s or " "..s end
while (absnum > 0) do
local word, ones, tens, huns = "", absnum%10, floor(absnum/10)%10, floor(absnum/100)%10
if (tens==0) then word = oneslist[ones]
elseif (tens==1) then word = teenlist[ones]
else word = tenslist[tens] .. dashed(oneslist[ones]) end
if (huns > 0) then word = oneslist[huns] .. " hundred" .. spaced(word) end
if (word ~= "") then result = word .. spaced(lionlist[lion]) .. spaced(result) end
absnum = floor(absnum / 1000)
lion = lion + 1
end
if (num < 0) then result = "negative " .. result end
return result
end
local function fourismagic(num)
local function fim(num)
local name = numname(num)
if (num == 4) then
return name .. " is magic."
else
local what = numname(#name)
return name .. " is " .. what .. ", " .. fim(#name)
end
end
local result = fim(num):gsub("^%l", string.upper)
return result
end
local numbers = { -21,-1, 0,1,2,3,4,5,6,7,8,9, 12,34,123,456,1024,1234,12345,123456,1010101 }
for _, num in ipairs(numbers) do
print(num, fourismagic(num))
end |
Function prototype | Lua | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
;Task:
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
* An explanation of any placement restrictions for prototype declarations
* A prototype declaration for a function that does not require arguments
* A prototype declaration for a function that requires two arguments
* A prototype declaration for a function that utilizes varargs
* A prototype declaration for a function that utilizes optional arguments
* A prototype declaration for a function that utilizes named parameters
* Example of prototype declarations for subroutines or procedures (if these differ from functions)
* An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
| function Func() -- Does not require arguments
return 1
end
function Func(a,b) -- Requires arguments
return a + b
end
function Func(a,b) -- Arguments are optional
return a or 4 + b or 2
end
function Func(a,...) -- One argument followed by varargs
return a,{...} -- Returns both arguments, varargs as table
end |
Functional coverage tree | Lua | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional ''requirements'' of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
;Task Description:
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The 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.
Some 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.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
;Calculation:
The 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.
'''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.
;Extra Credit:
After 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.
The 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.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
'''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.
| -- DATA:
local function node(name, weight, coverage, children)
return { name=name, weight=weight or 1.0, coverage=coverage or 0.0, sumofweights=0, delta=0, children=children }
end
local root =
node("cleaning", nil, nil, {
node("house1", 40, nil, {
node("bedrooms", nil, 0.25),
node("bathrooms", nil, nil, {
node("bathroom1", nil, 0.5),
node("bathroom2"),
node("outside_lavatory", nil, 1)
}),
node("attic", nil, 0.75),
node("kitchen", nil, 0.1),
node("living_rooms", nil, nil, {
node("lounge"),
node("dining_room"),
node("conservatory"),
node("playroom",nil,1)
}),
node("basement"),
node("garage"),
node("garden", nil, 0.8)
}),
node("house2", 60, nil, {
node("upstairs", nil, nil, {
node("bedrooms", nil, nil, {
node("suite_1"),
node("suite_2"),
node("bedroom_3"),
node("bedroom_4")
}),
node("bathroom"),
node("toilet"),
node("attics", nil, 0.6)
}),
node("groundfloor", nil, nil, {
node("kitchen"),
node("living_rooms", nil, nil, {
node("lounge"),
node("dining_room"),
node("conservatory"),
node("playroom")
}),
node("wet_room_&_toilet"),
node("garage"),
node("garden", nil, 0.9),
node("hot_tub_suite", nil, 1)
}),
node("basement", nil, nil, {
node("cellars", nil, 1),
node("wine_cellar", nil, 1),
node("cinema", nil, 0.75)
})
})
})
-- TASK:
local function calccover(node)
if (node.children) then
local cnt, sum = 0, 0
for _,child in ipairs(node.children) do
local ccnt, csum = calccover(child)
cnt, sum = cnt+ccnt, sum+csum
end
node.coverage = sum/cnt
node.sumofweights = cnt -- just as prep for extra credit
end
return node.weight, node.coverage * node.weight
end
calccover(root)
-- EXTRA CREDIT:
local function calcdelta(node, power)
node.delta = (1.0 - node.coverage) * power
if (node.children) then
for _,child in ipairs(node.children) do
calcdelta(child, power * child.weight / node.sumofweights)
end
end
end
calcdelta(root,1)
-- OUTPUT:
local function printnode(node, space)
print(string.format("%-32s| %3.f | %8.6f | %8.6f |", string.rep(" ",space)..node.name, node.weight, node.coverage, node.delta))
if node.children then
for _,child in ipairs(node.children) do printnode(child,space+4) end
end
end
print("NAME_HIERARCHY |WEIGHT |COVERAGE |DELTA |")
printnode(root,0) |
Fusc sequence | Lua from C | Definitions:
The '''fusc''' integer sequence is defined as:
::* fusc(0) = 0
::* fusc(1) = 1
::* for '''n'''>1, the '''n'''th term is defined as:
::::* if '''n''' is even; fusc(n) = fusc(n/2)
::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
;An observation:
:::::* fusc(A) = fusc(B)
where '''A''' is some non-negative integer expressed in binary, and
where '''B''' is the binary value of '''A''' reversed.
Fusc numbers are also known as:
::* fusc function (named by Dijkstra, 1982)
::* Stern's Diatomic series (although it starts with unity, not zero)
::* Stern-Brocot sequence (although it starts with unity, not zero)
;Task:
::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.
::* show the fusc number (and its index) whose length is greater than any previous fusc number length.
::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)
::* show all numbers with commas (if appropriate).
::* show all output here.
;Related task:
::* RosettaCode Stern-Brocot sequence
;Also see:
::* the MathWorld entry: Stern's Diatomic Series.
::* the OEIS entry: A2487.
| function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index-------Value")
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index-------Value")
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main() |
Gapful numbers | Lua from C | Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as '''gapful numbers'''.
''Evenly divisible'' means divisible with no remainder.
All one- and two-digit numbers have this property and are trivially excluded. Only
numbers >= '''100''' will be considered for this Rosetta Code task.
;Example:
'''187''' is a '''gapful''' number because it is evenly divisible by the
number '''17''' which is formed by the first and last decimal digits
of '''187'''.
About 7.46% of positive integers are ''gapful''.
;Task:
:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
:* Show the first '''30''' gapful numbers
:* Show the first '''15''' gapful numbers >= '''1,000,000'''
:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''
;Related tasks:
:* Harshad or Niven series.
:* palindromic gapful numbers.
:* largest number divisible by its digits.
;Also see:
:* The OEIS entry: A108343 gapful numbers.
:* numbersaplenty gapful numbers
| function generateGaps(start, count)
local counter = 0
local i = start
print(string.format("First %d Gapful numbers >= %d :", count, start))
while counter < count do
local str = tostring(i)
local denom = 10 * tonumber(str:sub(1, 1)) + (i % 10)
if i % denom == 0 then
print(string.format("%3d : %d", counter + 1, i))
counter = counter + 1
end
i = i + 1
end
end
generateGaps(100, 30)
print()
generateGaps(1000000, 15)
print()
generateGaps(1000000000, 15)
print() |
Generate Chess960 starting position | Lua | 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:
* as in the standard chess game, all eight white pawns must be placed on the second rank.
* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
** 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)
** the King must be between two rooks (with any number of other pieces between them all)
* 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.)
With those constraints there are '''960''' possible starting positions, thus the name of the variant.
;Task:
The 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.
| -- Insert 'str' into 't' at a random position from 'left' to 'right'
function randomInsert (t, str, left, right)
local pos
repeat pos = math.random(left, right) until not t[pos]
t[pos] = str
return pos
end
-- Generate a random Chess960 start position for white major pieces
function chess960 ()
local t, b1, b2 = {}
local kingPos = randomInsert(t, "K", 2, 7)
randomInsert(t, "R", 1, kingPos - 1)
randomInsert(t, "R", kingPos + 1, 8)
b1 = randomInsert(t, "B", 1, 8)
b2 = randomInsert(t, "B", 1, 8)
while (b2 - b1) % 2 == 0 do
t[b2] = false
b2 = randomInsert(t, "B", 1, 8)
end
randomInsert(t, "Q", 1, 8)
randomInsert(t, "N", 1, 8)
randomInsert(t, "N", 1, 8)
return t
end
-- Main procedure
math.randomseed(os.time())
print(table.concat(chess960())) |
Generator/Exponential | Lua | 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.
Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally".
Generators 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.
;Task:
* 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).
* Use it to create a generator of:
:::* Squares.
:::* Cubes.
* Create a new generator that filters all cubes from the generator of squares.
* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.
Note that this task ''requires'' the use of generators in the calculation of the result.
;Also see:
* Generator
| --could be done with a coroutine, but a simple closure works just as well.
local function powgen(m)
local count = 0
return function()
count = count + 1
return count^m
end
end
local squares = powgen(2)
local cubes = powgen(3)
local cowrap,coyield = coroutine.wrap, coroutine.yield
local function filter(f,g)
return cowrap(function()
local ff,gg = f(), g()
while true do
if ff == gg then
ff,gg = f(), g()
elseif ff < gg then
coyield(ff)
ff = f()
else
gg = g()
end
end
end)
end
filter = filter(squares,cubes)
for i = 1,30 do
local result = filter()
if i > 20 then
print(result)
end
end
|
Get system command output | Lua | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
;Related task
* Execute a system command
| local output = io.popen("echo Hurrah!")
print(output:read("*all")) |
Globally replace text in several files | Lua | Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
| filenames = { "f1.txt", "f2.txt" }
for _, fn in pairs( filenames ) do
fp = io.open( fn, "r" )
str = fp:read( "*all" )
str = string.gsub( str, "Goodbye London!", "Hello New York!" )
fp:close()
fp = io.open( fn, "w+" )
fp:write( str )
fp:close()
end |
Gray code | Lua from Euphoria | Karnaugh maps in order from left to right or top to bottom.
Create functions to encode a number to and decode a number from Gray code.
Display 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).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
;Reference
* Converting Between Gray and Binary Codes. It includes step-by-step animations.
| local bit = require 'bit'
local gray = require 'gray'
-- simple binary string formatter
local function to_bit_string(n, width)
width = width or 1
local output = ""
while n > 0 do
output = bit.band(n,1) .. output
n = bit.rshift(n,1)
end
while #output < width do
output = '0' .. output
end
return output
end
for i = 0,31 do
g = gray.encode(i);
gd = gray.decode(g);
print(string.format("%2d : %s => %s => %s : %2d", i,
to_bit_string(i,5), to_bit_string(g, 5),
to_bit_string(gd,5), gd))
end |
Greatest subsequential sum | Lua | 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.
An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
| function sumt(t, start, last) return start <= last and t[start] + sumt(t, start+1, last) or 0 end
function maxsub(ary, idx)
local idx = idx or 1
if not ary[idx] then return {} end
local maxsum, last = 0, idx
for i = idx, #ary do
if sumt(ary, idx, i) > maxsum then maxsum, last = sumt(ary, idx, i), i end
end
local v = maxsub(ary, idx + 1)
if maxsum < sumt(v, 1, #v) then return v end
local ret = {}
for i = idx, last do ret[#ret+1] = ary[i] end
return ret
end |
Hailstone sequence | Lua | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
* If n is '''1''' then the sequence ends.
* If n is '''even''' then the next n of the sequence = n/2
* If n is '''odd''' then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
:::* hailstone sequence, hailstone numbers
:::* 3x + 2 mapping, 3n + 1 problem
:::* Collatz sequence
:::* Hasse's algorithm
:::* Kakutani's problem
:::* Syracuse algorithm, Syracuse problem
:::* Thwaites conjecture
:::* Ulam's problem
The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
;Task:
# Create a routine to generate the hailstone sequence for a number.
# 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
# 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!)
;See also:
* xkcd (humourous).
* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
| function hailstone( n, print_numbers )
local n_iter = 1
while n ~= 1 do
if print_numbers then print( n ) end
if n % 2 == 0 then
n = n / 2
else
n = 3 * n + 1
end
n_iter = n_iter + 1
end
if print_numbers then print( n ) end
return n_iter;
end
hailstone( 27, true )
max_i, max_iter = 0, 0
for i = 1, 100000 do
num = hailstone( i, false )
if num >= max_iter then
max_i = i
max_iter = num
end
end
print( string.format( "Needed %d iterations for the number %d.\n", max_iter, max_i ) ) |
Harmonic series | Lua | {{Wikipedia|Harmonic number}}
In mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers:
'''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n'''
The series of harmonic numbers thus obtained is often loosely referred to as the harmonic series.
Harmonic numbers are closely related to the Euler-Mascheroni constant.
The harmonic series is divergent, albeit quite slowly, and grows toward infinity.
;Task
* Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers.
* Use that procedure to show the values of the first 20 harmonic numbers.
* Find and show the position in the series of the first value greater than the integers 1 through 5
;Stretch
* Find and show the position in the series of the first value greater than the integers 6 through 10
;Related
* [[Egyptian fractions]]
| -- Task 1
function harmonic (n)
if n < 1 or n ~= math.floor(n) then
error("Argument to harmonic function is not a natural number")
end
local Hn = 1
for i = 2, n do
Hn = Hn + (1/i)
end
return Hn
end
-- Task 2
for x = 1, 20 do
print(x .. " :\t" .. harmonic(x))
end
-- Task 3
local x, lastInt, Hx = 0, 1
repeat
x = x + 1
Hx = harmonic(x)
if Hx > lastInt then
io.write("The first harmonic number above " .. lastInt)
print(" is " .. Hx .. " at position " .. x)
lastInt = lastInt + 1
end
until lastInt > 10 -- Stretch goal just meant changing that value from 5 to 10
-- Execution still only takes about 120 ms under LuaJIT |
Harshad or Niven series | Lua | The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits.
For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.
Assume that the series is defined as the numbers in increasing order.
;Task:
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
::* list the first '''20''' members of the sequence, and
::* list the first Harshad number greater than '''1000'''.
Show your output here.
;Related task
:* Increasing gaps between consecutive Niven numbers
;See also
* OEIS: A005349
| function isHarshad(n)
local s=0
local n_str=tostring(n)
for i=1,#n_str do
s=s+tonumber(n_str:sub(i,i))
end
return n%s==0
end
local count=0
local harshads={}
local n=1
while count<20 do
if isHarshad(n) then
count=count+1
table.insert(harshads, n)
end
n=n+1
end
print(table.concat(harshads, " "))
local h=1001
while not isHarshad(h) do
h=h+1
end
print(h)
|
Hash join | Lua | {| class="wikitable"
|-
! Input
! Output
|-
|
{| style="border:none; border-collapse:collapse;"
|-
| style="border:none" | ''A'' =
| style="border:none" |
{| class="wikitable"
|-
! Age !! Name
|-
| 27 || Jonah
|-
| 18 || Alan
|-
| 28 || Glory
|-
| 18 || Popeye
|-
| 28 || Alan
|}
| style="border:none; padding-left:1.5em;" rowspan="2" |
| style="border:none" | ''B'' =
| style="border:none" |
{| class="wikitable"
|-
! Character !! Nemesis
|-
| Jonah || Whales
|-
| Jonah || Spiders
|-
| Alan || Ghosts
|-
| Alan || Zombies
|-
| Glory || Buffy
|}
|-
| style="border:none" | ''jA'' =
| style="border:none" | Name (i.e. column 1)
| style="border:none" | ''jB'' =
| style="border:none" | Character (i.e. column 0)
|}
|
{| class="wikitable" style="margin-left:1em"
|-
! A.Age !! A.Name !! B.Character !! B.Nemesis
|-
| 27 || Jonah || Jonah || Whales
|-
| 27 || Jonah || Jonah || Spiders
|-
| 18 || Alan || Alan || Ghosts
|-
| 18 || Alan || Alan || Zombies
|-
| 28 || Glory || Glory || Buffy
|-
| 28 || Alan || Alan || Ghosts
|-
| 28 || Alan || Alan || Zombies
|}
|}
The order of the rows in the output table is not significant.
If 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"]].
| local function recA(age, name) return { Age=age, Name=name } end
local tabA = { recA(27,"Jonah"), recA(18,"Alan"), recA(28,"Glory"), recA(18,"Popeye"), recA(28,"Alan") }
local function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end
local tabB = { recB("Jonah","Whales"), recB("Jonah","Spiders"), recB("Alan","Ghosts"), recB("Alan","Zombies"), recB("Glory","Buffy") }
local function hashjoin(taba, cola, tabb, colb)
local hash, join = {}, {}
for _,rowa in pairs(taba) do
if (not hash[rowa[cola]]) then hash[rowa[cola]] = {} end
table.insert(hash[rowa[cola]], rowa)
end
for _,rowb in pairs(tabb) do
for _,rowa in pairs(hash[rowb[colb]]) do
join[#join+1] = { A=rowa, B=rowb }
end
end
return join
end
for _,row in pairs(hashjoin(tabA, "Name", tabB, "Character")) do
print(row.A.Age, row.A.Name, row.B.Character, row.B.Nemesis)
end |
Haversine formula | Lua | {{Wikipedia}}
The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles".
;Task:
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
* Nashville International Airport (BNA) in Nashville, TN, USA, which is:
'''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-
* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
'''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' 1.0621333 km and .001" .00177 km,
practical precision required is certainly no greater than about
.0000001----i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
| local function haversine(x1, y1, x2, y2)
r=0.017453292519943295769236907684886127;
x1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1;
a = 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;
return d;
end |
Here document | Lua | A ''here document'' (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a ''here document'' is constructed using a command followed by "<<" (or some other symbol) followed by a token string.
The 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.
;Task:
Demonstrate the use of ''here documents'' within the language.
;Related task:
* [[Documentation]]
| print([[
This is a long paragraph of text
it is the simplest while using it
with lua, however it will have the
same line breaks and spacing as
you set in this block.
]])
print([=[by using equals signs, ]] may be embedded.]=])
local msg = [[this is a message that spans
multiple lines and will have the next lines
preserved as they were entered, so be careful
when using this]]
print(msg)
|
Heronian triangles | Lua | Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:
:::: A = \sqrt{s(s-a)(s-b)(s-c)},
where ''s'' is half the perimeter of the triangle; that is,
:::: s=\frac{a+b+c}{2}.
'''Heronian triangles'''
are triangles whose sides ''and area'' are all integers.
: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12''').
Note 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.
Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor
of all three sides is '''1''' (unity).
This will exclude, for example, triangle '''6, 8, 10.'''
;Task:
# Create a named function/method/procedure/... that implements Hero's formula.
# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.
# Show the count of how many triangles are found.
# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths
# Show the first ten ordered triangles in a table of sides, perimeter, and area.
# Show a similar ordered table for those triangles with area = 210
Show all output here.
'''Note''': when generating triangles it may help to restrict a <= b <= c
| -- Returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one
local function tryHt( a, b, c )
local result
local s = ( a + b + c ) / 2;
local areaSquared = s * ( s - a ) * ( s - b ) * ( s - c );
if areaSquared > 0 then
-- a, b, c does form a triangle
local area = math.sqrt( areaSquared );
if math.floor( area ) == area then
-- the area is integral so the triangle is Heronian
result = { a = a, b = b, c = c, perimeter = a + b + c, area = area }
end
end
return result
end
-- Returns the GCD of a and b
local function gcd( a, b ) return ( b == 0 and a ) or gcd( b, a % b ) end
-- Prints the details of the Heronian triangle t
local function htPrint( t ) print( string.format( "%4d %4d %4d %4d %4d", t.a, t.b, t.c, t.area, t.perimeter ) ) end
-- Prints headings for the Heronian Triangle table
local function htTitle() print( " a b c area perimeter" ); print( "---- ---- ---- ---- ---------" ) end
-- Construct ht as a table of the Heronian Triangles with sides up to 200
local ht = {};
for c = 1, 200 do
for b = 1, c do
for a = 1, b do
local t = gcd( gcd( a, b ), c ) == 1 and tryHt( a, b, c );
if t then
ht[ #ht + 1 ] = t
end
end
end
end
-- sort the table on ascending area, perimiter and max side length
-- note we constructed the triangles with c as the longest side
table.sort( ht, function( a, b )
return a.area < b.area or ( a.area == b.area
and ( a.perimeter < b.perimeter
or ( a.perimiter == b.perimiter
and a.c < b.c
)
)
)
end
);
-- Display the triangles
print( "There are " .. #ht .. " Heronian triangles with sides up to 200" );
htTitle();
for htPos = 1, 10 do htPrint( ht[ htPos ] ) end
print( " ..." );
print( "Heronian triangles with area 210:" );
htTitle();
for htPos = 1, #ht do
local t = ht[ htPos ];
if t.area == 210 then htPrint( t ) end
end |
History variables | Lua | ''Storing the history of objects in a program is a common task.
Maintaining 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.''
''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.
''
"History Variables:
The Semantics, Formal Correctness, and Implementation of History Variables
in an Imperative Programming Language" by Mallon and Takaoka
Concept also discussed on LtU and Patents.com.
;Task:
Demonstrate History variable support:
* enable history variable support (if needed)
* define a history variable
* assign three values
* non-destructively display the history
* recall the three values.
For extra points, if the language of choice does not support history variables,
demonstrate how this might be implemented.
| -- History variables in Lua 6/12/2020 db
local HistoryVariable = {
new = function(self)
return setmetatable({history={}},self)
end,
get = function(self)
return self.history[#self.history]
end,
set = function(self, value)
self.history[#self.history+1] = value
end,
undo = function(self)
self.history[#self.history] = nil
end,
}
HistoryVariable.__index = HistoryVariable
local hv = HistoryVariable:new()
print("defined:", hv)
print("value is:", hv:get())
--
hv:set(1); print("set() to:", hv:get())
hv:set(2); print("set() to:", hv:get())
hv:set(3); print("set() to:", hv:get())
--
print("history:", table.concat(hv.history,","))
--
hv:undo(); print("undo() to:", hv:get())
hv:undo(); print("undo() to:", hv:get())
hv:undo(); print("undo() to:", hv:get()) |
Hofstadter-Conway $10,000 sequence | Lua | The definition of the sequence is colloquially described as:
* Starting with the list [1,1],
* Take the last number in the list so far: 1, I'll call it x.
* Count forward x places from the beginning of the list to find the first number to add (1)
* Count backward x places from the end of the list to find the second number to add (1)
* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)
* This would then produce [1,1,2] where 2 is the third element of the sequence.
Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.
A less wordy description of the sequence is:
a(1)=a(2)=1
a(n)=a(a(n-1))+a(n-a(n-1))
The sequence begins:
1, 1, 2, 2, 3, 4, 4, 4, 5, ...
Interesting features of the sequence are that:
* a(n)/n tends to 0.5 as n grows towards infinity.
* a(n)/n where n is a power of 2 is 0.5
* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.
a(n) / n for n in 1..256
The sequence is so named because John Conway offered a prize of $10,000 to the first person who could
find the first position, p in the sequence where
|a(n)/n| < 0.55 for all n > p
It was later found that Hofstadter had also done prior work on the sequence.
The '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).
;Task:
# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.
# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20
# 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
;Also see:
* Conways Challenge Sequence, Mallows' own account.
* Mathworld Article.
| local fmt, write=string.format,io.write
local hof=coroutine.wrap(function()
local yield=coroutine.yield
local a={1,1}
yield(a[1], 1)
yield(a[2], 2)
local n=a[#a]
repeat
n=a[n]+a[1+#a-n]
a[#a+1]=n
yield(n, #a)
until false
end)
local mallows, mdiv=0,0
for p=1,20 do
local max, div, num, last, fdiv=0,0,0,0,0
for i=2^(p-1),2^p-1 do
h,n=hof()
div=h/n
if div>max then
max=div
num=n
end
if div>0.55 then
last=n
fdiv=div
end
end
write(fmt("From 2^%-2d to 2^%-2d the max is %.4f the %6dth Hofstadter number.\n",
p-1, p, max, num))
if max>.55 and p>4 then
mallows, mdiv=last, fdiv
end
end
write("So Mallows number is ", mallows, " with ", fmt("%.4f",mdiv), ", yay, just wire me my $10000 now!\n")
|
Horner's rule for polynomial evaluation | Lua | A fast scheme for evaluating a polynomial such as:
: -19+7x-4x^2+6x^3\,
when
: x=3\;.
is to arrange the computation as follows:
: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\;
And compute the result from the innermost brackets outwards as in this pseudocode:
coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''
x ''':=''' 3
accumulator ''':=''' 0
'''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''
''# Assumes 1-based indexing for arrays''
accumulator ''':=''' ( accumulator * x ) + coefficients[i]
'''done'''
''# accumulator now has the answer''
'''Task Description'''
: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.
Cf. [[Formal power series]]
| function horners_rule( coeff, x )
local res = 0
for i = #coeff, 1, -1 do
res = res * x + coeff[i]
end
return res
end
x = 3
coefficients = { -19, 7, -4, 6 }
print( horners_rule( coefficients, x ) ) |
ISBN13 check digit | Lua from C | Validate the check digit of an ISBN-13 code:
::* Multiply every other digit by '''3'''.
::* Add these numbers and the other digits.
::* Take the remainder of this number after division by '''10'''.
::* If it is '''0''', the ISBN-13 check digit is correct.
You might use the following codes for testing:
::::* 978-0596528126 (good)
::::* 978-0596528120 (bad)
::::* 978-1788399081 (good)
::::* 978-1788399083 (bad)
Show output here, on this page
;See also:
:* for details: 13-digit ISBN method of validation. (installs cookies.)
| function checkIsbn13(isbn)
local count = 0
local sum = 0
for c in isbn:gmatch"." do
if c == ' ' or c == '-' then
-- skip
elseif c < '0' or '9' < c then
return false
else
local digit = c - '0'
if (count % 2) > 0 then
sum = sum + 3 * digit
else
sum = sum + digit
end
count = count + 1
end
end
if count ~= 13 then
return false
end
return (sum % 10) == 0
end
function test(isbn)
if checkIsbn13(isbn) then
print(isbn .. ": good")
else
print(isbn .. ": bad")
end
end
function main()
test("978-1734314502")
test("978-1734314509")
test("978-1788399081")
test("978-1788399083")
end
main() |
I before E except after C | Lua | The phrase "I before E, except after C" is a
widely known mnemonic which is supposed to help when spelling English words.
;Task:
Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible individually:
:::# ''"I before E when not preceded by C"''
:::# ''"E before I when preceded by C"''
If both sub-phrases are plausible then the original phrase can be said to be plausible.
Something 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).
;Stretch goal:
As 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.
''Show your output here as well as your program.''
;cf.:
* Schools to rethink 'i before e' - BBC news, 20 June 2009
* I Before E Except After C - QI Series 8 Ep 14, (humorous)
* Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
| -- Needed to get dictionary file from web server
local http = require("socket.http")
-- Return count of words that contain pattern
function count (pattern, wordList)
local total = 0
for word in wordList:gmatch("%S+") do
if word:match(pattern) then total = total + 1 end
end
return total
end
-- Check plausibility of case given its opposite
function plaus (case, opposite, words)
if count(case, words) > 2 * count(opposite, words) then
print("PLAUSIBLE")
return true
else
print("IMPLAUSIBLE")
return false
end
end
-- Main procedure
local page = http.request("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
io.write("I before E when not preceded by C: ")
local sub1 = plaus("[^c]ie", "cie", page)
io.write("E before I when preceded by C: ")
local sub2 = plaus("cei", "[^c]ei", page)
io.write("Overall the phrase is ")
if not (sub1 and sub2) then io.write("not ") end
print("plausible.") |
Identity matrix | Lua | Build an identity matrix of a size known at run-time.
An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''',
where the diagonal elements are all '''1'''s (ones),
and all the other elements are all '''0'''s (zeroes).
I_n = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
0 & 0 & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & 1 \\
\end{bmatrix}
;Related tasks:
* [[Spiral matrix]]
* [[Zig-zag matrix]]
* [[Ulam_spiral_(for_primes)]]
| function identity_matrix (size)
local m = {}
for i = 1, size do
m[i] = {}
for j = 1, size do
m[i][j] = i == j and 1 or 0
end
end
return m
end
function print_matrix (m)
for i = 1, #m do
print(table.concat(m[i], " "))
end
end
print_matrix(identity_matrix(5)) |
Idiomatically determine all the characters that can be used for symbols | Lua | Idiomatically determine all the characters that can be used for ''symbols''.
The 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''.
The method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
;Task requirements
Display the set of all the characters that can be used for symbols which can be used (allowed) by the computer program.
You may want to mention what hardware architecture is being used, and if applicable, the operating system.
Note 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).
;See also
* Idiomatically determine all the lowercase and uppercase letters.
| function isValidIdentifier(id)
local reserved = {
["and"]=true, ["break"]=true, ["do"]=true, ["end"]=true, ["else"]=true, ["elseif"]=true, ["end"]=true,
["false"]=true, ["for"]=true, ["function"]=true, ["goto"]=true, ["if"]=true, ["in"]=true,
["local"]=true, ["nil"]=true, ["not"]=true, ["or"]=true, ["repeat"]=true, ["return"]=true,
["then"]=true, ["true"]=true, ["until"]=true, ["while"]=true }
return id:find("^[a-zA-Z_][a-zA-Z0-9_]*$") ~= nil and not reserved[id]
end
vfc, vsc = {}, {}
for i = 0, 255 do
local c = string.char(i)
if isValidIdentifier(c) then vfc[#vfc+1]=c end
if isValidIdentifier("_"..c) then vsc[#vsc+1]=c end
end
print("Valid First Characters: " .. table.concat(vfc))
print("Valid Subsequent Characters: " .. table.concat(vsc)) |
Idiomatically determine all the lowercase and uppercase letters | Lua | Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
;Task requirements
Display the set of all:
::::::* lowercase letters
::::::* uppercase letters
that can be used (allowed) by the computer program,
where ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''.
You may want to mention what hardware architecture is being used, and if applicable, the operating system.
;See also
* Idiomatically determine all the characters that can be used for symbols.
| function ASCIIstring (pattern)
local matchString, ch = ""
for charNum = 0, 255 do
ch = string.char(charNum)
if string.match(ch, pattern) then
matchString = matchString .. ch
end
end
return matchString
end
print(ASCIIstring("%l"))
print(ASCIIstring("%u"))
|
Integer overflow | Lua | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.
The integers supported by such a type can be ''signed'' or ''unsigned''.
Arithmetic for machine level integers can often be done by single CPU instructions.
This allows high performance and is the main reason to support machine level integers.
;Definition:
An integer overflow happens when the result of a computation does not fit into the fixed size integer.
The result can be too small or too big to be representable in the fixed size integer.
;Task:
When a language has fixed size integer types, create a program that
does arithmetic computations for the fixed size integers of the language.
These computations must be done such that the result would overflow.
The program should demonstrate what the following expressions do.
For 32-bit signed integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit signed integer
|-
| -(-2147483647-1)
| 2147483648
|-
| 2000000000 + 2000000000
| 4000000000
|-
| -2147483647 - 2147483647
| -4294967294
|-
| 46341 * 46341
| 2147488281
|-
| (-2147483647-1) / -1
| 2147483648
|}
For 64-bit signed integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit signed integer
|-
| -(-9223372036854775807-1)
| 9223372036854775808
|-
| 5000000000000000000+5000000000000000000
| 10000000000000000000
|-
| -9223372036854775807 - 9223372036854775807
| -18446744073709551614
|-
| 3037000500 * 3037000500
| 9223372037000250000
|-
| (-9223372036854775807-1) / -1
| 9223372036854775808
|}
For 32-bit unsigned integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit unsigned integer
|-
| -4294967295
| -4294967295
|-
| 3000000000 + 3000000000
| 6000000000
|-
| 2147483647 - 4294967295
| -2147483648
|-
| 65537 * 65537
| 4295098369
|}
For 64-bit unsigned integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit unsigned integer
|-
| -18446744073709551615
| -18446744073709551615
|-
| 10000000000000000000 + 10000000000000000000
| 20000000000000000000
|-
| 9223372036854775807 - 18446744073709551615
| -9223372036854775808
|-
| 4294967296 * 4294967296
| 18446744073709551616
|}
;Notes:
:* When the integer overflow does trigger an exception show how the exception is caught.
:* When the integer overflow produces some value, print it.
:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.
:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.
:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.
:* 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.
| assert(math.type~=nil, "Lua 5.3+ required for this test.")
minint, maxint = math.mininteger, math.maxinteger
print("min, max int64 = " .. minint .. ", " .. maxint)
print("min-1 underflow = " .. (minint-1) .. " equals max? " .. tostring(minint-1==maxint))
print("max+1 overflow = " .. (maxint+1) .. " equals min? " .. tostring(maxint+1==minint)) |
Integer sequence | Lua | 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.
An 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.
If 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.
| i = 1
-- in the event that the number inadvertently wraps around,
-- stop looping - this is unlikely with Lua's default underlying
-- number type (double), but on platform without double
-- the C type used for numbers can be changed
while i > 0 do
print( i )
i = i + 1
end
|
Inverted syntax | Lua | '''Inverted syntax with conditional expressions'''
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumbrella=true IF raining=true
'''Inverted syntax with assignment'''
In traditional syntax, assignments are usually expressed with the variable appearing before the expression:
a = 6
In inverted syntax, the expression appears before the variable:
6 = a
'''Task'''
The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.
| a = {1,3,5,4,2} -- a "plain" table
table.sort(a) -- library method passing a as param
print(table.concat(a)) -- and again --> "12345"
b = {1,3,5,4,2} -- a "plain" table, so far..
setmetatable(b, {__index=table}) -- ..but now "meta-decorated"
b:sort() -- syntax sugar passes b as "self"
print(b:concat()) -- and again --> "12345" |
Isqrt (integer square root) of X | Lua from C | Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a
real non-negative number.
Often '''X''' is actually a non-negative integer.
For the purposes of this task, '''X''' can be an integer or a real number, but if it
simplifies things in your computer programming language, assume it's an integer.
One of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or
primes) up to the
X of that
integer, either to find the factors of that integer, or to determine primality.
An alternative method for finding the '''Isqrt''' of a number is to
calculate: floor( sqrt(X) )
::* where '''sqrt''' is the square root function for non-negative real numbers, and
::* where '''floor''' is the floor function for real numbers.
If the hardware supports the computation of (real) square roots, the above method might be a faster method for
small numbers that don't have very many significant (decimal) digits.
However, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support.
;Pseudo-code using quadratic residue:
For this task, the integer square root of a non-negative number will be computed using a version
of ''quadratic residue'', which has the advantage that no ''floating point'' calculations are
used, only integer arithmetic.
Furthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions.
The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.
Pseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers):
q <-- 1 /*initialize Q to unity. */
/*find a power of 4 that's greater than X.*/
perform while q <= x /*perform while Q <= X. */
q <-- q * 4 /*multiply Q by four. */
end /*perform*/
/*Q is now greater than X.*/
z <-- x /*set Z to the value of X.*/
r <-- 0 /*initialize R to zero. */
perform while q > 1 /*perform while Q > unity. */
q <-- q / 4 /*integer divide by four. */
t <-- z - r - q /*compute value of T. */
r <-- r / 2 /*integer divide by two. */
if t >= 0 then do
z <-- t /*set Z to value of T. */
r <-- r + q /*compute new value of R. */
end
end /*perform*/
/*R is now the Isqrt(X). */
/* Sidenote: Also, Z is now the remainder after square root (i.e. */
/* R^2 + Z = X, so if Z = 0 then X is a perfect square). */
Another version for the (above) 1st '''perform''' is:
perform until q > X /*perform until Q > X. */
q <-- q * 4 /*multiply Q by four. */
end /*perform*/
Integer square roots of some values:
Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9
Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10
Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10
Isqrt( 3) is 1 Isqrt(63) is 7
Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10
Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11
Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11
Isqrt( 7) is 2 Isqrt(67) is 8
Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11
Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12
Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12
;Task:
Compute and show all output here (on this page) for:
::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format.
::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format.
::* use commas in the displaying of larger numbers.
You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.
If your computer programming language only supports smaller integers, show what you can.
;Related tasks:
:* sequence of non-squares
:* integer roots
:* square root by hand
| function isqrt(x)
local q = 1
local r = 0
while q <= x do
q = q << 2
end
while q > 1 do
q = q >> 2
local t = x - r - q
r = r >> 1
if t >= 0 then
x = t
r = r + q
end
end
return r
end
print("Integer square root for numbers 0 to 65:")
for n=0,65 do
io.write(isqrt(n) .. ' ')
end
print()
print()
print("Integer square roots of oddd powers of 7 from 1 to 21:")
print(" n | 7 ^ n | isqrt(7 ^ n)")
local p = 7
local n = 1
while n <= 21 do
print(string.format("%2d | %18d | %12d", n, p, isqrt(p)))
----------------------
n = n + 2
p = p * 49
end |
Iterated digits squaring | Lua | 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:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))
>>> [iterate(x) for x in xrange(1, 20)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]
;Task:
: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.
Or, for much less credit - (showing that your algorithm and/or language is slow):
: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.
This problem derives from the Project Euler problem 92.
For a quick algorithm for this task see the talk page
;Related tasks:
* [[Combinations with repetitions]]
* [[Digital root]]
* [[Digital root/Multiplicative digital root]]
| squares = {}
for i = 0, 9 do
for j = 0, 9 do
squares[i * 10 + j] = i * i + j * j
end
end
for i = 1, 99 do
for j = 0, 99 do
squares[i * 100 + j] = squares[i] + squares[j]
end
end
function sum_squares(n)
if n < 9999.5 then
return squares[n]
else
local m = math.floor(n / 10000)
return squares[n - 10000 * m] + sum_squares(m)
end
end
memory = {}
function calc_1_or_89(n)
local m = {}
n = memory[n] or n
while n ~= 1 and n ~= 89 do
n = memory[n] or sum_squares(n)
table.insert(m, n)
end
for _, i in pairs(m) do
memory[i] = n
end
return n
end
counter = 0
for i = 1, 100000000 do
if calc_1_or_89(i) == 89 then
counter = counter + 1
end
end
print(counter) |
JSON | Lua | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| local json = require("json")
local json_data = [=[[
42,
3.14159,
[ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ],
{ "H": 1, "He": 2, "X": null, "Li": 3 },
null,
true,
false
]]=]
print("Original JSON: " .. json_data)
local data = json.decode(json_data)
json.util.printValue(data, 'Lua')
print("JSON re-encoded: " .. json.encode(data))
local data = {
42,
3.14159,
{
2, 4, 8, 16, 32, 64,
"apples",
"bananas",
"cherries"
},
{
H = 1,
He = 2,
X = json.util.null(),
Li = 3
},
json.util.null(),
true,
false
}
print("JSON from new Lua data: " .. json.encode(data)) |
Jewels and stones | Lua from C | Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.
The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.
Note that:
:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered.
:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.
:# The parameters do not need to have exactly the same names.
:# Validating the arguments is unnecessary.
So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3.
This task was inspired by this problem.
| function count_jewels(s, j)
local count = 0
for i=1,#s do
local c = s:sub(i,i)
if string.match(j, c) then
count = count + 1
end
end
return count
end
print(count_jewels("aAAbbbb", "aA"))
print(count_jewels("ZZ", "z")) |
Julia set | Lua | Task
Generate and draw a Julia set.
;Related tasks
* Mandelbrot Set
| local cmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "$", "@" }
for y = -1.0, 1.0, 0.05 do
for x = -1.5, 1.5, 0.025 do
local zr, zi, i = x, y, 0
while i < 100 do
zr, zi = zr*zr - zi*zi - 0.79, zr * zi * 2 + 0.15
if (zr*zr + zi*zi > 4) then break else i = i + 1 end
end
io.write(cmap[math.floor(i/10)])
end
print()
end |
Jump anywhere | Lua | 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.
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For 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.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
This 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!
* Some languages can ''go to'' any global label in a program.
* Some languages can break multiple function calls, also known as ''unwinding the call stack''.
* 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).
These jumps are not all alike.
A simple ''goto'' never touches the call stack.
A continuation saves the call stack, so you can continue a function call after it ends.
;Task:
Use your language to demonstrate the various types of jumps that it supports.
Because the possibilities vary by language, this task is not specific.
You have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
| -- Forward jump
goto skip_print
print "won't print"
::skip_print::
-- Backward jump
::loop::
print "infinite loop"
goto loop
-- Labels follow the same scoping rules as local variables, but with no equivalent of upvalues
goto next
do
::next:: -- not visible to above goto
print "won't print"
end
::next:: -- goto actually jumps here
-- goto cannot jump into or out of a function
::outside::
function nope () goto outside end -- error: no visible label 'outside' for <goto> at line 2
goto inside
function nope () ::inside:: end -- error: no visible label 'inside' for <goto> at line 1
-- Convenient for breaking out of nested loops
for i = 1, 10 do
for j = 1, 10 do
for k = 1, 10 do
if i^2 + j^2 == k^2 then
print(("found: i=%d j=%d k=%d"):format(i, j, k))
goto exit
end
end
end
end
print "not found"
::exit:: |
Kaprekar numbers | Lua | A positive integer is a Kaprekar number if:
* It is '''1''' (unity)
* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
;Example Kaprekar numbers:
* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.
* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....
;Example process:
10000 (1002) splitting from left to right:
* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.
* 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.
;Task:
Generate and show all Kaprekar numbers less than 10,000.
;Extra credit:
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.
;Extra extra credit:
The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers);
if you can, show that Kaprekar numbers exist in other bases too.
For this purpose, do the following:
* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);
* Display each of them in base 10 representation;
* 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.
For 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
;Reference:
* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version
;Related task:
* [[Casting out nines]]
| -- Return length of an integer without string conversion
function numLength (n)
local length = 0
repeat
n = math.floor(n / 10)
length = length + 1
until n == 0
return length
end
-- Return a boolean indicating whether n is a Kaprekar number
function isKaprekar (n)
if n == 1 then return true end
local nSquared, a, b = n * n
for splitPoint = 1, numLength(nSquared) - 1 do
a = math.floor(nSquared / 10^splitPoint)
b = nSquared % 10^splitPoint
if a > 0 and b > 0 and a + b == n then return true end
end
return false
end
-- Main task
for n = 1, 10^4 do
if isKaprekar(n) then io.write(n .. " ") end
end
-- Extra credit
local count = 0
for n = 1, 10^6 do
if isKaprekar(n) then count = count + 1 end
end
print("\nThere are " .. count .. " Kaprekar numbers under one million.") |
Kernighans large earthquake problem | Lua | Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.
;Problem:
You 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.
Example lines from the file would be lines like:
8/27/1883 Krakatoa 8.8
5/18/1980 MountStHelens 7.6
3/13/2009 CostaRica 5.1
;Task:
* Create a program or script invocation to find all the events with magnitude greater than 6
* Assuming an appropriate name e.g. "data.txt" for the file:
:# Either: Show how your program is invoked to process a data file of that name.
:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
| -- arg[1] is the first argument provided at the command line
for line in io.lines(arg[1] or "data.txt") do -- use data.txt if arg[1] is nil
magnitude = line:match("%S+$")
if tonumber(magnitude) > 6 then print(line) end
end |
Knight's tour | Lua | Task
Problem: 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.
Input 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.
Input: starting square
Output: move sequence
;Related tasks
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| N = 8
moves = { {1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2} }
function Move_Allowed( board, x, y )
if board[x][y] >= 8 then return false end
local new_x, new_y = x + moves[board[x][y]+1][1], y + moves[board[x][y]+1][2]
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
return false
end
board = {}
for i = 1, N do
board[i] = {}
for j = 1, N do
board[i][j] = 0
end
end
x, y = 1, 1
lst = {}
lst[1] = { x, y }
repeat
if Move_Allowed( board, x, y ) then
board[x][y] = board[x][y] + 1
x, y = x+moves[board[x][y]][1], y+moves[board[x][y]][2]
lst[#lst+1] = { x, y }
else
if board[x][y] >= 8 then
board[x][y] = 0
lst[#lst] = nil
if #lst == 0 then
print "No solution found."
os.exit(1)
end
x, y = lst[#lst][1], lst[#lst][2]
end
board[x][y] = board[x][y] + 1
end
until #lst == N^2
last = lst[1]
for i = 2, #lst do
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] ) )
last = lst[i]
end |
Koch curve | Lua | Draw a Koch curve. See details: Koch curve
| local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
function Bitmap:render()
for y = 1, self.height do
print(table.concat(self.pixels[y]))
end
end
function Bitmap:drawKochPath(path, x, y, angle, speed, color)
local rules = {
["+"] = function() angle = angle + pi/3 end,
["-"] = function() angle = angle - pi/3 end,
["F"] = function()
local nx, ny = x+speed*cos(angle), y+speed*sin(angle)
self:line(floor(x*2+0.5), floor(y+0.5), floor(nx*2+0.5), floor(ny+0.5), color)
x, y = nx, ny
end
}
path:gsub("(.)", function(c) rules[c]() end)
end
function LSystem(axiom, rules, reps)
for i = 1, reps do
axiom = axiom:gsub("(.)", function(c) return rules[c] or c end)
end
return axiom
end
function KochPath(reps) return LSystem("F--F--F--", { F = "F+F--F+F" }, reps) end
demos = {
{ n=0, w= 11, h= 6, x=1, y= 4 },
{ n=1, w= 22, h=14, x=1, y= 9 },
{ n=2, w= 60, h=34, x=1, y=24 },
{ n=3, w=168, h=96, x=1, y=71 }
}
for _,d in ipairs(demos) do
bitmap = Bitmap(d.w, d.h)
bitmap:clear(".")
bitmap:drawKochPath(KochPath(d.n), d.x, d.y, 0, 3, "@")
bitmap:render()
print()
end |
Kolakoski sequence | Lua from C | The natural numbers, (excluding zero); with the property that:
: ''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''.
;Example:
This is ''not'' a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2,...
Its 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:
: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...
The above gives the RLE of:
2, 3, 1, 2, 1, ...
The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.
;Creating a Kolakoski sequence:
Lets 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,....
# We start the sequence s with the first item from the cycle c: 1
# 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.
We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.
We started s with 1 and therefore s[k] states that it should appear only the 1 time.
Increment k
Get the next item from c and append it to the end of sequence s. s will then become: 1, 2
k 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
Increment k
Append the next item from the cycle to the list: 1, 2,2, 1
k 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
increment k
...
'''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.
;Task:
# 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.
# 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.
# 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).
# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 20 members of the sequence generated from (2, 1)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)
# Check the sequence againt its RLE.
(There are rules on generating Kolakoski sequences from this method that are broken by the last example)
| function next_in_cycle(c,length,index)
local pos = index % length
return c[pos]
end
function kolakoski(c,s,clen,slen)
local i = 0
local k = 0
while true do
s[i] = next_in_cycle(c,clen,k)
if s[k] > 1 then
for j=1,s[k]-1 do
i = i + 1
if i == slen then
return nil
end
s[i] = s[i - 1]
end
end
i = i + 1
if i == slen then
return nil
end
k = k + 1
end
return nil
end
function possible_kolakoski(s,length)
local j = 0
local prev = s[0]
local count = 1
local rle = {}
local result = "True"
for i=0,length do
rle[i] = 0
end
for i=1,length-1 do
if s[i] == prev then
count = count + 1
else
rle[j] = count
j = j + 1
count = 1
prev = s[i]
end
end
-- no point adding the final 'count' to rle as we're not going to compare it anyway
for i=0,j-1 do
if rle[i] ~= s[i] then
result = "False"
break
end
end
return result
end
function print_array(a)
io.write("[")
for i=0,#a do
if i>0 then
io.write(", ")
end
io.write(a[i])
end
io.write("]")
end
-- main
local c0 = {[0]=1, [1]=2}
local c1 = {[0]=2, [1]=1}
local c2 = {[0]=1, [1]=3, [2]=1, [3]=2}
local c3 = {[0]=1, [1]=3, [2]=2, [3]=1}
local cs = {[0]=c0, [1]=c1, [2]=c2, [3]=c3}
local clens = {[0]=2, [1]=2, [2]=4, [3]=4}
local slens = {[0]=20, [1]=20, [2]=30, [3]=30}
for i=0,3 do
local clen = clens[i]
local slen = slens[i]
local s = {}
for j=0,slen-1 do
s[j] = 0
end
kolakoski(cs[i],s,clen,slen)
io.write(string.format("First %d members of the sequence generated by ", slen))
print_array(cs[i])
print(":")
print_array(s)
print()
local p = possible_kolakoski(s,slen)
print(string.format("Possible Kolakoski sequence? %s", p))
print()
end |
Kosaraju | Lua from C++ | {{wikipedia|Graph}}
Kosaraju'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.
For this task consider the directed graph with these connections:
0 -> 1
1 -> 2
2 -> 0
3 -> 1, 3 -> 2, 3 -> 4
4 -> 3, 4 -> 5
5 -> 2, 5 -> 6
6 -> 5
7 -> 4, 7 -> 6, 7 -> 7
And report the kosaraju strongly connected component for each node.
;References:
* The article on Wikipedia.
| function write_array(a)
io.write("[")
for i=0,#a do
if i>0 then
io.write(", ")
end
io.write(tostring(a[i]))
end
io.write("]")
end
function kosaraju(g)
-- 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.
local size = #g
local vis = {}
for i=0,size do
-- all false by default
vis[i] = false
end
local l = {}
for i=0,size do
-- all zero by default
l[i] = 0
end
local x = size+1 -- index for filling l in reverse order
local t = {} -- transpose graph
-- Recursive subroutine 'visit'
function visit(u)
if not vis[u] then
vis[u] = true
for i=0,#g[u] do
local v = g[u][i]
visit(v)
if t[v] then
local a = t[v]
a[#a+1] = u
else
t[v] = {[0]=u}
end
end
x = x - 1
l[x] = u
end
end
-- 2. For each vertex u of the graph do visit(u)
for i=0,#g do
visit(i)
end
local c = {}
for i=0,size do
-- used for component assignment
c[i] = 0
end
-- Recursive subroutine 'assign'
function assign(u, root)
if vis[u] then -- repurpose vis to mean 'unassigned'
vis[u] = false
c[u] = root
for i=0,#t[u] do
local v = t[u][i]
assign(v, root)
end
end
end
-- 3: For each element u of l in order, do assign(u, u)
for i=0,#l do
local u = l[i]
assign(u, u)
end
return c
end
-- main
local g = {
[0]={[0]=1},
[1]={[0]=2},
[2]={[0]=0},
[3]={[0]=1, [1]=2, [2]=4},
[4]={[0]=3, [1]=5},
[5]={[0]=2, [1]=6},
[6]={[0]=5},
[7]={[0]=4, [1]=6, [2]=7},
}
write_array(kosaraju(g))
print() |
Largest int from concatenated ints | Lua from Python | 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.
Use the following two sets of integers as tests and show your program output here.
:::::* {1, 34, 3, 98, 9, 76, 45, 4}
:::::* {54, 546, 548, 60}
;Possible algorithms:
# A solution could be found by trying all combinations and return the best.
# 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.
# 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.
;See also:
* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?
* Constructing the largest number possible by rearranging a list
| function icsort(numbers)
table.sort(numbers,function(x,y) return (x..y) > (y..x) end)
return numbers
end
for _,numbers in pairs({{1, 34, 3, 98, 9, 76, 45, 4}, {54, 546, 548, 60}}) do
print(('Numbers: {%s}\n Largest integer: %s'):format(
table.concat(numbers,","),table.concat(icsort(numbers))
))
end |
Largest number divisible by its digits | Lua | Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the
(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits.
;Example:
'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.
Note that the digit zero (0) can not be in the number as integer division by zero is undefined.
The digits must all be unique so a base ten number will have at most '''9''' digits.
Feel 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.)
;Stretch goal:
Do the same thing for hexadecimal.
;Related tasks:
:* gapful numbers.
:* palindromic gapful numbers.
;Also see:
:* The OEIS sequence: A115569: Lynch-Bell numbers.
| function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
end
a[r + 1] = 1
t = math.floor(t / 10)
end
return true
end
for i=9999999999,0,-1 do
if isDivisible(i) then
print(i)
break
end
end
|
Last Friday of each month | Lua | Write a program or a script that returns the date of the last Fridays 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).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28
;Related tasks
* [[Five weekends]]
* [[Day of the week]]
* [[Find the last Sunday of each month]]
| function isLeapYear (y)
return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0
end
function dayOfWeek (y, m, d)
local t = os.time({year = y, month = m, day = d})
return os.date("%A", t)
end
function lastWeekdays (wday, year)
local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if isLeapYear(year) then monthLength[2] = 29 end
for month = 1, 12 do
day = monthLength[month]
while dayOfWeek(year, month, day) ~= wday do day = day - 1 end
print(year .. "-" .. month .. "-" .. day)
end
end
lastWeekdays("Friday", tonumber(arg[1])) |
Last letter-first letter | Lua | 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.
For example, with "animals" as the category,
Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
...
;Task:
Take 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.
No Pokemon name is to be repeated.
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask
Extra brownie points for dealing with the full list of 646 names.
| -- BUILDING:
pokemon = [[
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask]]
words, inits, succs = {}, {}, {}
for word in pokemon:gmatch("%S+") do
table.insert(words, word)
local ch = word:sub(1,1)
inits[ch] = inits[ch] or {}
table.insert(inits[ch], word)
end
for _,word in pairs(words) do
succs[word] = {}
local ch = word:sub(-1,-1)
if inits[ch] then
for _,succ in pairs(inits[ch]) do
if succ~=word then
table.insert(succs[word],succ)
end
end
end
end
-- SEARCHING:
function expand(list, used, answer)
local word = list[#list]
for _,succ in ipairs(succs[word]) do
if not used[succ] then
used[succ] = true
list[#list+1] = succ
if #list == answer.len then
local perm = table.concat(list," ")
answer.perms[perm] = perm
answer.num = answer.num + 1
elseif #list > answer.len then
answer.len = #list
local perm = table.concat(list," ")
answer.perms = {[perm] = perm}
answer.num = 1
end
expand(list, used, answer)
list[#list] = nil
used[succ] = nil
end
end
end
answers = {}
for _,word in ipairs(words) do
local answer = { word=word, len=0, num=0, perms={} }
answers[#answers+1] = answer
expand({word}, {[word]=true}, answer)
end
-- REPORTING:
table.sort(answers, function(a,b) return a.len<b.len or (a.len==b.len and a.word<b.word) end)
print("first word length count example")
print("---------- ------ ----- -------...")
for _,answer in pairs(answers) do
local perm = next(answer.perms) or ""
print(string.format("%10s %6d %5d %s", answer.word, answer.len, answer.num, perm))
end |
Law of cosines - triples | Lua | The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(g) = C2
;Specific angles:
For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation":
A2 + B2 = C2
For an angle of '''60o''' this becomes the less familiar equation:
A2 + B2 - AB = C2
And finally for an angle of '''120o''' this becomes the equation:
A2 + B2 + AB = C2
;Task:
* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.
* Restrain all sides to the integers '''1..13''' inclusive.
* Show how many results there are for each of the three angles mentioned above.
* Display results on this page.
Note: Triangles with the same length sides but different order are to be treated as the same.
;Optional Extra credit:
* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.
;Related Task
* [[Pythagorean triples]]
;See also:
* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
| function solve(angle, maxlen, filter)
local squares, roots, solutions = {}, {}, {}
local cos2 = ({[60]=-1,[90]=0,[120]=1})[angle]
for i = 1, maxlen do squares[i], roots[i^2] = i^2, i end
for a = 1, maxlen do
for b = a, maxlen do
local lhs = squares[a] + squares[b] + cos2*a*b
local c = roots[lhs]
if c and (not filter or filter(a,b,c)) then
solutions[#solutions+1] = {a=a,b=b,c=c}
end
end
end
print(angle.."° on 1.."..maxlen.." has "..#solutions.." solutions")
if not filter then
for i,v in ipairs(solutions) do print("",v.a,v.b,v.c) end
end
end
solve(90, 13)
solve(60, 13)
solve(120, 13)
function fexcr(a,b,c) return a~=b or b~=c end
solve(60, 10000, fexcr) -- extra credit
solve(90, 10000, fexcr) -- more extra credit
solve(120, 10000, fexcr) -- even more extra credit |
Least common multiple | Lua | Compute the least common multiple (LCM) of two integers.
Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors.
;Example:
The least common multiple of '''12''' and '''18''' is '''36''', because:
:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and
:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and
:* there is no positive integer less than '''36''' that has both factors.
As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.
One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.
If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.
:::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)}
One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.
;Related task
:* greatest common divisor.
;See also:
* MathWorld entry: Least Common Multiple.
* Wikipedia entry: Least common multiple.
| function gcd( m, n )
while n ~= 0 do
local q = m
m = n
n = q % n
end
return m
end
function lcm( m, n )
return ( m ~= 0 and n ~= 0 ) and m * n / gcd( m, n ) or 0
end
print( lcm(12,18) ) |
Left factorials | Lua | '''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums'';
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations:
:::::::* !''n''`
:::::::* !''n''
:::::::* ''n''!
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)
This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':
::::: !n = \sum_{k=0}^{n-1} k!
:::: where
::::: !0 = 0
;Task
Display the left factorials for:
* zero through ten (inclusive)
* 20 through 110 (inclusive) by tens
Display the length (in decimal digits) of the left factorials for:
* 1,000 through 10,000 (inclusive), by thousands.
;Also see:
* The OEIS entry: A003422 left factorials
* The MathWorld entry: left factorial
* The MathWorld entry: factorial sums
* The MathWorld entry: subfactorial
;Related task:
* permutations/derangements (subfactorials)
| -- Lua bindings for GNU bc
require("bc")
-- Return table of factorials from 0 to n
function facsUpTo (n)
local f, fList = bc.number(1), {}
fList[0] = 1
for i = 1, n do
f = bc.mul(f, i)
fList[i] = f
end
return fList
end
-- Return left factorial of n
function leftFac (n)
local sum = bc.number(0)
for k = 0, n - 1 do sum = bc.add(sum, facList[k]) end
return bc.tostring(sum)
end
-- Main procedure
facList = facsUpTo(10000)
for i = 0, 10 do print("!" .. i .. " = " .. leftFac(i)) end
for i = 20, 110, 10 do print("!" .. i .. " = " .. leftFac(i)) end
for i = 1000, 10000, 1000 do
print("!" .. i .. " contains " .. #leftFac(i) .. " digits")
end |
Levenshtein distance | Lua | {{Wikipedia}}
In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.
;Example:
The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
::# '''k'''itten '''s'''itten (substitution of 'k' with 's')
::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')
::# sittin sittin'''g''' (insert 'g' at the end).
''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''.
''The distance between two strings is same as that when both strings are reversed.''
;Task:
Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting".
;Related task:
* [[Longest common subsequence]]
| function leven(s,t)
if s == '' then return t:len() end
if t == '' then return s:len() end
local s1 = s:sub(2, -1)
local t1 = t:sub(2, -1)
if s:sub(0, 1) == t:sub(0, 1) then
return leven(s1, t1)
end
return 1 + math.min(
leven(s1, t1),
leven(s, t1),
leven(s1, t )
)
end
print(leven("kitten", "sitting"))
print(leven("rosettacode", "raisethysword")) |
List rooted trees | Lua from Java | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81.
;Task:
Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| tree_list = {}
offset = {}
function init()
for i=1,32 do
if i == 2 then
table.insert(offset, 1)
else
table.insert(offset, 0)
end
end
end
function append(t)
local v = 1 | (t << 1)
table.insert(tree_list, v)
end
function show(t, l)
while l > 0 do
l = l - 1
if (t % 2) == 1 then
io.write('(')
else
io.write(')')
end
t = t >> 1
end
end
function listTrees(n)
local i = offset[n]
while i < offset[n + 1] do
show(tree_list[i + 1], n * 2)
print()
i = i + 1
end
end
function assemble(m, t, sl, pos, rem)
if rem == 0 then
append(t)
return
end
local pp = pos
local ss = sl
if sl > rem then
ss = rem
pp = offset[ss]
elseif pp >= offset[ss + 1] then
ss = ss - 1
if ss == 0 then
return
end
pp = offset[ss]
end
assemble(n, t << (2 * ss) | tree_list[pp + 1], ss, pp, rem - ss)
assemble(n, t, ss, pp + 1, rem)
end
function makeTrees(n)
if offset[n + 1] ~= 0 then
return
end
if n > 0 then
makeTrees(n - 1)
end
assemble(n, 0, n - 1, offset[n - 1], n - 1)
offset[n + 1] = #tree_list
end
function test(n)
append(0)
makeTrees(n)
print(string.format("Number of %d-trees: %d", n, offset[n+1] - offset[n]))
listTrees(n)
end
init()
test(5) |
Long literals, with continuations | Lua | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''
To make computer programming languages comparable, the statement widths should be
restricted to less than '''81''' bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if ''not''
in column one.
The list ''may'' have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program ''will'' be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the ''clause length'' of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
;Task:
:* Write a computer program (by whatever name) to contain a list of the known elements.
:* The program should eventually contain a long literal of words (the elements).
:* The literal should show how one could create a long list of blank-delineated words.
:* The "final" (stored) list should only have a single blank between elements.
:* Try to use the most idiomatic approach(es) in creating the final list.
:* Use continuation if possible, and/or show alternatives (possibly using concatenation).
:* Use a program comment to explain what the continuation character is if it isn't obvious.
:* The program should contain a variable that has the date of the last update/revision.
:* The program, when run, should display with verbiage:
:::* The last update/revision date (and should be unambiguous).
:::* The number of chemical elements in the list.
:::* The name of the highest (last) element name.
Show all output here, on this page.
| revised = "February 2, 2021"
-- the long literal string is delimited by double square brackets: [[...]]
-- each word must be separated by at least one whitespace character
-- additional whitespace may optionally be used to improve readability
-- (starting column does not matter, clause length is more than adequate)
longliteral = [[
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
fluorine neon sodium magnesium
aluminum silicon phosphorous sulfur
chlorine argon potassium calcium
scandium titanium vanadium chromium
manganese iron cobalt nickel
copper zinc gallium germanium
arsenic selenium bromine krypton
rubidium strontium yttrium zirconium
niobium molybdenum technetium ruthenium
rhodium palladium silver cadmium
indium tin antimony tellurium
iodine xenon cesium barium
lanthanum cerium praseodymium neodymium
promethium samarium europium gadolinium
terbium dysprosium holmium erbium
thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium
iridium platinum gold mercury
thallium lead bismuth polonium
astatine radon francium radium
actinium thorium protactinium uranium
neptunium plutonium americium curium
berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium
dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium
nihonium flerovium moscovium livermorium
tennessine oganesson
]]
-- the task requires the "final list" as single-space-between string version
-- (a more idiomatic overall approach would be to directly split into a table)
finallist = longliteral:gsub("%s+"," ")
elements = {}
-- longliteral could be used here DIRECTLY instead of using finallist:
for name in finallist:gmatch("%w+") do elements[#elements+1]=name end
print("revised date: " .. revised)
print("# elements : " .. #elements)
print("last element: " .. elements[#elements])
-- then, if still required, produce a single-space-between string version:
--finallist = table.concat(elements," ") |
Longest common subsequence | Lua | '''Introduction'''
Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.
The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.
Let ''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.
An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.
The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.
Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.
We 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''.
Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.
A 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.
A 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].
Every 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''.
According 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.
'''Background'''
Where 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.
The 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.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In 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.
A 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'').
'''Note'''
[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').
'''Legend'''
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of matches (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet S of distinct symbols in A + B
'''References'''
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, ''pp.'' 275-281]
'''Examples'''
The sequences "1234" and "1224533324" have an LCS of "1234":
'''1234'''
'''12'''245'''3'''332'''4'''
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
'''t'''hi'''si'''sa'''test'''
'''t'''e'''s'''t'''i'''ng123'''test'''ing
In 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.
For more information on this problem please see Wikipedia.
| function LCS( a, b )
if #a == 0 or #b == 0 then
return ""
elseif string.sub( a, -1, -1 ) == string.sub( b, -1, -1 ) then
return LCS( string.sub( a, 1, -2 ), string.sub( b, 1, -2 ) ) .. string.sub( a, -1, -1 )
else
local a_sub = LCS( a, string.sub( b, 1, -2 ) )
local b_sub = LCS( string.sub( a, 1, -2 ), b )
if #a_sub > #b_sub then
return a_sub
else
return b_sub
end
end
end
print( LCS( "thisisatest", "testing123testing" ) ) |
Longest increasing subsequence | Lua | Calculate and show here a longest increasing subsequence of the list:
:\{3, 2, 6, 4, 5, 1\}
And of the list:
:\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\}
Note that a list may have more than one subsequence that is of the maximum length.
;Ref:
# Dynamic Programming #1: Longest Increasing Subsequence on YouTube
# An efficient solution can be based on Patience sorting.
| function buildLIS(seq)
local piles = { { {table.remove(seq, 1), nil} } }
while #seq>0 do
local x=table.remove(seq, 1)
for j=1,#piles do
if piles[j][#piles[j]][1]>x then
table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])})
break
elseif j==#piles then
table.insert(piles, {{x, #piles[j]}})
end
end
end
local t={}
table.insert(t, piles[#piles][1][1])
local p=piles[#piles][1][2]
for i=#piles-1,1,-1 do
table.insert(t, piles[i][p][1])
p=piles[i][p][2]
end
table.sort(t)
print(unpack(t))
end
buildLIS({3,2,6,4,5,1})
buildLIS({0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15})
|
MAC vendor lookup | Lua | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
;Task:
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A 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.
Many 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.
'''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''
| -- Requires LuaSocket extension by Lua
-- Created by James A. Donnell Jr.
-- www.JamesDonnell.com
local baseURL = "http://api.macvendors.com/"
local function lookup(macAddress)
http = require "socket.http"
result, statuscode, content = http.request(baseURL .. macAddress)
return result
end
local macAddress = "FC-A1-3E-2A-1C-33"
print(lookup(macAddress)) |
Mad Libs | Lua | {{wikipedia}}
Mad 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.
;Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
went for a walk in the park.
found a . decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
| print("Enter a multi-line story (finish with blank line):")
dict, story, line = {}, "", io.read()
while #line>0 do story=story..line.."\n" line=io.read() end
story = story:gsub("(%<.-%>)", function(what)
if dict[what] then return dict[what] end
io.write("Please enter a " .. what .. ": ")
dict[what] = io.read()
return dict[what]
end)
print("\n"..story) |
Magic 8-ball | Lua | Create Magic 8-Ball.
See details at: Magic 8-Ball.
| math.randomseed(os.time())
answers = {
"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.",
"As I see it, yes.", "Most likely.", "Outlook good.", "Signs point to yes.", "Yes.",
"Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
"Don't bet on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."
}
while true do
io.write("Q: ")
question = io.read()
print("A: "..answers[math.random(#answers)])
end |
Magic squares of doubly even order | Lua | 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'').
A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12''').
This means that the subsquares also have an even size, which plays a role in the construction.
{| 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%"
|-
|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''
|-
|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''
|-
|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''
|-
|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''
|-
|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''
|-
|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''
|-
|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''
|-
|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''
|}
;Task
Create a magic square of '''8 x 8'''.
;Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of singly even order]]
;See also:
* Doubly Even Magic Squares (1728.org)
| For all three kinds of Magic Squares(Odd, singly and doubly even)<br />
See [[Magic_squares/Lua]].
|
Magic squares of odd order | Lua | 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'').
The numbers are usually (but not always) the first '''N'''2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.
{| 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%"
|-
| '''8''' || '''1''' || '''6'''
|-
| '''3''' || '''5''' || '''7'''
|-
| '''4''' || '''9''' || '''2'''
|}
;Task
For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here.
Optionally, show the ''magic number''.
You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.
; Related tasks
* [[Magic squares of singly even order]]
* [[Magic squares of doubly even order]]
; See also:
* MathWorld(tm) entry: Magic_square
* Odd Magic Squares (1728.org)
| For all three kinds of Magic Squares(Odd, singly and doubly even)<br />
See [[Magic_squares/Lua]].
|
Magic squares of singly even order | Lua | 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'').
A 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.
;Task
Create a magic square of 6 x 6.
; Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of doubly even order]]
; See also
* Singly Even Magic Squares (1728.org)
| For all three kinds of Magic Squares(Odd, singly and doubly even)<br />
See [[Magic_squares/Lua]].
|
Map range | Lua | Given two ranges:
:::* [a_1,a_2] and
:::* [b_1,b_2];
:::* then a value s in range [a_1,a_2]
:::* is linearly mapped to a value t in range [b_1,b_2]
where:
:::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)}
;Task:
Write 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.
Use this function to map values from the range [0, 10] to the range [-1, 0].
;Extra credit:
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| function map_range( a1, a2, b1, b2, s )
return b1 + (s-a1)*(b2-b1)/(a2-a1)
end
for i = 0, 10 do
print( string.format( "f(%d) = %f", i, map_range( 0, 10, -1, 0, i ) ) )
end |
Maximum triangle path sum | Lua | 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:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your 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.
;Task:
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| local triangleSmall = {
{ 55 },
{ 94, 48 },
{ 95, 30, 96 },
{ 77, 71, 26, 67 },
}
local triangleLarge = {
{ 55 },
{ 94, 48 },
{ 95, 30, 96 },
{ 77, 71, 26, 67 },
{ 97, 13, 76, 38, 45 },
{ 7, 36, 79, 16, 37, 68 },
{ 48, 7, 9, 18, 70, 26, 6 },
{ 18, 72, 79, 46, 59, 79, 29, 90 },
{ 20, 76, 87, 11, 32, 7, 7, 49, 18 },
{ 27, 83, 58, 35, 71, 11, 25, 57, 29, 85 },
{ 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55 },
{ 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23 },
{ 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42 },
{ 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72 },
{ 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36 },
{ 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52 },
{ 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15 },
{ 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 },
};
function solve(triangle)
-- Get total number of rows in triangle.
local nRows = table.getn(triangle)
-- Start at 2nd-to-last row and work up to the top.
for row = nRows-1, 1, -1 do
-- For each value in row, add the max of the 2 children beneath it.
for i = 1, row do
local child1 = triangle[row+1][i]
local child2 = triangle[row+1][i+1]
triangle[row][i] = triangle[row][i] + math.max(child1, child2)
end
end
-- The top of the triangle now holds the answer.
return triangle[1][1];
end
print(solve(triangleSmall))
print(solve(triangleLarge))
|
McNuggets problem | Lua | From Wikipedia:
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).
| function range(A,B)
return function()
return coroutine.wrap(function()
for i = A, B do coroutine.yield(i) end
end)
end
end
function filter(stream, f)
return function()
return coroutine.wrap(function()
for i in stream() do
if f(i) then coroutine.yield(i) end
end
end)
end
end
function triple(s1, s2, s3)
return function()
return coroutine.wrap(function()
for x in s1() do
for y in s2() do
for z in s3() do
coroutine.yield{x,y,z}
end
end
end
end)
end
end
function apply(f, stream)
return function()
return coroutine.wrap(function()
for T in stream() do
coroutine.yield(f(table.unpack(T)))
end
end)
end
end
function exclude(s1, s2)
local exlusions = {} for x in s1() do exlusions[x] = true end
return function()
return coroutine.wrap(function()
for x in s2() do
if not exlusions[x] then
coroutine.yield(x)
end
end
end)
end
end
function maximum(stream)
local M = math.mininteger
for x in stream() do
M = math.max(M, x)
end
return M
end
local N = 100
local A, B, C = 6, 9, 20
local Xs = filter(range(0, N), function(x) return x % A == 0 end)
local Ys = filter(range(0, N), function(x) return x % B == 0 end)
local Zs = filter(range(0, N), function(x) return x % C == 0 end)
local sum = filter(apply(function(x, y, z) return x + y + z end, triple(Xs, Ys, Zs)), function(x) return x <= N end)
print(maximum(exclude(sum, range(1, N))))
|
Middle three digits | Lua | 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.
Note: The order of the middle digits should be preserved.
Your 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:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| function middle_three(n)
if n < 0 then
n = -n
end
n = tostring(n)
if #n % 2 == 0 then
return "Error: the number of digits is even."
elseif #n < 3 then
return "Error: the number has less than 3 digits."
end
local l = math.floor(#n/2)
return n:sub(l, l+2)
end
-- test
do
local t = {123, 12345, 1234567, 987654321,
10001, -10001, -123, -100, 100, -12345, 1,
2, -1, -10, 2002, -2002, 0}
for _,n in pairs(t) do
print(n, middle_three(n))
end
end |
Mind boggling card trick | Lua | Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
; 1. Cards.
# Create a common deck of cards of 52 cards (which are half red, half black).
# Give the pack a good shuffle.
; 2. Deal from the shuffled deck, you'll be creating three piles.
# Assemble the cards face down.
## Turn up the ''top card'' and hold it in your hand.
### if the card is black, then add the ''next'' card (unseen) to the "black" pile.
### If the card is red, then add the ''next'' card (unseen) to the "red" pile.
## 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).
# Repeat the above for the rest of the shuffled deck.
; 3. Choose a random number (call it '''X''') that will be used to swap cards from the "red" and "black" piles.
# Randomly choose '''X''' cards from the "red" pile (unseen), let's call this the "red" bunch.
# Randomly choose '''X''' cards from the "black" pile (unseen), let's call this the "black" bunch.
# Put the "red" bunch into the "black" pile.
# Put the "black" bunch into the "red" pile.
# (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).
; 4. Order from randomness?
# Verify (or not) the mathematician's assertion that:
'''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.'''
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| -- support:
function T(t) return setmetatable(t, {__index=table}) end
table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end
table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end
table.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
table.clone = function(t) local s=T{} for k,v in ipairs(t) do s[k]=v end return s end
table.head = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end
table.tail = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[#t-n+i] end return s end
table.append = function(t,v) local s=t:clone() for i=1,#v do s[#s+1]=v[i] end return s end
table.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!
-- task:
function cardtrick()
-- 1.
local deck = T{}:range(52):map(function(v) return v%2==0 and "B" or "R" end):shuffle()
print("1. DECK : " .. deck:concat())
-- 2. (which guarantees the outcome)
local bpile, rpile, discs = T{}, T{}, T{}
local xpile = {B=bpile, R=rpile}
while #deck>0 do
local card, next = deck:remove(), deck:remove()
xpile[card]:insert(next)
discs:insert(card)
end
print("2. BLACK PILE: " .. bpile:concat())
print("2. RED PILE : " .. rpile:concat())
print("2. DISCARDS : " .. discs:concat())
-- 3. (which cannot change the outcome)
local x = math.random(0, math.min(#bpile, #rpile))
local btake, rtake = T{}, T{}
for i = 1, x do
btake:insert((bpile:remove(math.random(#bpile))))
rtake:insert((rpile:remove(math.random(#rpile))))
end
print("3. SWAPPING X: " .. x)
print("3. BLACK SWAP: keep:" .. bpile:concat() .. " take:" .. btake:concat())
print("3. RED SWAP : keep:" .. rpile:concat() .. " take:" .. rtake:concat())
bpile, rpile = bpile:append(rtake), rpile:append(btake)
print("3. BLACK PILE: " .. bpile:concat())
print("3. RED PILE : " .. rpile:concat())
-- 4. ("proving" that which was guaranteed earlier)
local binb, rinr = bpile:filter(function(v) return v=="B" end), rpile:filter(function(v) return v=="R" end)
print("4. BLACK PILE: contains " .. #binb .. " B's")
print("4. RED PILE : contains " .. #rinr .. " R's")
print(#binb==#rinr and "VERIFIED" or "NOT VERIFIED")
print()
end
-- demo:
math.randomseed(os.time())
for i = 1,3 do cardtrick() end |
Minimum positive multiple in base 10 using only 0 and 1 | Lua | 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.
This is simple to do, but can be challenging to do efficiently.
To 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'''".
;Task:
Write a routine to find the B10 of a given integer.
E.G.
'''n''' '''B10''' '''n''' x '''multiplier'''
1 1 ( 1 x 1 )
2 10 ( 2 x 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the '''B10''' value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find '''B10''' for:
1998, 2079, 2251, 2277
Stretch goal; find '''B10''' for:
2439, 2997, 4878
There 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.
;See also:
:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
:* How to find Minimum Positive Multiple in base 10 using only 0 and 1
| Without a bignum library, some values do not display or calculate properly
|
Minimum positive multiple in base 10 using only 0 and 1 | Lua from Ruby | 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.
This is simple to do, but can be challenging to do efficiently.
To 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'''".
;Task:
Write a routine to find the B10 of a given integer.
E.G.
'''n''' '''B10''' '''n''' x '''multiplier'''
1 1 ( 1 x 1 )
2 10 ( 2 x 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the '''B10''' value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find '''B10''' for:
1998, 2079, 2251, 2277
Stretch goal; find '''B10''' for:
2439, 2997, 4878
There 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.
;See also:
:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
:* How to find Minimum Positive Multiple in base 10 using only 0 and 1
| function array1D(n, v)
local tbl = {}
for i=1,n do
table.insert(tbl, v)
end
return tbl
end
function array2D(h, w, v)
local tbl = {}
for i=1,h do
table.insert(tbl, array1D(w, v))
end
return tbl
end
function mod(m, n)
m = math.floor(m)
local result = m % n
if result < 0 then
result = result + n
end
return result
end
function getA004290(n)
if n == 1 then
return 1
end
local arr = array2D(n, n, 0)
arr[1][1] = 1
arr[1][2] = 1
local m = 0
while true do
m = m + 1
if arr[m][mod(-10 ^ m, n) + 1] == 1 then
break
end
arr[m + 1][1] = 1
for k = 1, n - 1 do
arr[m + 1][k + 1] = math.max(arr[m][k + 1], arr[m][mod(k - 10 ^ m, n) + 1])
end
end
local r = 10 ^ m
local k = mod(-r, n)
for j = m - 1, 1, -1 do
if arr[j][k + 1] == 0 then
r = r + 10 ^ j
k = mod(k - 10 ^ j, n)
end
end
if k == 1 then
r = r + 1
end
return r
end
function test(cases)
for _,n in ipairs(cases) do
local result = getA004290(n)
print(string.format("A004290(%d) = %s = %d * %d", n, math.floor(result), n, math.floor(result / n)))
end
end
test({1, 2, 3, 4, 5, 6, 7, 8, 9})
test({95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105})
test({297, 576, 594, 891, 909, 999})
--test({1998, 2079, 2251, 2277})
--test({2439, 2997, 4878}) |
Modular arithmetic | Lua | equivalence relation called ''congruence''.
For any positive integer p called the ''congruence modulus'',
two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:
:a = b + k\,p
The corresponding set of multiplicative inverse for this task.
Addition 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.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
:f(x) = x^{100} + x + 1
You will use 13 as the congruence modulus and you will compute f(10).
It 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.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| function make(value, modulo)
local v = value % modulo
local tbl = {value=v, modulo=modulo}
local mt = {
__add = function(lhs, rhs)
if type(lhs) == "table" then
if type(rhs) == "table" then
if lhs.modulo ~= rhs.modulo then
error("Cannot add rings with different modulus")
end
return make(lhs.value + rhs.value, lhs.modulo)
else
return make(lhs.value + rhs, lhs.modulo)
end
else
error("lhs is not a table in +")
end
end,
__mul = function(lhs, rhs)
if lhs.modulo ~= rhs.modulo then
error("Cannot multiply rings with different modulus")
end
return make(lhs.value * rhs.value, lhs.modulo)
end,
__pow = function(b,p)
if p<0 then
error("p must be zero or greater")
end
local pp = p
local pwr = make(1, b.modulo)
while pp > 0 do
pp = pp - 1
pwr = pwr * b
end
return pwr
end,
__concat = function(lhs, rhs)
if type(lhs) == "table" and type(rhs) == "string" then
return "ModInt("..lhs.value..", "..lhs.modulo..")"..rhs
elseif type(lhs) == "string" and type(rhs) == "table" then
return lhs.."ModInt("..rhs.value..", "..rhs.modulo..")"
else
return "todo"
end
end
}
setmetatable(tbl, mt)
return tbl
end
function func(x)
return x ^ 100 + x + 1
end
-- main
local x = make(10, 13)
local y = func(x)
print("x ^ 100 + x + 1 for "..x.." is "..y) |
Monads/Maybe monad | lua 5.3 | Demonstrate in your programming language the following:
#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)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
#Compose the two functions with bind
A 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.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| -- None is represented by an empty table. Some is represented by any
-- array with one element. You SHOULD NOT compare maybe values with the
-- Lua operator == because it will give incorrect results. Use the
-- functions isMaybe(), isNone(), and isSome().
-- define once for efficiency, to avoid many different empty tables
local NONE = {}
local function unit(x) return { x } end
local Some = unit
local function isNone(mb) return #mb == 0 end
local function isSome(mb) return #mb == 1 end
local function isMaybe(mb) return isNone(mb) or isSome(mb) end
-- inverse of Some(), extract the value from the maybe; get(Some(x)) === x
local function get(mb) return mb[1] end
function maybeToStr(mb)
return isNone(mb) and "None" or ("Some " .. tostring(get(mb)))
end
local function bind(mb, ...) -- monadic bind for multiple functions
local acc = mb
for _, fun in ipairs({...}) do -- fun should be a monadic function
assert(type(fun) == "function")
if isNone(acc) then return NONE
else acc = fun(get(acc)) end
end
return acc
end
local function fmap(mb, ...) -- monadic fmap for multiple functions
local acc = mb
for _, fun in ipairs({...}) do -- fun should be a regular function
assert(type(fun) == "function")
if isNone(acc) then return NONE
else acc = Some(fun(get(acc))) end
end
return acc
end
-- ^^^ End of generic maybe monad functionality ^^^
--- vvv Start of example code vvv
local function time2(x) return x * 2 end
local function plus1(x) return x + 1 end
local answer
answer = fmap(Some(3), time2, plus1, time2)
assert(get(answer)==14)
answer = fmap(NONE, time2, plus1, time2)
assert(isNone(answer))
local function safeReciprocal(x)
if x ~= 0 then return Some(1/x) else return NONE end
end
local function safeRoot(x)
if x >= 0 then return Some(math.sqrt(x)) else return NONE end
end
local function safeLog(x)
if x > 0 then return Some(math.log(x)) else return NONE end
end
local function safeComputation(x)
return bind(safeReciprocal(x), safeRoot, safeLog)
end
local function map(func, table)
local result = {}
for key, val in pairs(table) do
result[key] = func(val)
end
return result
end
local inList = {-2, -1, -0.5, 0, math.exp (-1), 1, 2, math.exp (1), 3, 4, 5}
print("input:", table.concat(map(tostring, inList), ", "), "\n")
local outList = map(safeComputation, inList)
print("output:", table.concat(map(maybeToStr, outList), ", "), "\n")
|
Move-to-front algorithm | Lua | Given a symbol table of a ''zero-indexed'' array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).
The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful in some compression algorithms.
;Encoding algorithm:
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
;Decoding algorithm:
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
;Example:
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''b'''roood
| 1
| 'abcdefghijklmnopqrstuvwxyz'
|-
| b'''r'''oood
| 1 17
| 'bacdefghijklmnopqrstuvwxyz'
|-
| br'''o'''ood
| 1 17 15
| 'rbacdefghijklmnopqstuvwxyz'
|-
| bro'''o'''od
| 1 17 15 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| broo'''o'''d
| 1 17 15 0 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| brooo'''d'''
| 1 17 15 0 0 5
| 'orbacdefghijklmnpqstuvwxyz'
|}
Decoding the indices back to the original symbol order:
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''1''' 17 15 0 0 5
| b
| 'abcdefghijklmnopqrstuvwxyz'
|-
| 1 '''17''' 15 0 0 5
| br
| 'bacdefghijklmnopqrstuvwxyz'
|-
| 1 17 '''15''' 0 0 5
| bro
| 'rbacdefghijklmnopqstuvwxyz'
|-
| 1 17 15 '''0''' 0 5
| broo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 '''0''' 5
| brooo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 0 '''5'''
| broood
| 'orbacdefghijklmnpqstuvwxyz'
|}
;Task:
:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above.
:* Show the strings and their encoding here.
:* Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| -- Return table of the alphabet in lower case
function getAlphabet ()
local letters = {}
for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end
return letters
end
-- Move the table value at ind to the front of tab
function moveToFront (tab, ind)
local toMove = tab[ind]
for i = ind - 1, 1, -1 do tab[i + 1] = tab[i] end
tab[1] = toMove
end
-- Perform move-to-front encoding on input
function encode (input)
local symbolTable, output, index = getAlphabet(), {}
for pos = 1, #input do
for k, v in pairs(symbolTable) do
if v == input:sub(pos, pos) then index = k end
end
moveToFront(symbolTable, index)
table.insert(output, index - 1)
end
return table.concat(output, " ")
end
-- Perform move-to-front decoding on input
function decode (input)
local symbolTable, output = getAlphabet(), ""
for num in input:gmatch("%d+") do
output = output .. symbolTable[num + 1]
moveToFront(symbolTable, num + 1)
end
return output
end
-- Main procedure
local testCases, output = {"broood", "bananaaa", "hiphophiphop"}
for _, case in pairs(testCases) do
output = encode(case)
print("Original string: " .. case)
print("Encoded: " .. output)
print("Decoded: " .. decode(output))
print()
end |
Multi-dimensional array | Lua | For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.
It is enough to:
# State the number and extent of each index to the array.
# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.
;Task:
* State if the language supports multi-dimensional arrays in its syntax and usual implementation.
* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
* 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.
:* 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).
* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
* 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.
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
| -- Variadic, first argument is the value with which to populate the array.
function multiArray (initVal, ...)
local function copy (t)
local new = {}
for k, v in pairs(t) do
if type(v) == "table" then
new[k] = copy(v)
else
new[k] = v
end
end
return new
end
local dimensions, arr, newArr = {...}, {}
for i = 1, dimensions[#dimensions] do table.insert(arr, initVal) end
for d = #dimensions - 1, 1, -1 do
newArr = {}
for i = 1, dimensions[d] do table.insert(newArr, copy(arr)) end
arr = copy(newArr)
end
return arr
end
-- Function to print out the specific example created here
function show4dArray (a)
print("\nPrinting 4D array in 2D...")
for k, v in ipairs(a) do
print(k)
for l, w in ipairs(v) do
print("\t" .. l)
for m, x in ipairs(w) do
print("\t", m, unpack(x))
end
end
end
end
-- Main procedure
local t = multiArray("a", 2, 3, 4, 5)
show4dArray(t)
t[1][1][1][1] = true
show4dArray(t) |
Multifactorial | Lua | The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).
Multifactorials generalize factorials as follows:
: n! = n(n-1)(n-2)...(2)(1)
: n!! = n(n-2)(n-4)...
: n!! ! = n(n-3)(n-6)...
: n!! !! = n(n-4)(n-8)...
: n!! !! ! = n(n-5)(n-10)...
In all cases, the terms in the products are positive integers.
If 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:
# Write a function that given n and the degree, calculates the multifactorial.
# 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.
'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| function multiFact (n, degree)
local fact = 1
for i = n, 2, -degree do
fact = fact * i
end
return fact
end
print("Degree\t|\tMultifactorials 1 to 10")
print(string.rep("-", 52))
for d = 1, 5 do
io.write(" " .. d, "\t| ")
for n = 1, 10 do
io.write(multiFact(n, d) .. " ")
end
print()
end |
Multiple distinct objects | Lua | Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By ''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.
By ''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.
This 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.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: [[Closures/Value capture]]
| -- This concept is relevant to tables in Lua
local table1 = {1,2,3}
-- The following will create a table of references to table1
local refTab = {}
for i = 1, 10 do refTab[i] = table1 end
-- Instead, tables should be copied using a function like this
function copy (t)
local new = {}
for k, v in pairs(t) do new[k] = v end
return new
end
-- Now we can create a table of independent copies of table1
local copyTab = {}
for i = 1, 10 do copyTab[i] = copy(table1) end |
Multisplit | Lua | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=".
For 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".
Note that the quotation marks are shown for clarity and do not form part of the output.
'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| --[[
Returns a table of substrings by splitting the given string on
occurrences of the given character delimiters, which may be specified
as a single- or multi-character string or a table of such strings.
If chars is omitted, it defaults to the set of all space characters,
and keep is taken to be false. The limit and keep arguments are
optional: they are a maximum size for the result and a flag
determining whether empty fields should be kept in the result.
]]
function split (str, chars, limit, keep)
local limit, splitTable, entry, pos, match = limit or 0, {}, "", 1
if keep == nil then keep = true end
if not chars then
for e in string.gmatch(str, "%S+") do
table.insert(splitTable, e)
end
return splitTable
end
while pos <= str:len() do
match = nil
if type(chars) == "table" then
for _, delim in pairs(chars) do
if str:sub(pos, pos + delim:len() - 1) == delim then
match = string.len(delim) - 1
break
end
end
elseif str:sub(pos, pos + chars:len() - 1) == chars then
match = string.len(chars) - 1
end
if match then
if not (keep == false and entry == "") then
table.insert(splitTable, entry)
if #splitTable == limit then return splitTable end
entry = ""
end
else
entry = entry .. str:sub(pos, pos)
end
pos = pos + 1 + (match or 0)
end
if entry ~= "" then table.insert(splitTable, entry) end
return splitTable
end
local multisplit = split("a!===b=!=c", {"==", "!=", "="})
-- Returned result is a table (key/value pairs) - display all entries
print("Key\tValue")
print("---\t-----")
for k, v in pairs(multisplit) do
print(k, v)
end |
Munchausen numbers | Lua | 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''.
('''Munchausen''' is also spelled: '''Munchhausen'''.)
For instance: 3435 = 33 + 44 + 33 + 55
;Task
Find all Munchausen numbers between '''1''' and '''5000'''.
;Also see:
:* The OEIS entry: A046253
:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
| function isMunchausen (n)
local sum, nStr, digit = 0, tostring(n)
for pos = 1, #nStr do
digit = tonumber(nStr:sub(pos, pos))
sum = sum + digit ^ digit
end
return sum == n
end
-- alternative, faster version based on the C version,
-- avoiding string manipulation, for Lua 5.3 or higher
local function isMunchausen (n)
local sum, digit, acc = 0, 0, n
while acc > 0 do
digit = acc % 10.0
sum = sum + digit ^ digit
acc = acc // 10 -- integer div
end
return sum == n
end
for i = 1, 5000 do
if isMunchausen(i) then print(i) end
end |
Musical scale | Lua | 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.
These 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.
For 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.
For 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.
| c = string.char
midi = "MThd" .. c(0,0,0,6,0,0,0,1,0,96) -- header
midi = midi .. "MTrk" .. c(0,0,0,8*8+4) -- track
for _,note in ipairs{60,62,64,65,67,69,71,72} do
midi = midi .. c(0, 0x90, note, 0x40, 0x60, 0x80, note, 0) -- notes
end
midi = midi .. c(0, 0xFF, 0x2F, 0) -- end
file = io.open("scale.mid", "wb")
file:write(midi)
file:close()
-- (optional: hex dump to screen)
midi:gsub(".", function(c) io.write(string.format("%02X ", string.byte(c))) end) |
N-queens problem | Lua | right
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.
For the number of solutions for small values of '''N''', see OEIS: A000170.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| N = 8
-- We'll use nil to indicate no queen is present.
grid = {}
for i = 0, N do
grid[i] = {}
end
function can_find_solution(x0, y0)
local x0, y0 = x0 or 0, y0 or 1 -- Set default vals (0, 1).
for x = 1, x0 - 1 do
if grid[x][y0] or grid[x][y0 - x0 + x] or grid[x][y0 + x0 - x] then
return false
end
end
grid[x0][y0] = true
if x0 == N then return true end
for y0 = 1, N do
if can_find_solution(x0 + 1, y0) then return true end
end
grid[x0][y0] = nil
return false
end
if can_find_solution() then
for y = 1, N do
for x = 1, N do
-- Print "|Q" if grid[x][y] is true; "|_" otherwise.
io.write(grid[x][y] and "|Q" or "|_")
end
print("|")
end
else
print(string.format("No solution for %d queens.\n", N))
end |
Narcissistic decimal number | Lua | 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.
Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong.
They are also known as '''Plus Perfect''' numbers.
;An example:
::::* if n is '''153'''
::::* then m, (the number of decimal digits) is '''3'''
::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153'''
::::* and so '''153''' is a narcissistic decimal number
;Task:
Generate and show here the first '''25''' narcissistic decimal numbers.
Note: 0^1 = 0, the first in the series.
;See also:
* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
* MathWorld entry: Narcissistic Number.
* Wikipedia entry: Narcissistic number.
| function isNarc (n)
local m, sum, digit = string.len(n), 0
for pos = 1, m do
digit = tonumber(string.sub(n, pos, pos))
sum = sum + digit^m
end
return sum == n
end
local n, count = 0, 0
repeat
if isNarc(n) then
io.write(n .. " ")
count = count + 1
end
n = n + 1
until count == 25 |
Nested function | Lua | 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.
;Task:
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The 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.
The 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.
;References:
:* Nested function
| function makeList (separator)
local counter = 0
local function makeItem(item)
counter = counter + 1
return counter .. separator .. item .. "\n"
end
return makeItem("first") .. makeItem("second") .. makeItem("third")
end
print(makeList(". ")) |
Next highest int from digits | Lua | Given a zero or positive integer, the task is to generate the next largest
integer using only the given digits*1.
* Numbers will not be padded to the left with zeroes.
* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).
* If there is no next highest integer return zero.
:*1 Alternatively phrased as: "Find the smallest integer larger than the (positive or zero) integer '''N'''
:: which can be obtained by reordering the (base ten) digits of '''N'''".
;Algorithm 1:
# Generate all the permutations of the digits and sort into numeric order.
# Find the number in the list.
# Return the next highest number from the list.
The above could prove slow and memory hungry for numbers with large numbers of
digits, but should be easy to reason about its correctness.
;Algorithm 2:
# 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.
# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.
# 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)
'''E.g.:'''
n = 12453
12_4_53
12_5_43
12_5_34
return: 12534
This second algorithm is faster and more memory efficient, but implementations
may be harder to test.
One method of testing, (as used in developing the task), is to compare results from both
algorithms for random numbers generated from a range that the first algorithm can handle.
;Task requirements:
Calculate the next highest int from the digits of the following numbers:
:* 0
:* 9
:* 12
:* 21
:* 12453
:* 738440
:* 45072010
:* 95322020
;Optional stretch goal:
:* 9589776899767587796600
| unpack = unpack or table.unpack -- <=5.2 vs >=5.3 polyfill
function nexthighestint(n)
local digits, index = {}, {[0]={},{},{},{},{},{},{},{},{},{}}
for d in tostring(n):gmatch("%d") do digits[#digits+1]=tonumber(d) end
for i,d in ipairs(digits) do index[d][#index[d]+1]=i end
local function findswap(i,d)
for D=d+1,9 do
for I=1,#index[D] do
if index[D][I] > i then return index[D][I] end
end
end
end
for i = #digits-1,1,-1 do
local j = findswap(i,digits[i])
if j then
digits[i],digits[j] = digits[j],digits[i]
local sorted = {unpack(digits,i+1)}
table.sort(sorted)
for k=1,#sorted do digits[i+k]=sorted[k] end
return table.concat(digits)
end
end
end
tests = { 0, 9, 12, 21, 12453, 738440, 45072010, 95322020, -- task
"9589776899767587796600", -- stretch
"123456789098765432109876543210", -- stretchier
"1234567890999888777666555444333222111000" -- stretchiest
}
for _,n in ipairs(tests) do
print(n .. " -> " .. (nexthighestint(n) or "(none)"))
end |
Nim game | Lua | Nim is a simple game where the second player-if they know the trick-will always win.
The game has only 3 rules:
::* start with '''12''' tokens
::* each player takes '''1, 2, or 3''' tokens in turn
::* the player who takes the last token wins.
To 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.
;Task:
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| tokens = 12
print("Nim Game\n")
print("Starting with " .. tokens .. " tokens.\n\n")
function printRemaining()
print(tokens .. " tokens remaining.\n")
end
function playerTurn(take)
take = math.floor(take)
if (take < 1 or take > 3) then
print ("\nTake must be between 1 and 3.\n")
return false
end
tokens = tokens - take
print ("\nPlayer takes " .. take .. " tokens.")
printRemaining()
return true
end
function computerTurn()
take = tokens % 4
tokens = tokens - take
print("Computer takes " .. take .. " tokens.")
printRemaining()
end
while (tokens > 0) do
io.write("How many tokens would you like to take?: ")
if playerTurn(io.read("*n")) then
computerTurn()
end
end
print ("Computer wins.")
|
Nonoblock | Lua | Nonogram puzzle.
;Given:
* The number of cells in a row.
* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.
;Task:
* show all possible positions.
* show the number of positions of the blocks for the following cases within the row.
* show all output on this page.
* use a "neat" diagram of the block positions.
;Enumerate the following configurations:
# '''5''' cells and '''[2, 1]''' blocks
# '''5''' cells and '''[]''' blocks (no blocks)
# '''10''' cells and '''[8]''' blocks
# '''15''' cells and '''[2, 3, 2, 3]''' blocks
# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)
;Example:
Given 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:
|_|_|_|_|_| # 5 cells and [2, 1] blocks
And would expand to the following 3 possible rows of block positions:
|A|A|_|B|_|
|A|A|_|_|B|
|_|A|A|_|B|
Note how the sets of blocks are always separated by a space.
Note also that it is not necessary for each block to have a separate letter.
Output approximating
This:
|#|#|_|#|_|
|#|#|_|_|#|
|_|#|#|_|#|
This would also work:
##.#.
##..#
.##.#
;An algorithm:
* 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).
* 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.
* 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.
(This is the algorithm used in the [[Nonoblock#Python]] solution).
;Reference:
* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.
| local examples = {
{5, {2, 1}},
{5, {}},
{10, {8}},
{15, {2, 3, 2, 3}},
{5, {2, 3}},
}
function deep (blocks, iBlock, freedom, str)
if iBlock == #blocks then -- last
for takenFreedom = 0, freedom do
print (str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. string.rep("0", freedom - takenFreedom))
total = total + 1
end
else
for takenFreedom = 0, freedom do
local str2 = str..string.rep("0", takenFreedom) .. string.rep("1", blocks[iBlock]) .. "0"
deep (blocks, iBlock+1, freedom-takenFreedom, str2)
end
end
end
function main (cells, blocks) -- number, list
local str = " "
print (cells .. ' cells and {' .. table.concat(blocks, ', ') .. '} blocks')
local freedom = cells - #blocks + 1 -- freedom
for iBlock = 1, #blocks do
freedom = freedom - blocks[iBlock]
end
if #blocks == 0 then
print ('no blocks')
print (str..string.rep("0", cells))
total = 1
elseif freedom < 0 then
print ('no solutions')
else
print ('Possibilities:')
deep (blocks, 1, freedom, str)
end
end
for i, example in ipairs (examples) do
print ("\n--")
total = 0
main (example[1], example[2])
print ('A total of ' .. total .. ' possible configurations.')
end |
Numbers which are the cube roots of the product of their proper divisors | Lua | Example
Consider 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.
;Task
Compute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.
Also show the '''500th''' and '''5,000th''' such numbers.
;Stretch
Compute and show the '''50,000th''' such number.
;Reference
* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.
;Note
OEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.
| function is_1_or_has_eight_divisors (n)
if n == 1 then return true end
local divCount, sqr = 2, math.sqrt(n)
for d = 2, sqr do
if n % d == 0 then
divCount = d == sqr and divCount + 1 or divCount + 2
end
if divCount > 8 then return false end
end
return divCount == 8
end
-- First 50
local count, x = 0, 0
while count < 50 do
x = x + 1
if is_1_or_has_eight_divisors(x) then
io.write(x .. " ")
count = count + 1
end
end
-- 500th, 5,000th and 50,000th
while count < 50000 do
x = x + 1
if is_1_or_has_eight_divisors(x) then
count = count + 1
if count == 500 then print("\n\n500th: " .. x) end
if count == 5000 then print("5,000th: " .. x) end
end
end
print("50,000th: " .. x) |
Odd word problem | Lua | Write a program that solves the odd word problem with the restrictions given below.
;Description:
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
* the words (sequence of consecutive letters) are delimited by one and only one punctuation,
* the stream will begin with a word,
* the words will be at least one letter long, and
* a full stop (a period, [.]) appears after, and only after, the last word.
;Example:
A stream with six words:
:: what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
:: what,si,the;gninaem,of:efil.
while observing the following restrictions:
# 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;
# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
;Test cases:
Work on both the "life" example given above, and also the text:
:: we,are;not,in,kansas;any,more.
| function reverse()
local ch = io.read(1)
if ch:find("%w") then
local rc = reverse()
io.write(ch)
return rc
end
return ch
end
function forward()
ch = io.read(1)
io.write(ch)
if ch == "." then return false end
if not ch:find("%w") then
ch = reverse()
if ch then io.write(ch) end
if ch == "." then return false end
end
return true
end
while forward() do end |
Old lady swallowed a fly | Lua | 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.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
| animals = {"fly", "spider", "bird", "cat","dog", "goat", "cow", "horse"}
phrases = {
"",
"That wriggled and jiggled and tickled inside her",
"How absurd to swallow a bird",
"Fancy that to swallow a cat",
"What a hog, to swallow a dog",
"She just opened her throat and swallowed a goat",
"I don't know how she swallowed a cow",
" ...She's dead of course"
}
for i=0,7 do
io.write(string.format("There was an old lady who swallowed a %s\n", animals[i+1]))
if i>0 then io.write(phrases[i+1]) end
if i==7 then break end
if i>0 then
io.write("\n")
for j=i,1,-1 do
io.write(string.format("She swallowed the %s to catch the %s", animals[j+1], animals[j]))
-- if j<4 then p='.' else p=',' end
-- io.write(string.format("%s\n", p))
io.write("\n")
if j==2 then
io.write(string.format("%s!\n", phrases[2]))
end
end
end
io.write("I don't know why she swallowed a fly - Perhaps she'll die!\n\n")
end |
One of n lines in a file | Lua | A method of choosing a line randomly from a file:
::* Without reading the file more than once
::* When substantial parts of the file cannot be held in memory
::* Without knowing how many lines are in the file
Is to:
::* keep the first line of the file as a possible choice, then
::* 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.
::* 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.
::* ...
::* 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
::* Return the computed possible choice when no further lines exist in the file.
;Task:
# 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.
# 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.
# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| math.randomseed(os.time())
local n = 10
local trials = 1000000
function one(n)
local chosen = 1
for i = 1, n do
if math.random() < 1/i then
chosen = i
end
end
return chosen
end
-- 0 filled table for storing results
local results = {}
for i = 1, n do results[i] = 0 end
-- run simulation
for i = 1, trials do
local result = one(n)
results[result] = results[result] + 1
end
print("Value","Occurrences")
print("-------------------")
for k, v in ipairs(results) do
print(k,v)
end
|
Operator precedence | Lua | Operators in C and C++}}
;Task:
Provide 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.
Operators 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.
State whether arguments are passed by value or by reference.
| Table available [http://www.lua.org/manual/5.1/manual.html#2.5.6 here]. That table does not contain all operators, however.
{| class="wikitable"
|-
! Precedence
! Operator
! Description
|-
! lowest
| '''or'''
| Boolean OR
|-
!
| '''and'''
| Boolean AND
|-
!
| '''<, <=, >, >=, ~=, =='''
| Comparisons
|-
!
| '''..'''
| Concatenation [1]
|-
!
| '''+, -'''
| Addition and subtraction
|-
!
| '''*, /, %'''
| Multiplication, division, modulo
|-
!
| '''not, -, #'''
| Boolean NOT, negation, length
|-
!
| '''^'''
| Exponentiation [1]
|-
! highest
| '''x[index], x.index, x(arguments...), x:m(arguments...)'''
| Generic index, string index, function call, method index+call [2]
|}
Notes:
# Concatenation and exponentiation are right-associative, all other binary operators are left-associative
# Binding is done at the call site; therefore, method lookup is syntactically part of the call
|
Pangram checker | Lua | A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: ''The quick brown fox jumps over the lazy dog''.
;Task:
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
;Related tasks:
:* determine if a string has all the same characters
:* determine if a string has all unique characters
| require"lpeg"
S, C = lpeg.S, lpeg.C
function ispangram(s)
return #(C(S(s)^0):match"abcdefghijklmnopqrstuvwxyz") == 26
end
print(ispangram"waltz, bad nymph, for quick jigs vex")
print(ispangram"bobby")
print(ispangram"long sentence") |
Parsing/RPN calculator algorithm | Lua | 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''.
* Assume an input of a correct, space separated, string of tokens of an RPN expression
* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
* Print or display the output here
;Notes:
* '''^''' means exponentiation in the expression above.
* '''/''' means division.
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).
* [[Parsing/RPN to infix conversion]].
* [[Arithmetic evaluation]].
| local stack = {}
function push( a ) table.insert( stack, 1, a ) end
function pop()
if #stack == 0 then return nil end
return table.remove( stack, 1 )
end
function writeStack()
for i = #stack, 1, -1 do
io.write( stack[i], " " )
end
print()
end
function operate( a )
local s
if a == "+" then
push( pop() + pop() )
io.write( a .. "\tadd\t" ); writeStack()
elseif a == "-" then
s = pop(); push( pop() - s )
io.write( a .. "\tsub\t" ); writeStack()
elseif a == "*" then
push( pop() * pop() )
io.write( a .. "\tmul\t" ); writeStack()
elseif a == "/" then
s = pop(); push( pop() / s )
io.write( a .. "\tdiv\t" ); writeStack()
elseif a == "^" then
s = pop(); push( pop() ^ s )
io.write( a .. "\tpow\t" ); writeStack()
elseif a == "%" then
s = pop(); push( pop() % s )
io.write( a .. "\tmod\t" ); writeStack()
else
push( tonumber( a ) )
io.write( a .. "\tpush\t" ); writeStack()
end
end
function calc( s )
local t, a = "", ""
print( "\nINPUT", "OP", "STACK" )
for i = 1, #s do
a = s:sub( i, i )
if a == " " then operate( t ); t = ""
else t = t .. a
end
end
if a ~= "" then operate( a ) end
print( string.format( "\nresult: %.13f", pop() ) )
end
--[[ entry point ]]--
calc( "3 4 2 * 1 5 - 2 3 ^ ^ / +" )
calc( "22 11 *" ) |
Parsing/RPN to infix conversion | Lua | Create a program that takes an infix notation.
* Assume an input of a correct, space separated, string of tokens
* Generate a space separated output string representing the same expression in infix notation
* Show how the major datastructure of your algorithm changes with each new token parsed.
* Test with the following input RPN strings then print and display the output here.
:::::{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}
* Operator precedence and operator associativity is given in this table:
::::::::{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* Postfix to infix from the RubyQuiz site.
| function tokenize(rpn)
local out = {}
local cnt = 0
for word in rpn:gmatch("%S+") do
table.insert(out, word)
cnt = cnt + 1
end
return {tokens = out, pos = 1, size = cnt}
end
function advance(lex)
if lex.pos <= lex.size then
lex.pos = lex.pos + 1
return true
else
return false
end
end
function current(lex)
return lex.tokens[lex.pos]
end
function isOperator(sym)
return sym == '+' or sym == '-'
or sym == '*' or sym == '/'
or sym == '^'
end
function buildTree(lex)
local stack = {}
while lex.pos <= lex.size do
local sym = current(lex)
advance(lex)
if isOperator(sym) then
local b = table.remove(stack)
local a = table.remove(stack)
local t = {op=sym, left=a, right=b}
table.insert(stack, t)
else
table.insert(stack, sym)
end
end
return table.remove(stack)
end
function infix(tree)
if type(tree) == "table" then
local a = {}
local b = {}
if type(tree.left) == "table" then
a = '(' .. infix(tree.left) .. ')'
else
a = tree.left
end
if type(tree.right) == "table" then
b = '(' .. infix(tree.right) .. ')'
else
b = tree.right
end
return a .. ' ' .. tree.op .. ' ' .. b
else
return tree
end
end
function convert(str)
local lex = tokenize(str)
local tree = buildTree(lex)
print(infix(tree))
end
function main()
convert("3 4 2 * 1 5 - 2 3 ^ ^ / +")
convert("1 2 + 3 4 + ^ 5 6 + ^")
end
main() |
Parsing/Shunting-yard algorithm | Lua | 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
as each individual token is processed.
* Assume an input of a correct, space separated, string of tokens representing an infix expression
* Generate a space separated output string representing the RPN
* Test with the input string:
:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
* print and display the output here.
* Operator precedence is given in this table:
:{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
;Note
The handling of functions and arguments is not required.
;See also:
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* [[Parsing/RPN to infix conversion]].
| -- Lua 5.3.5
-- Retrieved from: https://devforum.roblox.com/t/more-efficient-way-to-implement-shunting-yard/1328711
-- Modified slightly to ensure conformity with other code snippets posted here
local OPERATOR_PRECEDENCE = {
-- [operator] = { [precedence], [is left assoc.] }
['-'] = { 2, true };
['+'] = { 2, true };
['/'] = { 3, true };
['*'] = { 3, true };
['^'] = { 4, false };
}
local function shuntingYard(expression)
local outputQueue = { }
local operatorStack = { }
local number, operator, parenthesis, fcall
while #expression > 0 do
local nStartPos, nEndPos = string.find(expression, '(%-?%d+%.?%d*)')
if nStartPos == 1 and nEndPos > 0 then
number, expression = string.sub(expression, nStartPos, nEndPos), string.sub(expression, nEndPos + 1)
table.insert(outputQueue, tonumber(number))
print('token:', number)
print('queue:', unpack(outputQueue))
print('stack:', unpack(operatorStack))
else
local oStartPos, oEndPos = string.find(expression, '([%-%+%*/%^])')
if oStartPos == 1 and oEndPos > 0 then
operator, expression = string.sub(expression, oStartPos, oEndPos), string.sub(expression, oEndPos + 1)
if #operatorStack > 0 then
while operatorStack[1] ~= '(' do
local operator1Precedence = OPERATOR_PRECEDENCE[operator]
local operator2Precedence = OPERATOR_PRECEDENCE[operatorStack[1]]
if operator2Precedence and ((operator2Precedence[1] > operator1Precedence[1]) or (operator2Precedence[1] == operator1Precedence[1] and operator1Precedence[2])) then
table.insert(outputQueue, table.remove(operatorStack, 1))
else
break
end
end
end
table.insert(operatorStack, 1, operator)
print('token:', operator)
print('queue:', unpack(outputQueue))
print('stack:', unpack(operatorStack))
else
local pStartPos, pEndPos = string.find(expression, '[%(%)]')
if pStartPos == 1 and pEndPos > 0 then
parenthesis, expression = string.sub(expression, pStartPos, pEndPos), string.sub(expression, pEndPos + 1)
if parenthesis == ')' then
while operatorStack[1] ~= '(' do
assert(#operatorStack > 0)
table.insert(outputQueue, table.remove(operatorStack, 1))
end
assert(operatorStack[1] == '(')
table.remove(operatorStack, 1)
else
table.insert(operatorStack, 1, parenthesis)
end
print('token:', parenthesis)
print('queue:', unpack(outputQueue))
print('stack:', unpack(operatorStack))
else
local wStartPos, wEndPos = string.find(expression, '%s+')
if wStartPos == 1 and wEndPos > 0 then
expression = string.sub(expression, wEndPos + 1)
else
error('Invalid character set: '.. expression)
end
end
end
end
end
while #operatorStack > 0 do
assert(operatorStack[1] ~= '(')
table.insert(outputQueue, table.remove(operatorStack, 1))
end
return table.concat(outputQueue, ' ')
end
local goodmath = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
print('infix:', goodmath)
print('postfix:', shuntingYard(goodmath))
|
Pascal matrix generation | Lua | A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
;Task:
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The 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).
;Note:
The [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| function factorial (n)
local f = 1
for i = 2, n do
f = f * i
end
return f
end
function binomial (n, k)
if k > n then return 0 end
return factorial(n) / (factorial(k) * factorial(n - k))
end
function pascalMatrix (form, size)
local matrix = {}
for row = 1, size do
matrix[row] = {}
for col = 1, size do
if form == "upper" then
matrix[row][col] = binomial(col - 1, row - 1)
end
if form == "lower" then
matrix[row][col] = binomial(row - 1, col - 1)
end
if form == "symmetric" then
matrix[row][col] = binomial(row + col - 2, col - 1)
end
end
end
matrix.form = form:sub(1, 1):upper() .. form:sub(2, -1)
return matrix
end
function show (mat)
print(mat.form .. ":")
for i = 1, #mat do
for j = 1, #mat[i] do
io.write(mat[i][j] .. "\t")
end
print()
end
print()
end
for _, form in pairs({"upper", "lower", "symmetric"}) do
show(pascalMatrix(form, 5))
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.