title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Password generator | Lua | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a --> z
upper-case letters: A --> Z
digits: 0 --> 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include ''at least one'' (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
::::* capital eye, lowercase ell, the digit one
::::* capital oh, the digit zero
::::* the digit five, capital ess
::::* the digit two, capital zee
| function randPW (length)
local index, pw, rnd = 0, ""
local chars = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789",
"!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"
}
repeat
index = index + 1
rnd = math.random(chars[index]:len())
if math.random(2) == 1 then
pw = pw .. chars[index]:sub(rnd, rnd)
else
pw = chars[index]:sub(rnd, rnd) .. pw
end
index = index % #chars
until pw:len() >= length
return pw
end
math.randomseed(os.time())
if #arg ~= 2 then
print("\npwgen.lua")
print("=========\n")
print("A Lua script to generate random passwords.\n")
print("Usage: lua pwgen.lua [password length] [number of passwords to generate]\n")
os.exit()
end
for i = 1, arg[2] do print(randPW(tonumber(arg[1]))) end |
Pentagram | Lua | A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
;Task:
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.
;See also
* Angle sum of a pentagram
| 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:pentagram(x, y, radius, rotation, outlcolor, fillcolor)
local function pxy(i) return x+radius*cos(i*pi*2/5+rotation), y+radius*sin(i*pi*2/5+rotation) end
local x1, y1 = pxy(0)
for i = 1, 5 do
local x2, y2 = pxy(i*2) -- btw: pxy(i) ==> pentagon
self:line(floor(x1*2), floor(y1), floor(x2*2), floor(y2), outlcolor)
x1, y1 = x2, y2
end
self:floodfill(floor(x*2), floor(y), fillcolor)
radius = radius / 2
for i = 1, 5 do
x1, y1 = pxy(i)
self:floodfill(floor(x1*2), floor(y1), fillcolor)
end
end
bitmap = Bitmap(40*2,40)
bitmap:clear(".")
bitmap:pentagram(20, 22, 20, -pi/2, "@", '+')
bitmap:render() |
Perfect shuffle | Lua | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right"
|-
| ''original:'' ||
1
2
3
4
5
6
7
8
|-
| ''after 1st shuffle:'' ||
1
5
2
6
3
7
4
8
|-
| ''after 2nd shuffle:'' ||
1
3
5
7
2
4
6
8
|-
| ''after 3rd shuffle:'' ||
1
2
3
4
5
6
7
8
|}
'''''The Task'''''
# Write a function that can perform a perfect shuffle on an even-sized list of values.
# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
'''''Test Cases'''''
::::: {| class="wikitable"
|-
! input ''(deck size)'' !! output ''(number of shuffles required)''
|-
| 8 || 3
|-
| 24 || 11
|-
| 52 || 8
|-
| 100 || 30
|-
| 1020 || 1018
|-
| 1024 || 10
|-
| 10000 || 300
|}
| -- Perform weave shuffle
function shuffle (cards)
local pile1, pile2 = {}, {}
for card = 1, #cards / 2 do table.insert(pile1, cards[card]) end
for card = (#cards / 2) + 1, #cards do table.insert(pile2, cards[card]) end
cards = {}
for card = 1, #pile1 do
table.insert(cards, pile1[card])
table.insert(cards, pile2[card])
end
return cards
end
-- Return boolean indicating whether or not the cards are in order
function inOrder (cards)
for k, v in pairs(cards) do
if k ~= v then return false end
end
return true
end
-- Count the number of shuffles needed before the cards are in order again
function countShuffles (deckSize)
local deck, count = {}, 0
for i = 1, deckSize do deck[i] = i end
repeat
deck = shuffle(deck)
count = count + 1
until inOrder(deck)
return count
end
-- Main procedure
local testCases = {8, 24, 52, 100, 1020, 1024, 10000}
print("Input", "Output")
for _, case in pairs(testCases) do print(case, countShuffles(case)) end |
Perfect totient numbers | Lua | Generate and show here, the first twenty Perfect totient numbers.
;Related task:
::* [[Totient function]]
;Also see:
::* the OEIS entry for perfect totient numbers.
::* mrob list of the first 54
| local function phi(n)
assert(type(n) == 'number', 'n must be a number!')
local result, i = n, 2
while i <= n do
if n % i == 0 then
while n % i == 0 do n = n // i end
result = result - (result // i)
end
if i == 2 then i = 1 end
i = i + 2
end
if n > 1 then result = result - (result // n) end
return result
end
local function phi_iter(n)
assert(type(n) == 'number', 'n must be a number!')
if n == 2 then
return phi(n) + 0
else
return phi(n) + phi_iter(phi(n))
end
end
local i, count = 2, 0
while count ~= 20 do
if i == phi_iter(i) then
io.write(i, ' ')
count = count + 1
end
i = i + 1
end
|
Perlin noise | Lua | The '''computer graphics, most notably to procedurally generate textures or heightmaps.
The Perlin noise is basically a pseudo-random mapping of \R^d into \R with an integer d which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
''Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.''
| local p = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
}
-- extending for easy access
for i = 1, #p do
p[i+256]=p[i]
end
local function fade (t)
-- fade graph: https://www.desmos.com/calculator/d5cgqlrmem
return t*t*t*(t*(t*6-15)+10)
end
local function lerp (t, a, b)
return a+t*(b-a)
end
local function grad (hash, x, y, z)
local h = hash%16
local cases = {
x+y,
-x+y,
x-y,
-x-y,
x+z,
-x+z,
x-z,
-x-z,
y+z,
-y+z,
y-z,
-y-z,
y+x,
-y+z,
y-x,
-y-z,
}
return cases[h+1]
end
local function noise (x,y,z)
local a, b, c = math.floor(x)%256, math.floor(y)%256, math.floor(z)%256 -- values in range [0, 255]
local xx, yy, zz = x%1, y%1, z%1
local u, v, w = fade (xx), fade (yy), fade (zz)
local a0 = p[a+1]+b
local a1, a2 = p[a0+1]+c, p[a0+2]+c
local b0 = p[a+2]+b
local b1, b2 = p[b0+1]+c, p[b0+2]+c
local k1 = grad(p[a1+1], xx, yy, zz)
local k2 = grad(p[b1+1], xx-1, yy, zz)
local k3 = grad(p[a2+1], xx, yy-1, zz)
local k4 = grad(p[b2+1], xx-1, yy-1, zz)
local k5 = grad(p[a1+2], xx, yy, zz-1)
local k6 = grad(p[b1+2], xx-1, yy, zz-1)
local k7 = grad(p[a2+2], xx, yy-1, zz-1)
local k8 = grad(p[b2+2], xx-1, yy-1, zz-1)
return lerp(w,
lerp(v, lerp(u, k1, k2), lerp(u, k3, k4)),
lerp(v, lerp(u, k5, k6), lerp(u, k7, k8)))
end
print (noise(3.14, 42, 7)) -- 0.136919958784
print (noise(1.4142, 1.2589, 2.718)) -- -0.17245663814988 |
Permutations/Derangements | Lua | A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''.
There are various ways to calculate !''n''.
;Task:
# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer).
# Generate ''and show'' all the derangements of 4 integers using the above routine.
# Create a function that calculates the subfactorial of ''n'', !''n''.
# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.
;Optional stretch goal:
* Calculate !''20''
;Related tasks:
* [[Anagrams/Deranged anagrams]]
* [[Best shuffle]]
* [[Left_factorials]]
| -- Return an iterator to produce every permutation of list
function permute (list)
local function perm (list, n)
if n == 0 then coroutine.yield(list) end
for i = 1, n do
list[i], list[n] = list[n], list[i]
perm(list, n - 1)
list[i], list[n] = list[n], list[i]
end
end
return coroutine.wrap(function() perm(list, #list) end)
end
-- Return a copy of table t (wouldn't work for a table of tables)
function copy (t)
if not t then return nil end
local new = {}
for k, v in pairs(t) do new[k] = v end
return new
end
-- Return true if no value in t1 can be found at the same index of t2
function noMatches (t1, t2)
for k, v in pairs(t1) do
if t2[k] == v then return false end
end
return true
end
-- Return a table of all derangements of table t
function derangements (t)
local orig = copy(t)
local nextPerm, deranged = permute(t), {}
local numList, keep = copy(nextPerm())
while numList do
if noMatches(numList, orig) then table.insert(deranged, numList) end
numList = copy(nextPerm())
end
return deranged
end
-- Return the subfactorial of n
function subFact (n)
if n < 2 then
return 1 - n
else
return (subFact(n - 1) + subFact(n - 2)) * (n - 1)
end
end
-- Return a table of the numbers 1 to n
function listOneTo (n)
local t = {}
for i = 1, n do t[i] = i end
return t
end
-- Main procedure
print("Derangements of [1,2,3,4]")
for k, v in pairs(derangements(listOneTo(4))) do print("", unpack(v)) end
print("\n\nSubfactorial vs counted derangements\n")
print("\tn\t| subFact(n)\t| Derangements")
print(" " .. string.rep("-", 42))
for i = 0, 9 do
io.write("\t" .. i .. "\t| " .. subFact(i))
if string.len(subFact(i)) < 5 then io.write("\t") end
print("\t| " .. #derangements(listOneTo(i)))
end
print("\n\nThe subfactorial of 20 is " .. subFact(20)) |
Permutations by swapping | Lua from C++ | Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation ''here''.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.
;References:
* Steinhaus-Johnson-Trotter algorithm
* Johnson-Trotter Algorithm Listing All Permutations
* Heap's algorithm
* Tintinnalogia
;Related tasks:
* [[Matrix arithmetic]
* [[Gray code]]
| _JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
setmetatable(n,{__index=_JT})
for i=1,dim do
n.values[i]=i
n.positions[i]=i
n.directions[i]=-1
end
return n
end
function _JT:largestMobile()
for i=#self.values,1,-1 do
local loc=self.positions[i]+self.directions[i]
if loc >= 1 and loc <= #self.values and self.values[loc] < i then
return i
end
end
return 0
end
function _JT:next()
local r=self:largestMobile()
if r==0 then return false end
local rloc=self.positions[r]
local lloc=rloc+self.directions[r]
local l=self.values[lloc]
self.values[lloc],self.values[rloc] = self.values[rloc],self.values[lloc]
self.positions[l],self.positions[r] = self.positions[r],self.positions[l]
self.sign=-self.sign
for i=r+1,#self.directions do self.directions[i]=-self.directions[i] end
return true
end
-- test
perm=JT(4)
repeat
print(unpack(perm.values))
until not perm:next() |
Phrase reversals | Lua | Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
:# Reverse the characters of the string.
:# Reverse the characters of each individual word in the string, maintaining original word order within the string.
:# Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
| -- Return a copy of table t in which each string is reversed
function reverseEach (t)
local rev = {}
for k, v in pairs(t) do rev[k] = v:reverse() end
return rev
end
-- Return a reversed copy of table t
function tabReverse (t)
local revTab = {}
for i, v in ipairs(t) do revTab[#t - i + 1] = v end
return revTab
end
-- Split string str into a table on space characters
function wordSplit (str)
local t = {}
for word in str:gmatch("%S+") do table.insert(t, word) end
return t
end
-- Main procedure
local str = "rosetta code phrase reversal"
local tab = wordSplit(str)
print("1. " .. str:reverse())
print("2. " .. table.concat(reverseEach(tab), " "))
print("3. " .. table.concat(tabReverse(tab), " ")) |
Pig the dice game | lua 5.1 | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach '''100''' points or more.
Play is taken in turns. On each person's turn that person has the option of either:
:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.
:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.
;Task:
Create a program to score for, and simulate dice throws for, a two-person game.
;Related task:
* [[Pig the dice game/Player]]
| local numPlayers = 2
local maxScore = 100
local scores = { }
for i = 1, numPlayers do
scores[i] = 0 -- total safe score for each player
end
math.randomseed(os.time())
print("Enter a letter: [h]old or [r]oll?")
local points = 0 -- points accumulated in current turn
local p = 1 -- start with first player
while true do
io.write("\nPlayer "..p..", your score is ".. scores[p]..", with ".. points.." temporary points. ")
local reply = string.sub(string.lower(io.read("*line")), 1, 1)
if reply == 'r' then
local roll = math.random(6)
io.write("You rolled a " .. roll)
if roll == 1 then
print(". Too bad. :(")
p = (p % numPlayers) + 1
points = 0
else
points = points + roll
end
elseif reply == 'h' then
scores[p] = scores[p] + points
if scores[p] >= maxScore then
print("Player "..p..", you win with a score of "..scores[p])
break
end
print("Player "..p..", your new score is " .. scores[p])
p = (p % numPlayers) + 1
points = 0
end
end
|
Plasma effect | Lua from C++ | The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.
;Task
Create a plasma effect.
;See also
* Computer Graphics Tutorial (lodev.org)
* Plasma (bidouille.org)
| _ = love.graphics
p1, p2, points = {}, {}, {}
function hypotenuse( a, b )
return a * a + b * b
end
function love.load()
size = _.getWidth()
currentTime, doub, half = 0, size * 2, size / 2
local b1, b2
for j = 0, size * 2 do
for i = 0, size * 2 do
b1 = math.floor( 128 + 127 * ( math.cos( math.sqrt( hypotenuse( size - j , size - i ) ) / 64 ) ) )
b2 = math.floor( ( math.sin( ( math.sqrt( 128.0 + hypotenuse( size - i, size - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90 )
table.insert( p1, b1 ); table.insert( p2, b2 )
end
end
end
function love.draw()
local a, c1, c2, c3, s1, s2, s3
currentTime = currentTime + math.random( 2 ) * 3
local x1 = math.floor( half + ( half - 2 ) * math.sin( currentTime / 47 ) )
local x2 = math.floor( half + ( half / 7 ) * math.sin( -currentTime / 149 ) )
local x3 = math.floor( half + ( half - 3 ) * math.sin( -currentTime / 157 ) )
local y1 = math.floor( half + ( half / 11 ) * math.cos( currentTime / 71 ) )
local y2 = math.floor( half + ( half - 5 ) * math.cos( -currentTime / 181 ) )
local y3 = math.floor( half + ( half / 23 ) * math.cos( -currentTime / 137 ) )
s1 = y1 * doub + x1; s2 = y2 * doub + x2; s3 = y3 * doub + x3
for j = 0, size do
for i = 0, size do
a = p2[s1] + p1[s2] + p2[s3]
c1 = a * 2; c2 = a * 4; c3 = a * 8
table.insert( points, { i, j, c1, c2, c3, 255 } )
s1 = s1 + 1; s2 = s2 + 1; s3 = s3 + 1;
end
s1 = s1 + size; s2 = s2 + size; s3 = s3 + size
end
_.points( points )
end
|
Poker hand analyser | Lua | Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
;Example:
::::'''2d''' (two of diamonds).
Faces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''
Suits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or
alternatively, the unicode card-suit characters:
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
;Examples:
2 2 2 k q: three-of-a-kind
2 5 7 8 9: high-card
a 2 3 4 5: straight
2 3 2 3 3: full-house
2 7 2 3 3: two-pair
2 7 7 7 7: four-of-a-kind
10 j q k a: straight-flush
4 4 k 5 10: one-pair
q 10 7 6 q: invalid
The programs output for the above examples should be displayed here on this page.
;Extra credit:
# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
# allow two jokers
::* use the symbol '''joker'''
::* duplicates would be allowed (for jokers only)
::* five-of-a-kind would then be the highest hand
;More extra credit examples:
joker 2 2 k q: three-of-a-kind
joker 5 7 8 9: straight
joker 2 3 4 5: straight
joker 3 2 3 3: four-of-a-kind
joker 7 2 3 3: three-of-a-kind
joker 7 7 7 7: five-of-a-kind
joker j q k A: straight-flush
joker 4 k 5 10: one-pair
joker k 7 6 4: flush
joker 2 joker 4 5: straight
joker Q joker A 10: straight
joker Q joker A 10: straight-flush
joker 2 2 joker q: four-of-a-kind
;Related tasks:
* [[Playing cards]]
* [[Card shuffles]]
* [[Deal cards_for_FreeCell]]
* [[War Card_Game]]
* [[Go Fish]]
| -- Check whether t is a valid poker hand
function valid (t)
if #t ~= 5 then return false end
for k, v in pairs(t) do
for key, card in pairs(t) do
if v.value == card.value and
v.suit == card.suit and
k ~= key
then
return false
end
end
end
return true
end
-- Return numerical value of a single card
function cardValue (card)
local val = card:sub(1, -2)
local n = tonumber(val)
if n then return n end
if val == "j" then return 11 end
if val == "q" then return 12 end
if val == "k" then return 13 end
if val == "a" then return 1 end
error("Invalid card value: " .. val)
end
-- Detect whether hand t is a straight
function straight (t)
table.sort(t, function (a, b) return a.value < b.value end)
local ace, thisValue, lastValue = false
for i = 2, #t do
thisValue, lastValue = t[i].value, t[i-1].value
if lastValue == 1 then ace = i - 1 end
if thisValue ~= lastValue + 1 then
if ace then
t[ace].value = 14
return straight(t)
else
return false
end
end
end
return true
end
-- Detect whether hand t is a flush
function isFlush (t)
local suit = t[1].suit
for card = 2, #t do
if t[card].suit ~= suit then return false end
end
return true
end
-- Return a table of the count of each card value in hand t
function countValues (t)
local countTab, maxCount = {}, 0
for k, v in pairs(t) do
if countTab[v.value] then
countTab[v.value] = countTab[v.value] + 1
else
countTab[v.value] = 1
end
end
return countTab
end
-- Find the highest value in t
function highestCount (t)
local maxCount = 0
for k, v in pairs(t) do
if v > maxCount then maxCount = v end
end
return maxCount
end
-- Detect full-house and two-pair using the value counts in t
function twoTypes (t)
local threes, twos = 0, 0
for k, v in pairs(t) do
if v == 3 then threes = threes + 1 end
if v == 2 then twos = twos + 1 end
end
return threes, twos
end
-- Return the rank of a poker hand represented as a string
function rank (cards)
local hand = {}
for card in cards:gmatch("%S+") do
table.insert(hand, {value = cardValue(card), suit = card:sub(-1, -1)})
end
if not valid(hand) then return "invalid" end
local st, fl = straight(hand), isFlush(hand)
if st and fl then return "straight-flush" end
local valCount = countValues(hand)
local highCount = highestCount(valCount)
if highCount == 4 then return "four-of-a-kind" end
local n3, n2 = twoTypes(valCount)
if n3 == 1 and n2 == 1 then return "full-house" end
if fl then return "flush" end
if st then return "straight" end
if highCount == 3 then return "three-of-a-kind" end
if n3 == 0 and n2 == 2 then return "two-pair" end
if highCount == 2 then return "one-pair" end
return "high-card"
end
-- Main procedure
local testCases = {
"2h 2d 2c kc qd", -- three-of-a-kind
"2h 5h 7d 8c 9s", -- high-card
"ah 2d 3c 4c 5d", -- straight
"2h 3h 2d 3c 3d", -- full-house
"2h 7h 2d 3c 3d", -- two-pair
"2h 7h 7d 7c 7s", -- four-of-a-kind
"10h jh qh kh ah",-- straight-flush
"4h 4s ks 5d 10s",-- one-pair
"qc 10c 7c 6c 4c" -- flush
}
for _, case in pairs(testCases) do print(case, ": " .. rank(case)) end |
Population count | Lua | The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.
''Population count'' is also known as:
::::* ''pop count''
::::* ''popcount''
::::* ''sideways sum''
::::* ''bit summation''
::::* ''Hamming weight''
For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.
''Evil numbers'' are non-negative integers that have an ''even'' population count.
''Odious numbers'' are positive integers that have an ''odd'' population count.
;Task:
* write a function (or routine) to return the population count of a non-negative integer.
* all computation of the lists below should start with '''0''' (zero indexed).
:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').
:* display the 1st thirty ''evil'' numbers.
:* display the 1st thirty ''odious'' numbers.
* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
;See also
* The On-Line Encyclopedia of Integer Sequences: A000120 population count.
* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| -- Take decimal number, return binary string
function dec2bin (n)
local bin, bit = ""
while n > 0 do
bit = n % 2
n = math.floor(n / 2)
bin = bit .. bin
end
return bin
end
-- Take decimal number, return population count as number
function popCount (n)
local bin, count = dec2bin(n), 0
for pos = 1, bin:len() do
if bin:sub(pos, pos) == "1" then count = count + 1 end
end
return count
end
-- Implement task requirements
function firstThirty (mode)
local numStr, count, n, remainder = "", 0, 0
if mode == "Evil" then remainder = 0 else remainder = 1 end
while count < 30 do
if mode == "3^x" then
numStr = numStr .. popCount(3 ^ count) .. " "
count = count + 1
else
if popCount(n) % 2 == remainder then
numStr = numStr .. n .. " "
count = count + 1
end
n = n + 1
end
end
print(mode .. ":" , numStr)
end
-- Main procedure
firstThirty("3^x")
firstThirty("Evil")
firstThirty("Odious") |
Pragmatic directives | Lua | Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).
;Task:
List any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.
| ffi = require("ffi")
ffi.cdef[[
#pragma pack(1)
typedef struct { char c; int i; } foo;
#pragma pack(4)
typedef struct { char c; int i; } bar;
]]
print(ffi.sizeof(ffi.new("foo")))
print(ffi.sizeof(ffi.new("bar"))) |
Priority queue | Lua | A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
;Task:
Create a priority queue. The queue must support at least two operations:
:# Insertion. An element is added to the queue with a priority (a numeric value).
:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
'''Priority''' '''Task'''
---------- ----------------
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| PriorityQueue = {
__index = {
put = function(self, p, v)
local q = self[p]
if not q then
q = {first = 1, last = 0}
self[p] = q
end
q.last = q.last + 1
q[q.last] = v
end,
pop = function(self)
for p, q in pairs(self) do
if q.first <= q.last then
local v = q[q.first]
q[q.first] = nil
q.first = q.first + 1
return p, v
else
self[p] = nil
end
end
end
},
__call = function(cls)
return setmetatable({}, cls)
end
}
setmetatable(PriorityQueue, PriorityQueue)
-- Usage:
pq = PriorityQueue()
tasks = {
{3, 'Clear drains'},
{4, 'Feed cat'},
{5, 'Make tea'},
{1, 'Solve RC tasks'},
{2, 'Tax return'}
}
for _, task in ipairs(tasks) do
print(string.format("Putting: %d - %s", unpack(task)))
pq:put(unpack(task))
end
for prio, task in pq.pop, pq do
print(string.format("Popped: %d - %s", prio, task))
end |
Pseudo-random numbers/Middle-square method | Lua | {{Wikipedia|Middle-square method|en}}
; The Method:
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
; Pseudo code:
var seed = 675248
function random()
var s = str(seed * seed) 'str: turn a number into string
do while not len(s) = 12
s = "0" + s 'add zeroes before the string
end do
seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
'val: turn a string into number
return seed
end function
; Middle-square method use:
for i = 1 to 5
print random()
end for
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.
* Show the first five integers generated with the seed 675248 as shown above.
* Show your output here, on this page.
| seed = 675248
function rnd ()
local s = tostring(seed * seed)
while #s ~= 12 do
s = "0" .. s
end
seed = tonumber(s:sub(4, 9))
return seed
end
for i = 1, 5 do
print(rnd())
end
|
Pseudo-random numbers/PCG32 | Lua from C | Some definitions to help in the explanation:
:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.
:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.
:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100
:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101
:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110
:'''|''' Bitwise or operator
::https://en.wikipedia.org/wiki/Bitwise_operation#OR
::Bitwise comparison gives 1 if any of corresponding bits are 1
:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111
;PCG32 Generator (pseudo-code):
PCG32 has two unsigned 64-bit integers of internal state:
# '''state''': All 2**64 values may be attained.
# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).
Values of sequence allow 2**63 ''different'' sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers using the above.
* Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
:Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
* Show your output here, on this page.
| function uint32(n)
return n & 0xffffffff
end
function uint64(n)
return n & 0xffffffffffffffff
end
N = 6364136223846793005
state = 0x853c49e6748fea9b
inc = 0xda3e39cb94b95bdb
function pcg32_seed(seed_state, seed_sequence)
state = 0
inc = (seed_sequence << 1) | 1
pcg32_int()
state = state + seed_state
pcg32_int()
end
function pcg32_int()
local old = state
state = uint64(old * N + inc)
local shifted = uint32(((old >> 18) ~ old) >> 27)
local rot = uint32(old >> 59)
return uint32((shifted >> rot) | (shifted << ((~rot + 1) & 31)))
end
function pcg32_float()
return 1.0 * pcg32_int() / (1 << 32)
end
-------------------------------------------------------------------
pcg32_seed(42, 54)
print(pcg32_int())
print(pcg32_int())
print(pcg32_int())
print(pcg32_int())
print(pcg32_int())
print()
counts = { 0, 0, 0, 0, 0 }
pcg32_seed(987654321, 1)
for i=1,100000 do
local j = math.floor(pcg32_float() * 5.0) + 1
counts[j] = counts[j] + 1
end
print("The counts for 100,000 repetitions are:")
for i=1,5 do
print(" " .. (i - 1) .. ": " .. counts[i])
end |
Pseudo-random numbers/Xorshift star | Lua from C | Some definitions to help in the explanation:
:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.
:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.
:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100
:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101
:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110
;Xorshift_star Generator (pseudo-code):
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
:;Xorshift use:
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers as shown above.
* Show that the first five integers genrated with the seed 1234567
are as shown above
* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
:Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
* Show your output here, on this page.
| function create()
local g = {
magic = 0x2545F4914F6CDD1D,
state = 0,
seed = function(self, num)
self.state = num
end,
next_int = function(self)
local x = self.state
x = x ~ (x >> 12)
x = x ~ (x << 25)
x = x ~ (x >> 27)
self.state = x
local answer = (x * self.magic) >> 32
return answer
end,
next_float = function(self)
return self:next_int() / (1 << 32)
end
}
return g
end
local g = create()
g:seed(1234567)
print(g:next_int())
print(g:next_int())
print(g:next_int())
print(g:next_int())
print(g:next_int())
print()
local counts = {[0]=0, [1]=0, [2]=0, [3]=0, [4]=0}
g:seed(987654321)
for i=1,100000 do
local j = math.floor(g:next_float() * 5.0)
counts[j] = counts[j] + 1
end
for i,v in pairs(counts) do
print(i..': '..v)
end |
Pythagorean quadruples | Lua | One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''):
:::::::: a2 + b2 + c2 = d2
An example:
:::::::: 22 + 32 + 62 = 72
::::: which is:
:::::::: 4 + 9 + 36 = 49
;Task:
For positive integers up '''2,200''' (inclusive), for all values of '''a''',
'''b''', '''c''', and '''d''',
find (and show here) those values of '''d''' that ''can't'' be represented.
Show the values of '''d''' on one line of output (optionally with a title).
;Related tasks:
* [[Euler's sum of powers conjecture]].
* [[Pythagorean triples]].
;Reference:
:* the Wikipedia article: Pythagorean quadruple.
| -- initialize
local N = 2200
local ar = {}
for i=1,N do
ar[i] = false
end
-- process
for a=1,N do
for b=a,N do
if (a % 2 ~= 1) or (b % 2 ~= 1) then
local aabb = a * a + b * b
for c=b,N do
local aabbcc = aabb + c * c
local d = math.floor(math.sqrt(aabbcc))
if (aabbcc == d * d) and (d <= N) then
ar[d] = true
end
end
end
end
-- print('done with a='..a)
end
-- print
for i=1,N do
if not ar[i] then
io.write(i.." ")
end
end
print() |
Quaternion type | Lua | complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''.
A quaternion has one real part and ''three'' imaginary parts, i, j, and k.
A quaternion might be written as a + bi + cj + dk.
In the quaternion numbering system:
:::* ii = jj = kk = ijk = -1, or more simply,
:::* ii = jj = kk = ijk = -1.
The order of multiplication is important, as, in general, for two quaternions:
:::: q1 and q2: q1q2 q2q1.
An example of a quaternion might be 1 +2i +3j +4k
There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position.
So the example above would be written as (1, 2, 3, 4)
;Task:
Given the three quaternions and their components:
q = (1, 2, 3, 4) = (a, b, c, d)
q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)
q2 = (3, 4, 5, 6) = (a2, b2, c2, d2)
And a wholly real number r = 7.
Create functions (or classes) to perform simple maths with quaternions including computing:
# The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2}
# The negative of a quaternion: = (-a, -b, -c, -d)
# The conjugate of a quaternion: = ( a, -b, -c, -d)
# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d)
# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2)
# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr)
# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 )
# Show that, for the two quaternions q1 and q2: q1q2 q2q1
If a language has built-in support for quaternions, then use it.
;C.f.:
* [[Vector products]]
* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
| Quaternion = {}
function Quaternion.new( a, b, c, d )
local q = { a = a or 1, b = b or 0, c = c or 0, d = d or 0 }
local metatab = {}
setmetatable( q, metatab )
metatab.__add = Quaternion.add
metatab.__sub = Quaternion.sub
metatab.__unm = Quaternion.unm
metatab.__mul = Quaternion.mul
return q
end
function Quaternion.add( p, q )
if type( p ) == "number" then
return Quaternion.new( p+q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a+q, p.b, p.c, p.d )
else
return Quaternion.new( p.a+q.a, p.b+q.b, p.c+q.c, p.d+q.d )
end
end
function Quaternion.sub( p, q )
if type( p ) == "number" then
return Quaternion.new( p-q.a, q.b, q.c, q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a-q, p.b, p.c, p.d )
else
return Quaternion.new( p.a-q.a, p.b-q.b, p.c-q.c, p.d-q.d )
end
end
function Quaternion.unm( p )
return Quaternion.new( -p.a, -p.b, -p.c, -p.d )
end
function Quaternion.mul( p, q )
if type( p ) == "number" then
return Quaternion.new( p*q.a, p*q.b, p*q.c, p*q.d )
elseif type( q ) == "number" then
return Quaternion.new( p.a*q, p.b*q, p.c*q, p.d*q )
else
return Quaternion.new( p.a*q.a - p.b*q.b - p.c*q.c - p.d*q.d,
p.a*q.b + p.b*q.a + p.c*q.d - p.d*q.c,
p.a*q.c - p.b*q.d + p.c*q.a + p.d*q.b,
p.a*q.d + p.b*q.c - p.c*q.b + p.d*q.a )
end
end
function Quaternion.conj( p )
return Quaternion.new( p.a, -p.b, -p.c, -p.d )
end
function Quaternion.norm( p )
return math.sqrt( p.a^2 + p.b^2 + p.c^2 + p.d^2 )
end
function Quaternion.print( p )
print( string.format( "%f + %fi + %fj + %fk\n", p.a, p.b, p.c, p.d ) )
end |
Quine | Lua | A quine is a self-referential program that can,
without any external access, output its own source.
A '''quine''' (named after Willard Van Orman Quine) is also known as:
::* ''self-reproducing automata'' (1972)
::* ''self-replicating program'' or ''self-replicating computer program''
::* ''self-reproducing program'' or ''self-reproducing computer program''
::* ''self-copying program'' or ''self-copying computer program''
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
;Task:
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
** Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
** If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
'''Next to the Quines presented here, many other versions can be found on the Quine page.'''
;Related task:
:* print itself.
| s=[[io.write('s=[','[',s,']','];',s)]];io.write('s=[','[',s,']','];',s) |
Quoting constructs | Lua | Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?
This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, '''NOT''' just a link to [See the language docs].
Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
| s1 = "This is a double-quoted 'string' with embedded single-quotes."
s2 = 'This is a single-quoted "string" with embedded double-quotes.'
s3 = "this is a double-quoted \"string\" with escaped double-quotes."
s4 = 'this is a single-quoted \'string\' with escaped single-quotes.'
s5 = [[This is a long-bracket "'string'" with embedded single- and double-quotes.]]
s6 = [=[This is a level 1 long-bracket ]]string[[ with [[embedded]] long-brackets.]=]
s7 = [==[This is a level 2 long-bracket ]=]string[=[ with [=[embedded]=] level 1 long-brackets, etc.]==]
s8 = [[This is
a long-bracket string
with embedded
line feeds]]
s9 = "any \0 form \1 of \2 string \3 may \4 contain \5 raw \6 binary \7 data \xDB"
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(s6)
print(s7)
print(s8)
print(s9) -- with audible "bell" from \7 if supported by os
print("some raw binary:", #s9, s9:byte(5), s9:byte(12), s9:byte(17)) |
Random number generator (included) | Lua | The task is to:
: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
: If possible, give a link to a wider explanation of the algorithm used.
Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
| Lua's <code>math.random()</code> is an interface to the C <code>rand()</code> function provided by the OS libc; its implementation varies by platform.
|
Range expansion | Lua | {{:Range extraction/Format}}
;Task:
Expand the range description:
-6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the '''range from minus 3 to ''minus'' 1'''.
;Related task:
* [[Range extraction]]
| function range(i, j)
local t = {}
for n = i, j, i<j and 1 or -1 do
t[#t+1] = n
end
return t
end
function expand_ranges(rspec)
local ptn = "([-+]?%d+)%s?-%s?([-+]?%d+)"
local t = {}
for v in string.gmatch(rspec, '[^,]+') do
local s, e = v:match(ptn)
if s == nil then
t[#t+1] = tonumber(v)
else
for i, n in ipairs(range(tonumber(s), tonumber(e))) do
t[#t+1] = n
end
end
end
return t
end
local ranges = "-6,-3--1,3-5,7-11,14,15,17-20"
print(table.concat(expand_ranges(ranges), ', ')) |
Range extraction | Lua | {{:Range extraction/Format}}
;Task:
* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
* Show the output of your program.
;Related task:
* [[Range expansion]]
| function extractRange (rList)
local rExpr, startVal = ""
for k, v in pairs(rList) do
if rList[k + 1] == v + 1 then
if not startVal then startVal = v end
else
if startVal then
if v == startVal + 1 then
rExpr = rExpr .. startVal .. "," .. v .. ","
else
rExpr = rExpr .. startVal .. "-" .. v .. ","
end
startVal = nil
else
rExpr = rExpr .. v .. ","
end
end
end
return rExpr:sub(1, -2)
end
local intList = {
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
}
print(extractRange(intList)) |
Read a specific line from a file | Lua | Some languages have special semantics for obtaining a known line number from a file.
;Task:
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
| function fileLine (lineNum, fileName)
local count = 0
for line in io.lines(fileName) do
count = count + 1
if count == lineNum then return line end
end
error(fileName .. " has fewer than " .. lineNum .. " lines.")
end
print(fileLine(7, "test.txt")) |
Recaman's sequence | Lua from C++ | The '''Recaman's sequence''' generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.
If the conditions ''don't'' hold then a(n) = a(n-1) + n.
;Task:
# Generate and show here the first 15 members of the sequence.
# Find and show here, the first duplicated number in the sequence.
# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.
;References:
* A005132, The On-Line Encyclopedia of Integer Sequences.
* The Slightly Spooky Recaman Sequence, Numberphile video.
* Recaman's sequence, on Wikipedia.
| local a = {[0]=0}
local used = {[0]=true}
local used1000 = {[0]=true}
local foundDup = false
local n = 1
while n<=15 or not foundDup or #used1000<1001 do
local nxt = a[n - 1] - n
if nxt<1 or used[nxt] ~= nil then
nxt = nxt + 2 * n
end
local alreadyUsed = used[nxt] ~= nil
table.insert(a, nxt)
if not alreadyUsed then
used[nxt] = true
if 0<=nxt and nxt<=1000 then
used1000[nxt] = true
end
end
if n==14 then
io.write("The first 15 terms of the Recaman sequence are:")
for k=0,#a do
io.write(" "..a[k])
end
print()
end
if not foundDup and alreadyUsed then
print("The first duplicated term is a["..n.."] = "..nxt)
foundDup = true
end
if #used1000 == 1001 then
print("Terms up to a["..n.."] are needed to generate 0 to 1000")
end
n = n + 1
end |
Remove lines from a file | Lua | Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2
Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.
An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
| function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end |
Repeat | Lua | Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| function myFunc ()
print("Sure looks like a function in here...")
end
function rep (func, times)
for count = 1, times do
func()
end
end
rep(myFunc, 4)
|
Reverse words in a string | Lua | Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
;Example:
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
;Input data
(ten lines within the box)
line
+----------------------------------------+
1 | ---------- Ice and Fire ------------ |
2 | | <--- a blank line here.
3 | fire, in end will world the say Some |
4 | ice. in say Some |
5 | desire of tasted I've what From |
6 | fire. favor who those with hold I |
7 | | <--- a blank line here.
8 | ... elided paragraph last ... |
9 | | <--- a blank line here.
10 | Frost Robert ----------------------- |
+----------------------------------------+
;Cf.
* [[Phrase reversals]]
| function table.reverse(a)
local res = {}
for i = #a, 1, -1 do
res[#res+1] = a[i]
end
return res
end
function splittokens(s)
local res = {}
for w in s:gmatch("%S+") do
res[#res+1] = w
end
return res
end
for line, nl in s:gmatch("([^\n]-)(\n)") do
print(table.concat(table.reverse(splittokens(line)), ' '))
end |
Roman numerals/Decode | Lua | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s (zeroes).
'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and
'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).
The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
| function ToNumeral( roman )
local Num = { ["M"] = 1000, ["D"] = 500, ["C"] = 100, ["L"] = 50, ["X"] = 10, ["V"] = 5, ["I"] = 1 }
local numeral = 0
local i = 1
local strlen = string.len(roman)
while i < strlen do
local z1, z2 = Num[ string.sub(roman,i,i) ], Num[ string.sub(roman,i+1,i+1) ]
if z1 < z2 then
numeral = numeral + ( z2 - z1 )
i = i + 2
else
numeral = numeral + z1
i = i + 1
end
end
if i <= strlen then numeral = numeral + Num[ string.sub(roman,i,i) ] end
return numeral
end
print( ToNumeral( "MCMXC" ) )
print( ToNumeral( "MMVIII" ) )
print( ToNumeral( "MDCLXVI" ) ) |
Roman numerals/Encode | Lua | Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| romans = {
{1000, "M"},
{900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"},
{90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"},
{9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} }
k = io.read() + 0
for _, v in ipairs(romans) do --note that this is -not- ipairs.
val, let = unpack(v)
while k >= val do
k = k - val
io.write(let)
end
end
print() |
Runge-Kutta method | Lua | Given the example Differential equation:
:y'(t) = t \times \sqrt {y(t)}
With initial condition:
:t_0 = 0 and y_0 = y(t_0) = y(0) = 1
This equation has an exact solution:
:y(t) = \tfrac{1}{16}(t^2 +4)^2
;Task
Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.
* Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given)
* Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution.
;Method summary
Starting with a given y_n and t_n calculate:
:\delta y_1 = \delta t\times y'(t_n, y_n)\quad
:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1)
:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2)
:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad
then:
:y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4)
:t_{n+1} = t_n + \delta t\quad
| local df = function (t, y)
-- derivative of function by value y at time t
return t*y^0.5
end
local dt = 0.1
local y = 1
print ("t", "realY"..' ', "y", ' '.."error")
print ("---", "-------"..' ', "---------------", ' '.."--------------------")
for i = 0, 100 do
local t = i*dt
if t%1 == 0 then
local realY = (t*t+4)^2/16
print (t, realY..' ', y, ' '..realY-y)
end
local dy1 = df(t, y)
local dy2 = df(t+dt/2, y+dt/2*dy1)
local dy3 = df(t+dt/2, y+dt/2*dy2)
local dy4 = df(t+dt, y+dt*dy3)
y = y + dt*(dy1+2*dy2+2*dy3+dy4)/6
end |
Runtime evaluation | Lua | Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].
| f = loadstring(s) -- load a string as a function. Returns a function.
one = loadstring"return 1" -- one() returns 1
two = loadstring"return ..." -- two() returns the arguments passed to it |
Runtime evaluation | Lua 5.2 | Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.
You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.
For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].
| > f = load("return 42")
> f()
42
> n = load("return 42")()
> n
42 |
Runtime evaluation/In an environment | Lua | Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.
Do so in a way which:
* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just x
* does not make x a ''global'' variable
or note that these are impossible.
;See also:
* For more general examples and language-specific details, see [[Eval]].
* [[Dynamic variable names]] is a similar task.
| code = loadstring"return x^2" --this doesn't really need to be input, does it?
val1 = setfenv(code, {x = io.read() + 0})()
val2 = setfenv(code, {x = io.read() + 0})()
print(val2 - val1)
|
Runtime evaluation/In an environment | Lua 5.2 | Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.
Do so in a way which:
* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just x
* does not make x a ''global'' variable
or note that these are impossible.
;See also:
* For more general examples and language-specific details, see [[Eval]].
* [[Dynamic variable names]] is a similar task.
| env = {}
f = load("return x", nil, nil, env)
env.x = tonumber(io.read()) -- user enters 2
a = f()
env.x = tonumber(io.read()) -- user enters 3
b = f()
print(a + b) --> outputs 5 |
Sailors, coconuts and a monkey problem | Lua from C | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
;The task:
# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)
# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
# Show your answers here.
;Extra credit (optional):
* Give some indication of the number of coconuts each sailor hides during the night.
;Note:
* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!
;C.f:
* Monkeys and Coconuts - Numberphile (Video) Analytical solution.
* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
| function valid(n,nuts)
local k = n
local i = 0
while k ~= 0 do
if (nuts % n) ~= 1 then
return false
end
k = k - 1
nuts = nuts - 1 - math.floor(nuts / n)
end
return nuts ~= 0 and (nuts % n == 0)
end
for n=2, 9 do
local x = 0
while not valid(n, x) do
x = x + 1
end
print(n..": "..x)
end |
Same fringe | Lua | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
| local type, insert, remove = type, table.insert, table.remove
None = {} -- a unique object for a truncated branch (i.e. empty subtree)
function isbranch(node) return type(node) == 'table' and #node == 2 end
function left(node) return node[1] end
function right(node) return node[2] end
function fringeiter(tree)
local agenda = {tree}
local function push(item) insert(agenda, item) end
local function pop() return remove(agenda) end
return function()
while #agenda > 0 do
node = pop()
if isbranch(node) then
push(right(node))
push(left(node))
elseif node == None then
-- continue
else
return node
end
end
end
end
function same_fringe(atree, btree)
local anext = fringeiter(atree or None)
local bnext = fringeiter(btree or None)
local pos = 0
repeat
local aitem, bitem = anext(), bnext()
pos = pos + 1
if aitem ~= bitem then
return false, string.format("at position %d, %s ~= %s", pos, aitem, bitem)
end
until not aitem
return true
end
t1 = {1, {2, {3, {4, {5, None}}}}}
t2 = {{1,2}, {{3, 4}, 5}}
t3 = {{{1,2}, 3}, 4}
function compare_fringe(label, ta, tb)
local equal, nonmatch = same_fringe(ta, tb)
io.write(label .. ": ")
if equal then
print("same fringe")
else
print(nonmatch)
end
end
compare_fringe("(t1, t2)", t1, t2)
compare_fringe("(t1, t3)", t1, t3)
|
Self-describing numbers | Lua | {{task}}There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.
For example, '''2020''' is a four-digit self describing number:
* position 0 has value 2 and there are two 0s in the number;
* position 1 has value 0 and there are no 1s in the number;
* position 2 has value 2 and there are two 2s;
* position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
;Task Description
# Write a function/routine/method/... that will check whether a given positive integer is self-describing.
# As an optional stretch goal - generate and display the set of self-describing numbers.
;Related tasks:
* [[Fours is the number of letters in the ...]]
* [[Look-and-say sequence]]
* [[Number names]]
* [[Self-referential sequence]]
* [[Spelling of ordinal numbers]]
| function Is_self_describing( n )
local s = tostring( n )
local t = {}
for i = 0, 9 do t[i] = 0 end
for i = 1, s:len() do
local idx = tonumber( s:sub(i,i) )
t[idx] = t[idx] + 1
end
for i = 1, s:len() do
if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end
end
return true
end
for i = 1, 999999999 do
print( Is_self_describing( i ) )
end |
Semordnilap | Lua | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: ''lager'' and ''regal''
;Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
| #!/usr/bin/env lua
-- allow dictionary file and sample size to be specified on command line
local dictfile = arg[1] or "unixdict.txt"
local sample_size = arg[2] or 5;
-- read dictionary
local f = assert(io.open(dictfile, "r"))
local dict = {}
for line in f:lines() do
dict[line] = line:reverse()
end
f:close()
-- find the semordnilaps
local semordnilaps = {}
for fwd, rev in pairs(dict) do
if dict[rev] and fwd < rev then
table.insert(semordnilaps, {fwd,rev})
end
end
-- print the report
print("There are " .. #semordnilaps .. " semordnilaps in " .. dictfile .. ". Here are " .. sample_size .. ":")
math.randomseed( os.time() )
for i = 1, sample_size do
local j
repeat
j = math.random(1,#semordnilaps)
until semordnilaps[j]
local f, r = unpack(semordnilaps[j])
semordnilaps[j] = nil
print(f .. " -> " .. r)
end |
Set consolidation | Lua | Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:
* The two input sets if no common item exists between the two input sets of items.
* The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
;'''Example 1:'''
:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
;'''Example 2:'''
:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
;'''Example 3:'''
:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
;'''Example 4:'''
:The consolidation of the five sets:
::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
:Is the two sets:
::{A, C, B, D}, and {G, F, I, H, K}
'''See also'''
* Connected component (graph theory)
* [[Range consolidation]]
| -- SUPPORT:
function T(t) return setmetatable(t, {__index=table}) end
function S(t) local s=T{} for k,v in ipairs(t) do s[v]=v end return s end
table.each = function(t,f,...) for _,v in pairs(t) do f(v,...) end end
table.copy = function(t) local s=T{} for k,v in pairs(t) do s[k]=v end return s end
table.keys = function(t) local s=T{} for k,_ in pairs(t) do s[#s+1]=k end return s end
table.intersects = function(t1,t2) for k,_ in pairs(t1) do if t2[k] then return true end end return false end
table.union = function(t1,t2) local s=t1:copy() for k,_ in pairs(t2) do s[k]=k end return s end
table.dump = function(t) print('{ '..table.concat(t, ', ')..' }') end
-- TASK:
table.consolidate = function(t)
for a = #t, 1, -1 do
local seta = t[a]
for b = #t, a+1, -1 do
local setb = t[b]
if setb and seta:intersects(setb) then
t[a], t[b] = seta:union(setb), nil
end
end
end
return t
end
-- TESTING:
examples = {
T{ S{"A","B"}, S{"C","D"} },
T{ S{"A","B"}, S{"B","D"} },
T{ S{"A","B"}, S{"C","D"}, S{"D","B"} },
T{ S{"H","I","K"}, S{"A","B"}, S{"C","D"}, S{"D","B"}, S{"F","G","H"} },
}
for i,example in ipairs(examples) do
print("Given input sets:")
example:each(function(set) set:keys():dump() end)
print("Consolidated output sets:")
example:consolidate():each(function(set) set:keys():dump() end)
print("")
end |
Set of real numbers | Lua | All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of "between", depending on open or closed boundary:
* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }
* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }
* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }
* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }
Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.
'''Task'''
* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):
:* ''x'' ''A'': determine if ''x'' is an element of ''A''
:: example: 1 is in [1, 2), while 2, 3, ... are not.
:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}
:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]
:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set
:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) - (1, 3) = [0, 1]
* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
:* (0, 1] [0, 2)
:* [0, 2) (1, 2]
:* [0, 3) - (0, 1)
:* [0, 3) - [0, 1]
'''Implementation notes'''
* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
'''Optional work'''
* Create a function to determine if a given set is empty (contains no element).
* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that
|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.
| function createSet(low,high,rt)
local l,h = tonumber(low), tonumber(high)
if l and h then
local t = {low=l, high=h}
if type(rt) == "string" then
if rt == "open" then
t.contains = function(d) return low< d and d< high end
elseif rt == "closed" then
t.contains = function(d) return low<=d and d<=high end
elseif rt == "left" then
t.contains = function(d) return low< d and d<=high end
elseif rt == "right" then
t.contains = function(d) return low<=d and d< high end
else
error("Unknown range type: "..rt)
end
elseif type(rt) == "function" then
t.contains = rt
else
error("Unable to find a range type or predicate")
end
t.union = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) or o.contains(d) end
return createSet(l2, h2, p)
end
t.intersect = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) and o.contains(d) end
return createSet(l2, h2, p)
end
t.subtract = function(o)
local l2 = math.min(l, o.low)
local h2 = math.min(h, o.high)
local p = function(d) return t.contains(d) and not o.contains(d) end
return createSet(l2, h2, p)
end
t.length = function()
if h <= l then return 0.0 end
local p = l
local count = 0
local interval = 0.00001
repeat
if t.contains(p) then count = count + 1 end
p = p + interval
until p>=high
return count * interval
end
t.empty = function()
if l == h then
return not t.contains(low)
end
return t.length() == 0.0
end
return t
else
error("Either '"..low.."' or '"..high.."' is not a number")
end
end
local a = createSet(0.0, 1.0, "left")
local b = createSet(0.0, 2.0, "right")
local c = createSet(1.0, 2.0, "left")
local d = createSet(0.0, 3.0, "right")
local e = createSet(0.0, 1.0, "open")
local f = createSet(0.0, 1.0, "closed")
local g = createSet(0.0, 0.0, "closed")
for i=0,2 do
print("(0, 1] union [0, 2) contains "..i.." is "..tostring(a.union(b).contains(i)))
print("[0, 2) intersect (1, 2] contains "..i.." is "..tostring(b.intersect(c).contains(i)))
print("[0, 3) - (0, 1) contains "..i.." is "..tostring(d.subtract(e).contains(i)))
print("[0, 3) - [0, 1] contains "..i.." is "..tostring(d.subtract(f).contains(i)))
print()
end
print("[0, 0] is empty is "..tostring(g.empty()))
print()
local aa = createSet(
0.0, 10.0,
function(x) return (0.0<x and x<10.0) and math.abs(math.sin(math.pi * x * x)) > 0.5 end
)
local bb = createSet(
0.0, 10.0,
function(x) return (0.0<x and x<10.0) and math.abs(math.sin(math.pi * x)) > 0.5 end
)
local cc = aa.subtract(bb)
print("Approx length of A - B is "..cc.length()) |
Shoelace formula for polygonal area | Lua | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
;Task:
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| function shoeArea(ps)
local function ssum(acc, p1, p2, ...)
if not p2 or not p1 then
return math.abs(0.5 * acc)
else
return ssum(acc + p1[1]*p2[2]-p1[2]*p2[1], p2, ...)
end
end
return ssum(0, ps[#ps], table.unpack(ps))
end
local p = {{3,4}, {5,11}, {12,8}, {9,5}, {5,6}}
print(shoeArea(p))-- 30 |
Show ASCII table | Lua from Go | Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.
| -- map of character values to desired representation
local chars = setmetatable({[32] = "Spc", [127] = "Del"}, {__index = function(_, k) return string.char(k) end})
-- row iterator
local function iter(s,a)
a = (a or s) + 16
if a <= 127 then return a, chars[a] end
end
-- print loop
for i = 0, 15 do
for j, repr in iter, i+16 do
io.write(("%3d : %3s "):format(j, repr))
end
io.write"\n"
end |
Sierpinski pentagon | Lua | Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.
;See also
* Sierpinski pentagon
| Bitmap.chaosgame = function(self, n, r, niters)
local w, h, vertices = self.width, self.height, {}
for i = 1, n do
vertices[i] = {
x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n),
y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n)
}
end
local x, y = w/2, h/2
for i = 1, niters do
local v = math.random(n)
x = x + r * (vertices[v].x - x)
y = y + r * (vertices[v].y - y)
self:set(x,y,0xFFFFFFFF)
end
end
local bitmap = Bitmap(128, 128)
bitmap:chaosgame(5, 1/((1+math.sqrt(5))/2), 1e6)
bitmap:render({[0x000000]='..', [0xFFFFFFFF]='██'}) |
Smith numbers | Lua | sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are ''excluded'' as they (naturally) satisfy this condition!
Smith numbers are also known as ''joke'' numbers.
;Example
Using the number '''166'''
Find the prime factors of '''166''' which are: '''2''' x '''83'''
Then, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''
Then, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''
Therefore, the number '''166''' is a Smith number.
;Task
Write a program to find all Smith numbers ''below'' 10000.
;See also
* from Wikipedia: [Smith number].
* from MathWorld: [Smith number].
* from OEIS A6753: [OEIS sequence A6753].
* from OEIS A104170: [Number of Smith numbers below 10^n].
* from The Prime pages: [Smith numbers].
| -- Returns a boolean indicating whether n is prime
function isPrime (n)
if n < 2 then return false end
if n < 4 then return true end
if n % 2 == 0 then return false end
for d = 3, math.sqrt(n), 2 do
if n % d == 0 then return false end
end
return true
end
-- Returns a table of the prime factors of n
function primeFactors (n)
local pfacs, divisor = {}, 1
if n < 1 then return pfacs end
while not isPrime(n) do
while not isPrime(divisor) do divisor = divisor + 1 end
while n % divisor == 0 do
n = n / divisor
table.insert(pfacs, divisor)
end
divisor = divisor + 1
if n == 1 then return pfacs end
end
table.insert(pfacs, n)
return pfacs
end
-- Returns the sum of the digits of n
function sumDigits (n)
local sum, nStr = 0, tostring(n)
for digit = 1, nStr:len() do
sum = sum + tonumber(nStr:sub(digit, digit))
end
return sum
end
-- Returns a boolean indicating whether n is a Smith number
function isSmith (n)
if isPrime(n) then return false end
local sumFacs = 0
for _, v in ipairs(primeFactors(n)) do
sumFacs = sumFacs + sumDigits(v)
end
return sumFacs == sumDigits(n)
end
-- Main procedure
for n = 1, 10000 do
if isSmith(n) then io.write(n .. "\t") end
end |
Solve a Holy Knight's tour | Lua | Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution to such problems. At least demonstrate your program by solving the following:
;Example:
0 0 0
0 0 0
0 0 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0 0 0
0 0 0
0 0 0
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
;Related tasks:
* [[A* search algorithm]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8
local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13
local puzzle, movesCnt, wid = {}, 0, 0
local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 },
{ -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } }
function isValid( x, y )
return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 )
end
function solve( x, y, s )
if s > movesCnt then return true end
local test, a, b
for i = 1, #moves do
test = false
a = x + moves[i][1]; b = y + moves[i][2]
if isValid( a, b ) then
puzzle[a + b * wid - wid] = s
if solve( a, b, s + 1 ) then return true end
puzzle[a + b * wid - wid] = 0
end
end
return false
end
function printSolution()
local lp
for j = 1, wid do
for i = 1, wid do
lp = puzzle[i + j * wid - wid]
if lp == -1 then io.write( " " )
else io.write( string.format( " %.2d", lp ) )
end
end
print()
end
print( "\n" )
end
local sx, sy
function fill( pz, w )
puzzle = {}; wid = w; movesCnt = #pz
local lp
for i = 1, #pz do
lp = pz:sub( i, i )
if lp == "x" then
table.insert( puzzle, 0 )
elseif lp == "." then
table.insert( puzzle, -1 ); movesCnt = movesCnt - 1
else
table.insert( puzzle, 1 )
sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid )
end
end
end
-- [[ entry point ]] --
print( "\n\n" ); fill( p1, p1W );
if solve( sx, sy, 2 ) then printSolution() end
print( "\n\n" ); fill( p2, p2W );
if solve( sx, sy, 2 ) then printSolution() end
|
Split a character string based on change of character | Lua | Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
| function charSplit (inStr)
local outStr, nextChar = inStr:sub(1, 1)
for pos = 2, #inStr do
nextChar = inStr:sub(pos, pos)
if nextChar ~= outStr:sub(#outStr, #outStr) then
outStr = outStr .. ", "
end
outStr = outStr .. nextChar
end
return outStr
end
print(charSplit("gHHH5YY++///\\")) |
Square-free integers | Lua | Write a function to test if a number is ''square-free''.
A ''square-free'' is an integer which is divisible by no perfect square other
than '''1''' (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
::* '''1''' ---> '''145''' (inclusive)
::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
::* '''1''' ---> one hundred (inclusive)
::* '''1''' ---> one thousand (inclusive)
::* '''1''' ---> ten thousand (inclusive)
::* '''1''' ---> one hundred thousand (inclusive)
::* '''1''' ---> one million (inclusive)
;See also:
:* the Wikipedia entry: square-free integer
| function squareFree (n)
for root = 2, math.sqrt(n) do
if n % (root * root) == 0 then return false end
end
return true
end
function run (lo, hi, showValues)
io.write("From " .. lo .. " to " .. hi)
io.write(showValues and ":\n" or " = ")
local count = 0
for i = lo, hi do
if squareFree(i) then
if showValues then
io.write(i, "\t")
else
count = count + 1
end
end
end
print(showValues and "\n" or count)
end
local testCases = {
{1, 145, true},
{1000000000000, 1000000000145, true},
{1, 100},
{1, 1000},
{1, 10000},
{1, 100000},
{1, 1000000}
}
for _, example in pairs(testCases) do run(unpack(example)) end |
Square but not cube | Lua | Show the first '''30''' positive integers which are squares but not cubes of such integers.
Optionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.
| function nthroot (x, n)
local r = 1
for i = 1, 16 do
r = (((n - 1) * r) + x / (r ^ (n - 1))) / n
end
return r
end
local i, count, sq, cbrt = 0, 0
while count < 30 do
i = i + 1
sq = i * i
-- The next line should say nthroot(sq, 3), right? But this works. Maths, eh?
cbrt = nthroot(i, 3)
if cbrt == math.floor(cbrt) then
print(sq .. " is square and cube")
else
print(sq)
count = count + 1
end
end |
Stair-climbing puzzle | Lua | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
* Base case (if the step() call returns true): it stepped up one step. QED
* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| function step_up()
while not step() do step_up() end
end
|
Statistics/Normal distribution | Lua | The derive normally distributed random numbers from a uniform generator.
;The task:
# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
# Mention any native language support for the generation of normally distributed random numbers.
;Reference:
* You may refer to code in [[Statistics/Basic]] if available.
| function gaussian (mean, variance)
return math.sqrt(-2 * variance * math.log(math.random())) *
math.cos(2 * math.pi * math.random()) + mean
end
function mean (t)
local sum = 0
for k, v in pairs(t) do
sum = sum + v
end
return sum / #t
end
function std (t)
local squares, avg = 0, mean(t)
for k, v in pairs(t) do
squares = squares + ((avg - v) ^ 2)
end
local variance = squares / #t
return math.sqrt(variance)
end
function showHistogram (t)
local lo = math.ceil(math.min(unpack(t)))
local hi = math.floor(math.max(unpack(t)))
local hist, barScale = {}, 200
for i = lo, hi do
hist[i] = 0
for k, v in pairs(t) do
if math.ceil(v - 0.5) == i then
hist[i] = hist[i] + 1
end
end
io.write(i .. "\t" .. string.rep('=', hist[i] / #t * barScale))
print(" " .. hist[i])
end
end
math.randomseed(os.time())
local t, average, variance = {}, 50, 10
for i = 1, 1000 do
table.insert(t, gaussian(average, variance))
end
print("Mean:", mean(t) .. ", expected " .. average)
print("StdDev:", std(t) .. ", expected " .. math.sqrt(variance) .. "\n")
showHistogram(t) |
Stern-Brocot sequence | Lua | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].
# The first and second members of the sequence are both 1:
#* 1, 1
# Start by considering the second member of the sequence
# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
#* 1, 1, 2
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1
# Consider the next member of the series, (the third member i.e. 2)
# GOTO 3
#*
#* --- Expanding another loop we get: ---
#*
# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
#* 1, 1, 2, 1, 3
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1, 3, 2
# Consider the next member of the series, (the fourth member i.e. 1)
;The task is to:
* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
;Related tasks:
:* [[Fusc sequence]].
:* [[Continued fraction/Arithmetic]]
;Ref:
* Infinite Fractions - Numberphile (Video).
* Trees, Teeth, and Time: The mathematics of clock making.
* A002487 The On-Line Encyclopedia of Integer Sequences.
| -- Task 1
function sternBrocot (n)
local sbList, pos, c = {1, 1}, 2
repeat
c = sbList[pos]
table.insert(sbList, c + sbList[pos - 1])
table.insert(sbList, c)
pos = pos + 1
until #sbList >= n
return sbList
end
-- Return index in table 't' of first value matching 'v'
function findFirst (t, v)
for key, value in pairs(t) do
if v then
if value == v then return key end
else
if value ~= 0 then return key end
end
end
return nil
end
-- Return greatest common divisor of 'x' and 'y'
function gcd (x, y)
if y == 0 then
return math.abs(x)
else
return gcd(y, x % y)
end
end
-- Check GCD of adjacent values in 't' up to 1000 is always 1
function task5 (t)
for pos = 1, 1000 do
if gcd(t[pos], t[pos + 1]) ~= 1 then return "FAIL" end
end
return "PASS"
end
-- Main procedure
local sb = sternBrocot(10000)
io.write("Task 2: ")
for n = 1, 15 do io.write(sb[n] .. " ") end
print("\n\nTask 3:")
for i = 1, 10 do print("\t" .. i, findFirst(sb, i)) end
print("\nTask 4: " .. findFirst(sb, 100))
print("\nTask 5: " .. task5(sb)) |
Strip control codes and extended characters from a string | Lua | Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
:* a string with control codes stripped (but extended characters not stripped)
:* a string with control codes and extended characters stripped
In ASCII, the control codes have decimal codes 0 through to 31 and 127.
On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.
On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
| function Strip_Control_Codes( str )
local s = ""
for i in str:gmatch( "%C+" ) do
s = s .. i
end
return s
end
function Strip_Control_and_Extended_Codes( str )
local s = ""
for i = 1, str:len() do
if str:byte(i) >= 32 and str:byte(i) <= 126 then
s = s .. str:sub(i,i)
end
end
return s
end
q = ""
for i = 0, 255 do
q = q .. string.char(i)
end
print( Strip_Control_Codes(q) )
print( Strip_Control_and_Extended_Codes(q) ) |
Subleq | Lua | One-Instruction Set Computer (OISC).
It is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero.
;Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:
::::* simple numeric values
::::* memory addresses
::::* characters for input or output
Any reasonable word size that accommodates all three of the above uses is fine.
The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:
:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.
:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.
:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.
:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.
:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.
:# If the instruction pointer becomes negative, execution halts.
Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).
For purposes of this task, show the output of your solution when fed the below "Hello, world!" program.
As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.
15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0
The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:
start:
0f 11 ff subleq (zero), (message), -1
11 ff ff subleq (message), -1, -1 ; output character at message
10 01 ff subleq (neg1), (start+1), -1
10 03 ff subleq (neg1), (start+3), -1
0f 0f 00 subleq (zero), (zero), start
; useful constants
zero:
00 .data 0
neg1:
ff .data -1
; the message to print
message: .data "Hello, world!\n\0"
48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
| function subleq (prog)
local mem, p, A, B, C = {}, 0
for word in prog:gmatch("%S+") do
mem[p] = tonumber(word)
p = p + 1
end
p = 0
repeat
A, B, C = mem[p], mem[p + 1], mem[p + 2]
if A == -1 then
mem[B] = io.read()
elseif B == -1 then
io.write(string.char(mem[A]))
else
mem[B] = mem[B] - mem[A]
if mem[B] <= 0 then p = C end
end
p = p + 3
until not mem[mem[p]]
end
subleq("15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0") |
Substring/Top and tail | Lua | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
* String with first character removed
* String with last character removed
* String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
| print (string.sub("knights",2)) -- remove the first character
print (string.sub("knights",1,-2)) -- remove the last character
print (string.sub("knights",2,-2)) -- remove the first and last characters |
Sum and product puzzle | Lua from C++ | * Wikipedia: Sum and Product Puzzle
| function print_count(t)
local cnt = 0
for k,v in pairs(t) do
cnt = cnt + 1
end
print(cnt .. ' candidates')
end
function make_pair(a,b)
local t = {}
table.insert(t, a) -- 1
table.insert(t, b) -- 2
return t
end
function setup()
local candidates = {}
for x = 2, 98 do
for y = x + 1, 98 do
if x + y <= 100 then
local p = make_pair(x, y)
table.insert(candidates, p)
end
end
end
return candidates
end
function remove_by_sum(candidates, sum)
for k,v in pairs(candidates) do
local s = v[1] + v[2]
if s == sum then
table.remove(candidates, k)
end
end
end
function remove_by_prod(candidates, prod)
for k,v in pairs(candidates) do
local p = v[1] * v[2]
if p == prod then
table.remove(candidates, k)
end
end
end
function statement1(candidates)
local unique = {}
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] ~= nil then
unique[prod] = unique[prod] + 1
else
unique[prod] = 1
end
end
local done
repeat
done = true
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] == 1 then
local sum = v[1] + v[2]
remove_by_sum(candidates, sum)
done = false
break
end
end
until done
end
function statement2(candidates)
local unique = {}
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] ~= nil then
unique[prod] = unique[prod] + 1
else
unique[prod] = 1
end
end
local done
repeat
done = true
for k,v in pairs(candidates) do
local prod = v[1] * v[2]
if unique[prod] > 1 then
remove_by_prod(candidates, prod)
done = false
break
end
end
until done
end
function statement3(candidates)
local unique = {}
for k,v in pairs(candidates) do
local sum = v[1] + v[2]
if unique[sum] ~= nil then
unique[sum] = unique[sum] + 1
else
unique[sum] = 1
end
end
local done
repeat
done = true
for k,v in pairs(candidates) do
local sum = v[1] + v[2]
if unique[sum] > 1 then
remove_by_sum(candidates, sum)
done = false
break
end
end
until done
end
function main()
local candidates = setup()
print_count(candidates)
statement1(candidates)
print_count(candidates)
statement2(candidates)
print_count(candidates)
statement3(candidates)
print_count(candidates)
for k,v in pairs(candidates) do
local sum = v[1] + v[2]
local prod = v[1] * v[2]
print("a=" .. v[1] .. ", b=" .. v[2] .. "; S=" .. sum .. ", P=" .. prod)
end
end
main() |
Sum digits of an integer | Lua | Take a Natural Number in a given base and return the sum of its digits:
:* '''1'''10 sums to '''1'''
:* '''1234'''10 sums to '''10'''
:* '''fe'''16 sums to '''29'''
:* '''f0e'''16 sums to '''29'''
| function sum_digits(n, base)
sum = 0
while n > 0.5 do
m = math.floor(n / base)
digit = n - m * base
sum = sum + digit
n = m
end
return sum
end
print(sum_digits(1, 10))
print(sum_digits(1234, 10))
print(sum_digits(0xfe, 16))
print(sum_digits(0xf0e, 16)) |
Sum multiples of 3 and 5 | Lua from Tcl | The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''.
Show output for ''n'' = 1000.
This is is the same as Project Euler problem 1.
'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
| function tri (n) return n * (n + 1) / 2 end
function sum35 (n)
n = n - 1
return ( 3 * tri(math.floor(n / 3)) +
5 * tri(math.floor(n / 5)) -
15 * tri(math.floor(n / 15))
)
end
print(sum35(1000))
print(sum35(1e+20))
|
Sum to 100 | Lua from C | Find solutions to the ''sum to one hundred'' puzzle.
Add (insert) the mathematical
operators '''+''' or '''-''' (plus
or minus) before any of the digits in the
decimal numeric string '''123456789''' such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, '''100''').
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
:* Show all solutions that sum to '''100'''
:* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++)
:* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task
:* Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
++ (where ''infinity'' would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: '''5074'''
(which, of course, isn't the lowest positive sum that can't be expressed).
| local expressionsLength = 0
function compareExpressionBySum(a, b)
return a.sum - b.sum
end
local countSumsLength = 0
function compareCountSumsByCount(a, b)
return a.counts - b.counts
end
function evaluate(code)
local value = 0
local number = 0
local power = 1
for k=9,1,-1 do
number = power*k + number
local mod = code % 3
if mod == 0 then
-- ADD
value = value + number
number = 0
power = 1
elseif mod == 1 then
-- SUB
value = value - number
number = 0
power = 1
elseif mod == 2 then
-- JOIN
power = 10 * power
else
print("This should not happen.")
end
code = math.floor(code / 3)
end
return value
end
function printCode(code)
local a = 19683
local b = 6561
local s = ""
for k=1,9 do
local temp = math.floor((code % a) / b)
if temp == 0 then
-- ADD
if k>1 then
s = s .. '+'
end
elseif temp == 1 then
-- SUB
s = s .. '-'
end
a = b
b = math.floor(b/3)
s = s .. tostring(k)
end
print("\t"..evaluate(code).." = "..s)
end
-- Main
local nexpr = 13122
print("Show all solutions that sum to 100")
for i=0,nexpr-1 do
if evaluate(i) == 100 then
printCode(i)
end
end
print()
print("Show the sum that has the maximum number of solutions")
local nbest = -1
for i=0,nexpr-1 do
local test = evaluate(i)
if test>0 then
local ntest = 0
for j=0,nexpr-1 do
if evaluate(j) == test then
ntest = ntest + 1
end
if ntest > nbest then
best = test
nbest = ntest
end
end
end
end
print(best.." has "..nbest.." solutions\n")
print("Show the lowest positive number that can't be expressed")
local code = -1
for i=0,123456789 do
for j=0,nexpr-1 do
if evaluate(j) == i then
code = j
break
end
end
if evaluate(code) ~= i then
code = i
break
end
end
print(code.."\n")
print("Show the ten highest numbers that can be expressed")
local limit = 123456789 + 1
for i=1,10 do
local best=0
for j=0,nexpr-1 do
local test = evaluate(j)
if (test<limit) and (test>best) then
best = test
end
end
for j=0,nexpr-1 do
if evaluate(j) == best then
printCode(j)
end
end
limit = best
end |
Summarize and say sequence | Lua | There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
;Task:
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
;Related tasks:
* [[Fours is the number of letters in the ...]]
* [[Look-and-say sequence]]
* [[Number names]]
* [[Self-describing numbers]]
* [[Spelling of ordinal numbers]]
;Also see:
* The On-Line Encyclopedia of Integer Sequences.
| -- Return the next term in the self-referential sequence
function findNext (nStr)
local nTab, outStr, pos, count = {}, "", 1, 1
for i = 1, #nStr do nTab[i] = nStr:sub(i, i) end
table.sort(nTab, function (a, b) return a > b end)
while pos <= #nTab do
if nTab[pos] == nTab[pos + 1] then
count = count + 1
else
outStr = outStr .. count .. nTab[pos]
count = 1
end
pos = pos + 1
end
return outStr
end
-- Return boolean indicating whether table t contains string s
function contains (t, s)
for k, v in pairs(t) do
if v == s then return true end
end
return false
end
-- Return the sequence generated by the given seed term
function buildSeq (term)
local sequence = {}
repeat
table.insert(sequence, term)
if not nextTerm[term] then nextTerm[term] = findNext(term) end
term = nextTerm[term]
until contains(sequence, term)
return sequence
end
-- Main procedure
nextTerm = {}
local highest, seq, hiSeq = 0
for i = 1, 10^6 do
seq = buildSeq(tostring(i))
if #seq > highest then
highest = #seq
hiSeq = {seq}
elseif #seq == highest then
table.insert(hiSeq, seq)
end
end
io.write("Seed values: ")
for _, v in pairs(hiSeq) do io.write(v[1] .. " ") end
print("\n\nIterations: " .. highest)
print("\nSample sequence:")
for _, v in pairs(hiSeq[1]) do print(v) end |
Superellipse | Lua | A superellipse is a geometric figure defined as the set of all points (x, y) with
::: \left|\frac{x}{a}\right|^n\! + \left|\frac{y}{b}\right|^n\! = 1,
where ''n'', ''a'', and ''b'' are positive numbers.
;Task
Draw a superellipse with n = 2.5, and a = b = 200
| local abs,cos,floor,pi,pow,sin = math.abs,math.cos,math.floor,math.pi,math.pow,math.sin
local bitmap = {
init = function(self, w, h, value)
self.w, self.h, self.pixels = w, h, {}
for y=1,h do self.pixels[y]={} end
self:clear(value)
end,
clear = function(self, value)
for y=1,self.h do
for x=1,self.w do
self.pixels[y][x] = value or " "
end
end
end,
set = function(self, x, y, value)
x,y = floor(x+0.5),floor(y+0.5)
if x>0 and y>0 and x<=self.w and y<=self.h then
self.pixels[y][x] = value or "#"
end
end,
superellipse = function(self, ox, oy, n, a, b, c)
local function sgn(n) return n>=0 and 1 or -1 end
for t = 0, 1, 0.002 do
local theta = t * 2 * pi
local x = ox + a * pow(abs(cos(theta)), 2/n) * sgn(cos(theta))
local y = oy + b * pow(abs(sin(theta)), 2/n) * sgn(sin(theta))
self:set(x, y, c)
end
end,
render = function(self)
for y=1,self.h do
print(table.concat(self.pixels[y]))
end
end,
}
bitmap:init(80, 60, "..")
bitmap:superellipse(40, 30, 2.5, 38, 28, "[]")
bitmap:render() |
Tau function | Lua from Java | Given a positive integer, count the number of its positive divisors.
;Task
Show the result for the first '''100''' positive integers.
;Related task
* [[Tau number]]
| function divisorCount(n)
local total = 1
-- Deal with powers of 2 first
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
-- Odd prime factors up tot eh square root
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = n / p
end
total = total * count
p = p + 2
end
-- If n > 1 then it's prime
if n > 1 then
total = total * 2
end
return total
end
limit = 100
print("Count of divisors for the first " .. limit .. " positive integers:")
for n=1,limit do
io.write(string.format("%3d", divisorCount(n)))
if n % 20 == 0 then
print()
end
end |
Temperature conversion | Lua | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
: 0 degrees Celsius corresponds to 273.15 kelvin.
: 0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
: 0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
;Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
;Example:
K 21.00
C -252.15
F -421.87
R 37.80
| function convert_temp(k)
local c = k - 273.15
local r = k * 1.8
local f = r - 459.67
return k, c, r, f
end
print(string.format([[
Kelvin: %.2f K
Celcius: %.2f °C
Rankine: %.2f °R
Fahrenheit: %.2f °F
]],convert_temp(21.0))) |
Terminal control/Coloured text | Lua | Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
* How the system should determine if the terminal supports colour
* Setting of the background colour
* How to cause blinking or flashing (if supported by the terminal)
| print("Normal \027[1mBold\027[0m \027[4mUnderline\027[0m \027[7mInverse\027[0m")
colors = { 30,31,32,33,34,35,36,37,90,91,92,93,94,95,96,97 }
for _,bg in ipairs(colors) do
for _,fg in ipairs(colors) do
io.write("\027["..fg..";"..(bg+10).."mX")
end
print("\027[0m") -- be nice, reset
end |
Test integerness | Lua | {| class="wikitable"
|-
! colspan=2 | Input
! colspan=2 | Output
! rowspan=2 | Comment
|-
! Type
! Value
! exact
! tolerance = 0.00001
|-
| rowspan=3 | decimal
| 25.000000
| colspan=2 | true
|
|-
| 24.999999
| false
| true
|
|-
| 25.000100
| colspan=2 | false
|
|-
| rowspan=4 | floating-point
| -2.1e120
| colspan=2 | true
| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.
|-
| -5e-2
| colspan=2 | false
|
|-
| NaN
| colspan=2 | false
|
|-
| Inf
| colspan=2 | false
| This one is debatable. If your code considers it an integer, that's okay too.
|-
| rowspan=2 | complex
| 5.0+0.0i
| colspan=2 | true
|
|-
| 5-5i
| colspan=2 | false
|
|}
(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| function isInt (x) return type(x) == "number" and x == math.floor(x) end
print("Value\tInteger?")
print("=====\t========")
local testCases = {2, 0, -1, 3.5, "String!", true}
for _, input in pairs(testCases) do print(input, isInt(input)) end |
Textonyms | Lua | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
;Task:
Write a program that finds textonyms in a list of words such as
[[Textonyms/wordlist]] or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
;Extra credit:
Use a word list and keypad mapping other than English.
| -- Global variables
http = require("socket.http")
keys = {"VOICEMAIL", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
dictFile = "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
-- Return the sequence of keys required to type a given word
function keySequence (str)
local sequence, noMatch, letter = ""
for pos = 1, #str do
letter = str:sub(pos, pos)
for i, chars in pairs(keys) do
noMatch = true
if chars:match(letter) then
sequence = sequence .. tostring(i)
noMatch = false
break
end
end
if noMatch then return nil end
end
return tonumber(sequence)
end
-- Generate table of words grouped by key sequence
function textonyms (dict)
local combTable, keySeq = {}
for word in dict:gmatch("%S+") do
keySeq = keySequence(word)
if keySeq then
if combTable[keySeq] then
table.insert(combTable[keySeq], word)
else
combTable[keySeq] = {word}
end
end
end
return combTable
end
-- Analyse sequence table and print details
function showReport (keySeqs)
local wordCount, seqCount, tCount = 0, 0, 0
for seq, wordList in pairs(keySeqs) do
wordCount = wordCount + #wordList
seqCount = seqCount + 1
if #wordList > 1 then tCount = tCount + 1 end
end
print("There are " .. wordCount .. " words in " .. dictFile)
print("which can be represented by the digit key mapping.")
print("They require " .. seqCount .. " digit combinations to represent them.")
print(tCount .. " digit combinations represent Textonyms.")
end
-- Main procedure
showReport(textonyms(http.request(dictFile))) |
The Name Game | Lua from C# | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
| function printVerse(name)
local sb = string.lower(name)
sb = sb:gsub("^%l", string.upper)
local x = sb
local x0 = x:sub(1,1)
local y
if x0 == 'A' or x0 == 'E' or x0 == 'I' or x0 == 'O' or x0 == 'U' then
y = string.lower(x)
else
y = x:sub(2)
end
local b = "b" .. y
local f = "f" .. y
local m = "m" .. y
if x0 == 'B' then
b = y
elseif x0 == 'F' then
f = y
elseif x0 == 'M' then
m = y
end
print(x .. ", " .. x .. ", bo-" .. b)
print("Banana-fana fo-" .. f)
print("Fee-fi-mo-" .. m)
print(x .. "!")
print()
return nil
end
local nameList = { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }
for _,name in pairs(nameList) do
printVerse(name)
end |
The Twelve Days of Christmas | Lua | Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
| local days = {
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth',
}
local gifts = {
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming",
}
local verses = {}
for i = 1, 12 do
local lines = {}
lines[1] = "On the " .. days[i] .. " day of Christmas, my true love gave to me"
local j = i
local k = 2
repeat
lines[k] = gifts[j]
k = k + 1
j = j - 1
until j == 0
verses[i] = table.concat(lines, '\n')
end
print(table.concat(verses, '\n\n'))
|
Thue-Morse | Lua | Create a Thue-Morse sequence.
;See also
* YouTube entry: The Fairest Sharing Sequence Ever
* YouTube entry: Math and OCD - My story with the Thue-Morse sequence
* Task: [[Fairshare between two and more]]
| ThueMorse = {sequence = "0"}
function ThueMorse:show ()
print(self.sequence)
end
function ThueMorse:addBlock ()
local newBlock = ""
for bit = 1, self.sequence:len() do
if self.sequence:sub(bit, bit) == "1" then
newBlock = newBlock .. "0"
else
newBlock = newBlock .. "1"
end
end
self.sequence = self.sequence .. newBlock
end
for i = 1, 5 do
ThueMorse:show()
ThueMorse:addBlock()
end |
Top rank per group | Lua | Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| --Employee Class
local EmployeeMethods = {
}
local EmployeeMetamethods = {
__index=EmployeeMethods,
__tostring=function(self)
return ("%s %s %s %s"):format(self.Name,self.EmployeeId,self.Salary,self.DepartmentName)
end,
__metatable="Locked",
}
local EmployeeBase = {}
EmployeeBase.new = function(Name,EmployeeId,Salary,DepartmentName)
return setmetatable({
Name=Name,
EmployeeId=EmployeeId,
Salary=Salary,
DepartmentName=DepartmentName,
},EmployeeMetamethods)
end
--Department Class
local DepartmentMethods = {
NewEmployee=function(self,Employee)
table.insert(self.__Employees,Employee)
end,
CalculateHighestSalaries=function(self,Amount)
local Highest = {}
local EL = #self.__Employees
table.sort(self.__Employees,function(a,b)
return a.Salary > b.Salary
end)
for i=1,Amount do
if i>EL then
break
end
table.insert(Highest,self.__Employees[i])
end
return Highest
end,
}
local DepartmentMetamethods = {
__index=DepartmentMethods,
__tostring=function(self)
return ("Department %s"):format(self.Name)
end,
__metatable="Locked",
}
local DepartmentBase = {
__Departments={},
}
DepartmentBase.new = function(Name)
local Department = DepartmentBase.__Departments[Name]
if Department then return Department end
Department = setmetatable({
__Employees={},
Name=Name,
},DepartmentMetamethods)
DepartmentBase.__Departments[Name] = Department
return Department
end
--Main Program
local Employees = {
EmployeeBase.new("Tyler Bennett","E10297",32000,"D101"),
EmployeeBase.new("John Rappl","E21437",47000,"D050"),
EmployeeBase.new("George Woltman","E00127",53500,"D101"),
EmployeeBase.new("Adam Smith","E63535",18000,"D202"),
EmployeeBase.new("Claire Buckman","E39876",27800,"D202"),
EmployeeBase.new("David McClellan","E04242",41500,"D101"),
EmployeeBase.new("Rich Holcomb","E01234",49500,"D202"),
EmployeeBase.new("Nathan Adams","E41298",21900,"D050"),
EmployeeBase.new("Richard Potter","E43128",15900,"D101"),
EmployeeBase.new("David Motsinger","E27002",19250,"D202"),
EmployeeBase.new("Tim Sampair","E03033",27000,"D101"),
EmployeeBase.new("Kim Arlich","E10001",57000,"D190"),
EmployeeBase.new("Timothy Grove","E16398",29900,"D190"),
}
for _,Employee in next,Employees do
local Department = DepartmentBase.new(Employee.DepartmentName)
Department:NewEmployee(Employee)
end
for _,Department in next,DepartmentBase.__Departments do
local Highest = Department:CalculateHighestSalaries(2)
print(Department)
for _,Employee in next,Highest do
print("\t"..tostring(Employee))
end
end |
Topswops | Lua | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first m cards where m is the value of the topmost card.
Rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded.
For our example the swaps produce:
[2, 4, 1, 3] # Initial shuffle
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.
For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.
;Task:
The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.
;Note:
Topswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.
;Related tasks:
* [[Number reversal game]]
* [[Sorting algorithms/Pancake sort]]
| -- Return an iterator to produce every permutation of list
function permute (list)
local function perm (list, n)
if n == 0 then coroutine.yield(list) end
for i = 1, n do
list[i], list[n] = list[n], list[i]
perm(list, n - 1)
list[i], list[n] = list[n], list[i]
end
end
return coroutine.wrap(function() perm(list, #list) end)
end
-- Perform one topswop round on table t
function swap (t)
local new, limit = {}, t[1]
for i = 1, #t do
if i <= limit then
new[i] = t[limit - i + 1]
else
new[i] = t[i]
end
end
return new
end
-- Find the most swaps needed for any starting permutation of n cards
function topswops (n)
local numTab, highest, count = {}, 0
for i = 1, n do numTab[i] = i end
for numList in permute(numTab) do
count = 0
while numList[1] ~= 1 do
numList = swap(numList)
count = count + 1
end
if count > highest then highest = count end
end
return highest
end
-- Main procedure
for i = 1, 10 do print(i, topswops(i)) end |
Trabb Pardo–Knuth algorithm | Lua | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
'''ask''' for 11 numbers to be read into a sequence ''S''
'''reverse''' sequence ''S''
'''for each''' ''item'' '''in''' sequence ''S''
''result'' ''':=''' '''call''' a function to do an ''operation''
'''if''' ''result'' overflows
'''alert''' user
'''else'''
'''print''' ''result''
The task is to implement the algorithm:
# Use the function: f(x) = |x|^{0.5} + 5x^3
# The overflow condition is an answer of greater than 400.
# The 'user alert' should not stop processing of other items of the sequence.
# Print a prompt before accepting '''eleven''', textual, numeric inputs.
# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.
# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| function f (x) return math.abs(x)^0.5 + 5*x^3 end
function reverse (t)
local rev = {}
for i, v in ipairs(t) do rev[#t - (i-1)] = v end
return rev
end
local sequence, result = {}
print("Enter 11 numbers...")
for n = 1, 11 do
io.write(n .. ": ")
sequence[n] = io.read()
end
for _, x in ipairs(reverse(sequence)) do
result = f(x)
if result > 400 then print("Overflow!") else print(result) end
end |
Truncate a file | Lua | Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| function truncate (filename, length)
local inFile = io.open(filename, 'r')
if not inFile then
error("Specified filename does not exist")
end
local wholeFile = inFile:read("*all")
inFile:close()
if length >= wholeFile:len() then
error("Provided length is not less than current file length")
end
local outFile = io.open(filename, 'w')
outFile:write(wholeFile:sub(1, length))
outFile:close()
end |
URL decoding | Lua | This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
;Test cases:
* The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
* The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Baha".
* The encoded string "%25%32%35" should revert to the unencoded form "%25" and '''not''' "%".
| function decodeChar(hex)
return string.char(tonumber(hex,16))
end
function decodeString(str)
local output, t = string.gsub(str,"%%(%x%x)",decodeChar)
return output
end
-- will print "http://foo bar/"
print(decodeString("http%3A%2F%2Ffoo%20bar%2F")) |
URL encoding | Lua | Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
* Extended characters with character codes of 128 decimal (80 hex) and above.
;Example:
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
;Variations:
* Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
* Special characters have different encodings for different standards:
** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~".
** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+".
** encodeURI function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#".
;Options:
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
;Related tasks:
* [[URL decoding]]
* [[URL parser]]
| function encodeChar(chr)
return string.format("%%%X",string.byte(chr))
end
function encodeString(str)
local output, t = string.gsub(str,"[^%w]",encodeChar)
return output
end
-- will print "http%3A%2F%2Ffoo%20bar%2F"
print(encodeString("http://foo bar/")) |
UTF-8 encode and decode | Lua 5.3 | As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
o LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Zh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
EUR EURO SIGN U+20AC E2 82 AC
MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| -- Accept an integer representing a codepoint.
-- Return the values of the individual octets.
function encode (codepoint)
local codepoint_str = utf8.char(codepoint)
local result = {}
for i = 1, #codepoint_str do
result[#result + 1] = string.unpack("B", codepoint_str, i)
end
return table.unpack(result)
end
-- Accept a variable number of octets.
-- Return the corresponding Unicode character.
function decode (...)
local len = select("#", ...) -- the number of octets
local fmt = string.rep("B", len)
return string.pack(fmt, ...)
end
-- Run the given test cases.
function test_encode_decode ()
-- "A", "ö", "Ж", "€", "𝄞"
local tests = {tonumber("41", 16), tonumber("f6", 16), tonumber("416", 16),
tonumber("20ac", 16), tonumber("1d11e", 16)}
for i, test in ipairs(tests) do
print("Char: ", test)
print("Encoding: ", encode(test))
print("Decoding: ", decode(encode(test)))
end
end
|
Unbias a random generator | Lua | Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.
;Task details:
* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| local function randN(n)
return function()
if math.random() < 1/n then return 1 else return 0 end
end
end
local function unbiased(n)
local biased = randN (n)
return function()
local a, b = biased(), biased()
while a==b do
a, b = biased(), biased()
end
return a
end
end
local function demonstrate (samples)
for n = 3, 6 do
biased = randN(n)
unbias = unbiased(n)
local bcounts = {[0]=0,[1]=0}
local ucounts = {[0]=0,[1]=0}
for i=1, samples do
local bnum = biased()
local unum = unbias()
bcounts[bnum] = bcounts[bnum]+1
ucounts[unum] = ucounts[unum]+1
end
print(string.format("N = %d",n),
"# 0", "# 1",
"% 0", "% 1")
print("biased", bcounts[0], bcounts[1],
bcounts[0] / samples * 100,
bcounts[1] / samples * 100)
print("unbias", ucounts[0], ucounts[1],
ucounts[0] / samples * 100,
ucounts[1] / samples * 100)
end
end
demonstrate(100000)
|
Unicode strings | Lua | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
;Task:
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
:* How easy is it to present Unicode strings in source code?
:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
:* How well can the language communicate with the rest of the world?
:* Is it good at input/output with Unicode?
:* Is it convenient to manipulate Unicode strings in the language?
:* How broad/deep does the language support Unicode?
:* What encodings (e.g. UTF-8, UTF-16, etc) can be used?
:* Does it support normalization?
;Note:
This task is a bit unusual in that it encourages general discussion rather than clever coding.
;See also:
* [[Unicode variable names]]
* [[Terminal control/Display an extended character]]
| By default, Lua doesn't support Unicode. Most string methods will work properly on the ASCII range only like [[String case#Lua|case transformation]]. But there is a [https://www.lua.org/manual/5.4/manual.html#6.5 <code>utf8</code>] module that add some very basic support with a very limited number of functions. For example, this module brings a new [[String length#Lua|length method]] adapted for UTF-8. But there is no method to transform the case of Unicode string correctly. So globally the Unicode support is very limited and not by default.
|
Universal Turing machine | Lua | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936-1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
;Task:
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
'''Simple incrementer'''
* '''States:''' q0, qf
* '''Initial state:''' q0
* '''Terminating states:''' qf
* '''Permissible symbols:''' B, 1
* '''Blank symbol:''' B
* '''Rules:'''
** (q0, 1, 1, right, q0)
** (q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
'''Three-state busy beaver'''
* '''States:''' a, b, c, halt
* '''Initial state:''' a
* '''Terminating states:''' halt
* '''Permissible symbols:''' 0, 1
* '''Blank symbol:''' 0
* '''Rules:'''
** (a, 0, 1, right, b)
** (a, 1, 1, left, c)
** (b, 0, 1, left, a)
** (b, 1, 1, right, b)
** (c, 0, 1, left, b)
** (c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
'''Bonus:'''
'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''
* '''States:''' A, B, C, D, E, H
* '''Initial state:''' A
* '''Terminating states:''' H
* '''Permissible symbols:''' 0, 1
* '''Blank symbol:''' 0
* '''Rules:'''
** (A, 0, 1, right, B)
** (A, 1, 1, left, C)
** (B, 0, 1, right, C)
** (B, 1, 1, right, B)
** (C, 0, 1, right, D)
** (C, 1, 0, left, E)
** (D, 0, 1, left, A)
** (D, 1, 1, left, D)
** (E, 0, 1, stay, H)
** (E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| -- Machine definitions
local incrementer = {
name = "Simple incrementer",
initState = "q0",
endState = "qf",
blank = "B",
rules = {
{"q0", "1", "1", "right", "q0"},
{"q0", "B", "1", "stay", "qf"}
}
}
local threeStateBB = {
name = "Three-state busy beaver",
initState = "a",
endState = "halt",
blank = "0",
rules = {
{"a", "0", "1", "right", "b"},
{"a", "1", "1", "left", "c"},
{"b", "0", "1", "left", "a"},
{"b", "1", "1", "right", "b"},
{"c", "0", "1", "left", "b"},
{"c", "1", "1", "stay", "halt"}
}
}
local fiveStateBB = {
name = "Five-state busy beaver",
initState = "A",
endState = "H",
blank = "0",
rules = {
{"A", "0", "1", "right", "B"},
{"A", "1", "1", "left", "C"},
{"B", "0", "1", "right", "C"},
{"B", "1", "1", "right", "B"},
{"C", "0", "1", "right", "D"},
{"C", "1", "0", "left", "E"},
{"D", "0", "1", "left", "A"},
{"D", "1", "1", "left", "D"},
{"E", "0", "1", "stay", "H"},
{"E", "1", "0", "left", "A"}
}
}
-- Display a representation of the tape and machine state on the screen
function show (state, headPos, tape)
local leftEdge = 1
while tape[leftEdge - 1] do leftEdge = leftEdge - 1 end
io.write(" " .. state .. "\t| ")
for pos = leftEdge, #tape do
if pos == headPos then io.write("[" .. tape[pos] .. "] ") else io.write(" " .. tape[pos] .. " ") end
end
print()
end
-- Simulate a turing machine
function UTM (machine, tape, countOnly)
local state, headPos, counter = machine.initState, 1, 0
print("\n\n" .. machine.name)
print(string.rep("=", #machine.name) .. "\n")
if not countOnly then print(" State", "| Tape [head]\n---------------------") end
repeat
if not tape[headPos] then tape[headPos] = machine.blank end
if not countOnly then show(state, headPos, tape) end
for _, rule in ipairs(machine.rules) do
if rule[1] == state and rule[2] == tape[headPos] then
tape[headPos] = rule[3]
if rule[4] == "left" then headPos = headPos - 1 end
if rule[4] == "right" then headPos = headPos + 1 end
state = rule[5]
break
end
end
counter = counter + 1
until state == machine.endState
if countOnly then print("Steps taken: " .. counter) else show(state, headPos, tape) end
end
-- Main procedure
UTM(incrementer, {"1", "1", "1"})
UTM(threeStateBB, {})
UTM(fiveStateBB, {}, "countOnly") |
Validate International Securities Identification Number | Lua | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
;Task:
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, ''and'' the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
;Details:
The format of an ISIN is as follows:
+------------- a 2-character ISO country code (A-Z)
| +----------- a 9-character security code (A-Z, 0-9)
| | +-- a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.
# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)
;Test cases:
:::: {| class="wikitable"
! ISIN
! Validity
! Comment
|-
| US0378331005 || valid ||
|-
| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.
|-
| U50378331005 || not valid || The substitution typo is caught by the format constraint.
|-
| US03378331005 || not valid || The duplication typo is caught by the format constraint.
|-
| AU0000XVGZA3 || valid ||
|-
| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.
|-
| FR0000988040 || valid ||
|}
(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)
Related task:
* [[Luhn test of credit card numbers]]
;Also see:
* Interactive online ISIN validator
* Wikipedia article: International Securities Identification Number
| function luhn (n)
local revStr, s1, s2, digit, mod = n:reverse(), 0, 0
for pos = 1, #revStr do
digit = tonumber(revStr:sub(pos, pos))
if pos % 2 == 1 then
s1 = s1 + digit
else
digit = digit * 2
if digit > 9 then
mod = digit % 10
digit = mod + ((digit - mod) / 10)
end
s2 = s2 + digit
end
end
return (s1 + s2) % 10 == 0
end
function checkISIN (inStr)
if #inStr ~= 12 then return false end
local numStr = ""
for pos = 1, #inStr do
numStr = numStr .. tonumber(inStr:sub(pos, pos), 36)
end
return luhn(numStr)
end
local testCases = {
"US0378331005",
"US0373831005",
"US0373831005",
"US03378331005",
"AU0000XVGZA3",
"AU0000VXGZA3",
"FR0000988040"
}
for _, ISIN in pairs(testCases) do print(ISIN, checkISIN(ISIN)) end |
Van Eck sequence | Lua | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
;Example:
Using A:
:0
Using B:
:0 0
Using C:
:0 0 1
Using B:
:0 0 1 0
Using C: (zero last occurred two steps back - before the one)
:0 0 1 0 2
Using B:
:0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
:0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
:0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
:0 0 1 0 2 0 2 2 1 6
...
;Task:
# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
# Use it to display here, on this page:
:# The first ten terms of the sequence.
:# Terms 991 - to - 1000 of the sequence.
;References:
* Don't Know (the Van Eck Sequence) - Numberphile video.
* Wikipedia Article: Van Eck's Sequence.
* OEIS sequence: A181391.
| -- Return a table of the first n values of the Van Eck sequence
function vanEck (n)
local seq, foundAt = {0}
while #seq < n do
foundAt = nil
for pos = #seq - 1, 1, -1 do
if seq[pos] == seq[#seq] then
foundAt = pos
break
end
end
if foundAt then
table.insert(seq, #seq - foundAt)
else
table.insert(seq, 0)
end
end
return seq
end
-- Show the set of values in table t from key numbers lo to hi
function showValues (t, lo, hi)
for i = lo, hi do
io.write(t[i] .. " ")
end
print()
end
-- Main procedure
local sequence = vanEck(1000)
showValues(sequence, 1, 10)
showValues(sequence, 991, 1000) |
Van der Corput sequence | Lua | When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is 1 \times 2^1 + 0 \times 2^0.
You can also have binary digits to the right of the "point", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2.
The weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.
If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4.
Monte Carlo simulations.
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
'''Hint'''
A ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is 1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 1\times 2^0.
Reflected this would become .1101 or 1\times 2^{-1} + 1\times 2^{-2} + 0\times 2^{-3} + 1\times 2^{-4}
;Task description:
* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.
* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).
* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
;See also:
* The Basic Low Discrepancy Sequences
* [[Non-decimal radices/Convert]]
* Van der Corput sequence
| function vdc(n, base)
local digits = {}
while n ~= 0 do
local m = math.floor(n / base)
table.insert(digits, n - m * base)
n = m
end
m = 0
for p, d in pairs(digits) do
m = m + math.pow(base, -p) * d
end
return m
end |
Vector products | Lua | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
* '''The dot product''' (a scalar quantity)
:::: A * B = a1b1 + a2b2 + a3b3
* '''The cross product''' (a vector quantity)
:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
* '''The scalar triple product''' (a scalar quantity)
:::: A * (B x C)
* '''The vector triple product''' (a vector quantity)
:::: A x (B x C)
;Task:
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
# Create a named function/subroutine/method to compute the dot product of two vectors.
# Create a function to compute the cross product of two vectors.
# Optionally create a function to compute the scalar triple product of three vectors.
# Optionally create a function to compute the vector triple product of three vectors.
# Compute and display: a * b
# Compute and display: a x b
# Compute and display: a * (b x c), the scalar triple product.
# Compute and display: a x (b x c), the vector triple product.
;References:
* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.
* Wikipedia dot product.
* Wikipedia cross product.
* Wikipedia triple product.
;Related tasks:
* [[Dot product]]
* [[Quaternion type]]
| Vector = {}
function Vector.new( _x, _y, _z )
return { x=_x, y=_y, z=_z }
end
function Vector.dot( A, B )
return A.x*B.x + A.y*B.y + A.z*B.z
end
function Vector.cross( A, B )
return { x = A.y*B.z - A.z*B.y,
y = A.z*B.x - A.x*B.z,
z = A.x*B.y - A.y*B.x }
end
function Vector.scalar_triple( A, B, C )
return Vector.dot( A, Vector.cross( B, C ) )
end
function Vector.vector_triple( A, B, C )
return Vector.cross( A, Vector.cross( B, C ) )
end
A = Vector.new( 3, 4, 5 )
B = Vector.new( 4, 3, 5 )
C = Vector.new( -5, -12, -13 )
print( Vector.dot( A, B ) )
r = Vector.cross(A, B )
print( r.x, r.y, r.z )
print( Vector.scalar_triple( A, B, C ) )
r = Vector.vector_triple( A, B, C )
print( r.x, r.y, r.z ) |
Video display modes | Lua | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| print("\33[?3h") -- 132-column text
print("\33[?3l") -- 80-column text |
Visualize a tree | Lua from C# | A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
:::* indented text (a la unix tree command)
:::* nested HTML tables
:::* hierarchical GUI widgets
:::* 2D or 3D images
:::* etc.
;Task:
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| function makeTree(v,ac)
if type(ac) == "table" then
return {value=v,children=ac}
else
return {value=v}
end
end
function printTree(t,last,prefix)
if last == nil then
printTree(t, false, '')
else
local current = ''
local next = ''
if last then
current = prefix .. '\\-' .. t.value
next = prefix .. ' '
else
current = prefix .. '|-' .. t.value
next = prefix .. '| '
end
print(current:sub(3))
if t.children ~= nil then
for k,v in pairs(t.children) do
printTree(v, k == #t.children, next)
end
end
end
end
printTree(
makeTree('A', {
makeTree('B0', {
makeTree('C1'),
makeTree('C2', {
makeTree('D', {
makeTree('E1'),
makeTree('E2'),
makeTree('E3')
})
}),
makeTree('C3', {
makeTree('F1'),
makeTree('F2'),
makeTree('F3', {makeTree('G')}),
makeTree('F4', {
makeTree('H1'),
makeTree('H2')
})
})
}),
makeTree('B1',{
makeTree('K1'),
makeTree('K2', {
makeTree('L1', {makeTree('M')}),
makeTree('L2'),
makeTree('L3')
}),
makeTree('K3')
})
})
) |
Vogel's approximation method | Lua from Kotlin | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them "A", "B", "C", "D", and "E". They estimate that:
* A will require 30 hours of work,
* B will require 20 hours of work,
* C will require 70 hours of work,
* D will require 30 hours of work, and
* E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called "W", "X", "Y", and "Z".
* W has 50 hours available to commit to working,
* X has 60 hours available,
* Y has 50 hours available, and
* Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is PS3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is PS3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
;Cf.
* Transportation problem
| function initArray(n,v)
local tbl = {}
for i=1,n do
table.insert(tbl,v)
end
return tbl
end
function initArray2(m,n,v)
local tbl = {}
for i=1,m do
table.insert(tbl,initArray(n,v))
end
return tbl
end
supply = {50, 60, 50, 50}
demand = {30, 20, 70, 30, 60}
costs = {
{16, 16, 13, 22, 17},
{14, 14, 13, 19, 15},
{19, 19, 20, 23, 50},
{50, 12, 50, 15, 11}
}
nRows = table.getn(supply)
nCols = table.getn(demand)
rowDone = initArray(nRows, false)
colDone = initArray(nCols, false)
results = initArray2(nRows, nCols, 0)
function diff(j,le,isRow)
local min1 = 100000000
local min2 = min1
local minP = -1
for i=1,le do
local done = false
if isRow then
done = colDone[i]
else
done = rowDone[i]
end
if not done then
local c = 0
if isRow then
c = costs[j][i]
else
c = costs[i][j]
end
if c < min1 then
min2 = min1
min1 = c
minP = i
elseif c < min2 then
min2 = c
end
end
end
return {min2 - min1, min1, minP}
end
function maxPenalty(len1,len2,isRow)
local md = -100000000
local pc = -1
local pm = -1
local mc = -1
for i=1,len1 do
local done = false
if isRow then
done = rowDone[i]
else
done = colDone[i]
end
if not done then
local res = diff(i, len2, isRow)
if res[1] > md then
md = res[1] -- max diff
pm = i -- pos of max diff
mc = res[2] -- min cost
pc = res[3] -- pos of min cost
end
end
end
if isRow then
return {pm, pc, mc, md}
else
return {pc, pm, mc, md}
end
end
function nextCell()
local res1 = maxPenalty(nRows, nCols, true)
local res2 = maxPenalty(nCols, nRows, false)
if res1[4] == res2[4] then
if res1[3] < res2[3] then
return res1
else
return res2
end
else
if res1[4] > res2[4] then
return res2
else
return res1
end
end
end
function main()
local supplyLeft = 0
for i,v in pairs(supply) do
supplyLeft = supplyLeft + v
end
local totalCost = 0
while supplyLeft > 0 do
local cell = nextCell()
local r = cell[1]
local c = cell[2]
local q = math.min(demand[c], supply[r])
demand[c] = demand[c] - q
if demand[c] == 0 then
colDone[c] = true
end
supply[r] = supply[r] - q
if supply[r] == 0 then
rowDone[r] = true
end
results[r][c] = q
supplyLeft = supplyLeft - q
totalCost = totalCost + q * costs[r][c]
end
print(" A B C D E")
local labels = {'W','X','Y','Z'}
for i,r in pairs(results) do
io.write(labels[i])
for j,c in pairs(r) do
io.write(string.format(" %2d", c))
end
print()
end
print("Total Cost = " .. totalCost)
end
main() |
Voronoi diagram | Lua from Python | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.
;Task:
Demonstrate how to generate and display a Voroni diagram.
See algo [[K-means++ clustering]].
| function love.load( )
love.math.setRandomSeed( os.time( ) ) --set the random seed
keys = { } --an empty table where we will store key presses
number_cells = 50 --the number of cells we want in our diagram
--draw the voronoi diagram to a canvas
voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )
end
function hypot( x, y )
return math.sqrt( x*x + y*y )
end
function generateVoronoi( width, height, num_cells )
canvas = love.graphics.newCanvas( width, height )
local imgx = canvas:getWidth( )
local imgy = canvas:getHeight( )
local nx = { }
local ny = { }
local nr = { }
local ng = { }
local nb = { }
for a = 1, num_cells do
table.insert( nx, love.math.random( 0, imgx ) )
table.insert( ny, love.math.random( 0, imgy ) )
table.insert( nr, love.math.random( 0, 1 ) )
table.insert( ng, love.math.random( 0, 1 ) )
table.insert( nb, love.math.random( 0, 1 ) )
end
love.graphics.setColor( { 1, 1, 1 } )
love.graphics.setCanvas( canvas )
for y = 1, imgy do
for x = 1, imgx do
dmin = hypot( imgx-1, imgy-1 )
j = -1
for i = 1, num_cells do
d = hypot( nx[i]-x, ny[i]-y )
if d < dmin then
dmin = d
j = i
end
end
love.graphics.setColor( { nr[j], ng[j], nb[j] } )
love.graphics.points( x, y )
end
end
--reset color
love.graphics.setColor( { 1, 1, 1 } )
--draw points
for b = 1, num_cells do
love.graphics.points( nx[b], ny[b] )
end
love.graphics.setCanvas( )
return canvas
end
--RENDER
function love.draw( )
--reset color
love.graphics.setColor( { 1, 1, 1 } )
--draw diagram
love.graphics.draw( voronoiDiagram )
--draw drop shadow text
love.graphics.setColor( { 0, 0, 0 } )
love.graphics.print( "space: regenerate\nesc: quit", 1, 1 )
--draw text
love.graphics.setColor( { 0.7, 0.7, 0 } )
love.graphics.print( "space: regenerate\nesc: quit" )
end
--CONTROL
function love.keyreleased( key )
if key == 'space' then
voronoiDiagram = generateVoronoi( love.graphics.getWidth( ), love.graphics.getHeight( ), number_cells )
elseif key == 'escape' then
love.event.quit( )
end
end
|
Water collected between towers | Lua from C# | In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ## 9 ##
8 ## 8 ##
7 ## ## 7 ####
6 ## ## ## 6 ######
5 ## ## ## #### 5 ##########
4 ## ## ######## 4 ############
3 ###### ######## 3 ##############
2 ################ ## 2 ##################
1 #################### 1 ####################
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele
* Water collected between towers on Stack Overflow, from which the example above is taken)
* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| function waterCollected(i,tower)
local length = 0
for _ in pairs(tower) do
length = length + 1
end
local wu = 0
repeat
local rht = length - 1
while rht >= 0 do
if tower[rht + 1] > 0 then
break
end
rht = rht - 1
end
if rht < 0 then
break
end
local bof = 0
local col = 0
while col <= rht do
if tower[col + 1] > 0 then
tower[col + 1] = tower[col + 1] - 1
bof = bof + 1
elseif bof > 0 then
wu = wu + 1
end
col = col + 1
end
if bof < 2 then
break
end
until false
if wu == 0 then
print(string.format("Block %d does not hold any water.", i))
else
print(string.format("Block %d holds %d water units.", i, wu))
end
end
function main()
local towers = {
{1, 5, 3, 7, 2},
{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
{5, 5, 5, 5},
{5, 6, 7, 8},
{8, 7, 7, 6},
{6, 7, 10, 7, 6}
}
for i,tbl in pairs(towers) do
waterCollected(i,tbl)
end
end
main() |
Weird numbers | Lua from C# | In number theory, a perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').
For example:
* '''12''' is ''not'' a weird number.
** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),
** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.
* '''70''' ''is'' a weird number.
** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),
** and there is no subset of proper divisors that sum to '''70'''.
;Task:
Find and display, here on this page, the first '''25''' weird numbers.
;Related tasks:
:* Abundant, deficient and perfect number classifications
:* Proper divisors
;See also:
:* OEIS: A006037 weird numbers
:* Wikipedia: weird number
:* MathWorld: weird number
| function make(n, d)
local a = {}
for i=1,n do
table.insert(a, d)
end
return a
end
function reverse(t)
local n = #t
local i = 1
while i < n do
t[i],t[n] = t[n],t[i]
i = i + 1
n = n - 1
end
end
function tail(list)
return { select(2, unpack(list)) }
end
function divisors(n)
local divs = {}
table.insert(divs, 1)
local divs2 = {}
local i = 2
while i * i <= n do
if n % i == 0 then
local j = n / i
table.insert(divs, i)
if i ~= j then
table.insert(divs2, j)
end
end
i = i + 1
end
reverse(divs)
for i,v in pairs(divs) do
table.insert(divs2, v)
end
return divs2
end
function abundant(n, divs)
local sum = 0
for i,v in pairs(divs) do
sum = sum + v
end
return sum > n
end
function semiPerfect(n, divs)
if #divs > 0 then
local h = divs[1]
local t = tail(divs)
if n < h then
return semiPerfect(n, t)
else
return n == h
or semiPerfect(n - h, t)
or semiPerfect(n, t)
end
else
return false
end
end
function sieve(limit)
-- false denotes abundant and not semi-perfect.
-- Only interested in even numbers >= 2
local w = make(limit, false)
local i = 2
while i < limit do
if not w[i] then
local divs = divisors(i)
if not abundant(i, divs) then
w[i] = true
elseif semiPerfect(i, divs) then
local j = i
while j < limit do
w[j] = true
j = j + i
end
end
end
i = i + 1
end
return w
end
function main()
local w = sieve(17000)
local count = 0
local max = 25
print("The first 25 weird numbers:")
local n = 2
while count < max do
if not w[n] then
io.write(n, ' ')
count = count + 1
end
n = n + 2
end
print()
end
main() |
Word frequency | lua 5.3 | Given a text file and an integer '''n''', print/display the '''n''' most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
* A word is a sequence of one or more contiguous letters.
* You are free to define what a ''letter'' is.
* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
* You may treat a compound word like '''well-dressed''' as either one word or two.
* The word '''it's''' could also be one or two words as you see fit.
* You may also choose not to support non US-ASCII characters.
* Assume words will not span multiple lines.
* Don't worry about normalization of word spelling differences.
* Treat '''color''' and '''colour''' as two distinct words.
* Uppercase letters are considered equivalent to their lowercase counterparts.
* Words of equal frequency can be listed in any order.
* Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.
;History:
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
;References:
*McIlroy's program
| -- This program takes two optional command line arguments. The first (arg[1])
-- specifies the input file, or defaults to standard input. The second
-- (arg[2]) specifies the number of results to show, or defaults to 10.
-- in freq, each key is a word and each value is its count
local freq = {}
for line in io.lines(arg[1]) do
-- %a stands for any letter
for word in string.gmatch(string.lower(line), "%a+") do
if not freq[word] then
freq[word] = 1
else
freq[word] = freq[word] + 1
end
end
end
-- in array, each entry is an array whose first value is the count and whose
-- second value is the word
local array = {}
for word, count in pairs(freq) do
table.insert(array, {count, word})
end
table.sort(array, function (a, b) return a[1] > b[1] end)
for i = 1, arg[2] or 10 do
io.write(string.format('%7d %s\n', array[i][1] , array[i][2]))
end
|
Word wrap | Lua | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
;Basic task:
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
;Extra credit:
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
| function splittokens(s)
local res = {}
for w in s:gmatch("%S+") do
res[#res+1] = w
end
return res
end
function textwrap(text, linewidth)
if not linewidth then
linewidth = 75
end
local spaceleft = linewidth
local res = {}
local line = {}
for _, word in ipairs(splittokens(text)) do
if #word + 1 > spaceleft then
table.insert(res, table.concat(line, ' '))
line = {word}
spaceleft = linewidth - #word
else
table.insert(line, word)
spaceleft = spaceleft - (#word + 1)
end
end
table.insert(res, table.concat(line, ' '))
return table.concat(res, '\n')
end
local example1 = [[
Even today, with proportional fonts and complex layouts,
there are still cases where you need to wrap text at a
specified column. The basic task is to wrap a paragraph
of text in a simple way in your language. If there is a
way to do this that is built-in, trivial, or provided in
a standard library, show that. Otherwise implement the
minimum length greedy algorithm from Wikipedia.
]]
print(textwrap(example1))
print()
print(textwrap(example1, 60)) |
World Cup group stage | Lua from C++ | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
:::* A win is worth three points.
:::* A draw/tie is worth one point.
:::* A loss is worth zero points.
;Task:
:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
:* Calculate the standings points for each team with each combination of outcomes.
:* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''
| function array1D(a, d)
local m = {}
for i=1,a do
table.insert(m, d)
end
return m
end
function array2D(a, b, d)
local m = {}
for i=1,a do
table.insert(m, array1D(b, d))
end
return m
end
function fromBase3(num)
local out = 0
for i=1,#num do
local c = num:sub(i,i)
local d = tonumber(c)
out = 3 * out + d
end
return out
end
function toBase3(num)
local ss = ""
while num > 0 do
local rem = num % 3
num = math.floor(num / 3)
ss = ss .. tostring(rem)
end
return string.reverse(ss)
end
games = { "12", "13", "14", "23", "24", "34" }
results = "000000"
function nextResult()
if results == "222222" then
return false
end
local res = fromBase3(results)
results = string.format("%06s", toBase3(res + 1))
return true
end
points = array2D(4, 10, 0)
repeat
local records = array1D(4, 0)
for i=1,#games do
if results:sub(i,i) == '2' then
local j = tonumber(games[i]:sub(1,1))
records[j] = records[j] + 3
elseif results:sub(i,i) == '1' then
local j = tonumber(games[i]:sub(1,1))
records[j] = records[j] + 1
j = tonumber(games[i]:sub(2,2))
records[j] = records[j] + 1
elseif results:sub(i,i) == '0' then
local j = tonumber(games[i]:sub(2,2))
records[j] = records[j] + 3
end
end
table.sort(records)
for i=1,#records do
points[i][records[i]+1] = points[i][records[i]+1] + 1
end
until not nextResult()
print("POINTS 0 1 2 3 4 5 6 7 8 9")
print("-------------------------------------------------------------")
places = { "1st", "2nd", "3rd", "4th" }
for i=1,#places do
io.write(places[i] .. " place")
local row = points[i]
for j=1,#row do
io.write(string.format("%5d", points[5 - i][j]))
end
print()
end |
Write float arrays to a text file | Lua | Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
| filename = "file.txt"
x = { 1, 2, 3, 1e11 }
y = { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 };
xprecision = 3;
yprecision = 5;
fstr = "%."..tostring(xprecision).."f ".."%."..tostring(yprecision).."f\n"
fp = io.open( filename, "w+" )
for i = 1, #x do
fp:write( string.format( fstr, x[i], y[i] ) )
end
io.close( fp ) |
Write language name in 3D ASCII | Lua | Write/display a language's name in '''3D''' ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
;Related tasks:
* draw a sphere
* draw a cuboid
* draw a rotating cube
* draw a Deathstar
| io.write(" /$$\n")
io.write("| $$\n")
io.write("| $$ /$$ /$$ /$$$$$$\n")
io.write("| $$ | $$ | $$ |____ $$\n")
io.write("| $$ | $$ | $$ /$$$$$$$\n")
io.write("| $$ | $$ | $$ /$$__ $$\n")
io.write("| $$$$$$$$| $$$$$$/| $$$$$$$\n")
io.write("|________/ \______/ \_______/\n") |
Yellowstone sequence | Lua from Java | The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
;Example:
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
;Task
: Find and show as output the first '''30''' Yellowstone numbers.
;Extra
: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
;Related tasks:
:* Greatest common divisor.
:* Plot coordinate pairs.
;See also:
:* The OEIS entry: A098550 The Yellowstone permutation.
:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].
| function gcd(a, b)
if b == 0 then
return a
end
return gcd(b, a % b)
end
function printArray(a)
io.write('[')
for i,v in pairs(a) do
if i > 1 then
io.write(', ')
end
io.write(v)
end
io.write(']')
return nil
end
function removeAt(a, i)
local na = {}
for j,v in pairs(a) do
if j ~= i then
table.insert(na, v)
end
end
return na
end
function yellowstone(sequenceCount)
local yellow = {1, 2, 3}
local num = 4
local notYellow = {}
local yellowSize = 3
while yellowSize < sequenceCount do
local found = -1
for i,test in pairs(notYellow) do
if gcd(yellow[yellowSize - 1], test) > 1 and gcd(yellow[yellowSize - 0], test) == 1 then
found = i
break
end
end
if found >= 0 then
table.insert(yellow, notYellow[found])
notYellow = removeAt(notYellow, found)
yellowSize = yellowSize + 1
else
while true do
if gcd(yellow[yellowSize - 1], num) > 1 and gcd(yellow[yellowSize - 0], num) == 1 then
table.insert(yellow, num)
yellowSize = yellowSize + 1
num = num + 1
break
end
table.insert(notYellow, num)
num = num + 1
end
end
end
return yellow
end
function main()
print("First 30 values in the yellowstone sequence:")
printArray(yellowstone(30))
print()
end
main() |
Zeckendorf number representation | Lua | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.
;Task:
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
;Also see:
* OEIS A014417 for the the sequence of required results.
* Brown's Criterion - Numberphile
;Related task:
* [[Fibonacci sequence]]
| -- Return the distinct Fibonacci numbers not greater than 'n'
function fibsUpTo (n)
local fibList, last, current, nxt = {}, 1, 1
while current <= n do
table.insert(fibList, current)
nxt = last + current
last = current
current = nxt
end
return fibList
end
-- Return the Zeckendorf representation of 'n'
function zeckendorf (n)
local fib, zeck = fibsUpTo(n), ""
for pos = #fib, 1, -1 do
if n >= fib[pos] then
zeck = zeck .. "1"
n = n - fib[pos]
else
zeck = zeck .. "0"
end
end
if zeck == "" then return "0" end
return zeck
end
-- Main procedure
print(" n\t| Zeckendorf(n)")
print(string.rep("-", 23))
for n = 0, 20 do
print(" " .. n, "| " .. zeckendorf(n))
end |
Zhang-Suen thinning algorithm | Lua | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
;Algorithm:
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
;Step 1:
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and P6 is white
* (4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
;Step 2:
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and '''P8''' is white
* (4) At least one of '''P2''' and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
;Iteration:
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
;Task:
# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
;Reference:
* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
* "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| function zhangSuenThin(img)
local dirs={
{ 0,-1},
{ 1,-1},
{ 1, 0},
{ 1, 1},
{ 0, 1},
{-1, 1},
{-1, 0},
{-1,-1},
{ 0,-1},
}
local black=1
local white=0
function A(x, y)
local c=0
local current=img[y+dirs[1][2]][x+dirs[1][1]]
for i=2,#dirs do
local to_compare=img[y+dirs[i][2]][x+dirs[i][1]]
if current==white and to_compare==black then
c=c+1
end
current=to_compare
end
return c
end
function B(x, y)
local c=0
for i=2,#dirs do
local value=img[y+dirs[i][2]][x+dirs[i][1]]
if value==black then
c=c+1
end
end
return c
end
function common_step(x, y)
if img[y][x]~=black or x<=1 or x>=#img[y] or y<=1 or y>=#img then
return false
end
local b_value=B(x, y)
if b_value<2 or b_value>6 then
return false
end
local a_value=A(x, y)
if a_value~=1 then
return false
end
return true
end
function step_one(x, y)
if not common_step(x, y) then
return false
end
local p2=img[y+dirs[1][2]][x+dirs[1][1]]
local p4=img[y+dirs[3][2]][x+dirs[3][1]]
local p6=img[y+dirs[5][2]][x+dirs[5][1]]
local p8=img[y+dirs[7][2]][x+dirs[7][1]]
if p4==white or p6==white or p2==white and p8==white then
return true
end
return false
end
function step_two(x, y)
if not common_step(x, y) then
return false
end
local p2=img[y+dirs[1][2]][x+dirs[1][1]]
local p4=img[y+dirs[3][2]][x+dirs[3][1]]
local p6=img[y+dirs[5][2]][x+dirs[5][1]]
local p8=img[y+dirs[7][2]][x+dirs[7][1]]
if p2==white or p8==white or p4==white and p6==white then
return true
end
return false
end
function convert(to_do)
for k,v in pairs(to_do) do
img[v[2]][v[1]]=white
end
end
function do_step_on_all(step)
local to_convert={}
for y=1,#img do
for x=1,#img[y] do
if step(x, y) then
table.insert(to_convert, {x,y})
end
end
end
convert(to_convert)
return #to_convert>0
end
local continue=true
while continue do
continue=false
if do_step_on_all(step_one) then
continue=true
end
if do_step_on_all(step_two) then
continue=true
end
end
for y=1,#img do
for x=1,#img[y] do
io.write(img[y][x]==black and '#' or ' ')
end
io.write('\n')
end
end
local image = {
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},
{0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,0,0},
{0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0},
{0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0},
{0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0},
{0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
}
zhangSuenThin(image)
|
100 doors | Python 2.5+ | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
;Task:
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
'''Alternate:'''
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| doors = [False] * 100
for i in range(100):
for j in range(i, 100, i+1):
doors[j] = not doors[j]
print("Door %d:" % (i+1), 'open' if doors[i] else 'close')
|
100 doors | Python 3.x | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
;Task:
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
'''Alternate:'''
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| for i in range(1, 101):
if i**0.5 % 1:
state='closed'
else:
state='open'
print("Door {}:{}".format(i, state))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.