title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Barnsley fern
Lua
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). ;Task: Create this fractal fern, using the following transformations: * f1 (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn * f2 (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = -0.04 xn + 0.85 yn + 1.6 * f3 (chosen 7% of the time) xn + 1 = 0.2 xn - 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 * f4 (chosen 7% of the time) xn + 1 = -0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
g = love.graphics wid, hei = g.getWidth(), g.getHeight() function choose( i, j ) local r = math.random() if r < .01 then return 0, .16 * j elseif r < .07 then return .2 * i - .26 * j, .23 * i + .22 * j + 1.6 elseif r < .14 then return -.15 * i + .28 * j, .26 * i + .24 * j + .44 else return .85 * i + .04 * j, -.04 * i + .85 * j + 1.6 end end function createFern( iterations ) local hw, x, y, scale = wid / 2, 0, 0, 45 local pts = {} for k = 1, iterations do pts[1] = { hw + x * scale, hei - 15 - y * scale, 20 + math.random( 80 ), 128 + math.random( 128 ), 20 + math.random( 80 ), 150 } g.points( pts ) x, y = choose( x, y ) end end function love.load() math.randomseed( os.time() ) canvas = g.newCanvas( wid, hei ) g.setCanvas( canvas ) createFern( 15e4 ) g.setCanvas() end function love.draw() g.draw( canvas ) end
Base64 decode data
Lua
See [[Base64 encode data]]. Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
-- Start taken from https://stackoverflow.com/a/35303321 local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- You will need this for encoding/decoding -- decoding function dec(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end -- end of copy local data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo" print(data) print() local decoded = dec(data) print(decoded)
Bell numbers
Lua
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''. ;So: :'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }''' :'''B1 = 1''' There is only one way to partition a set with one element. '''{a}''' :'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}''' :'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}''' : and so on. A simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. ;Task: Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. If you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle. ;See also: :* '''OEIS:A000110 Bell or exponential numbers''' :* '''OEIS:A011971 Aitken's array'''
-- Bell numbers in Lua -- db 6/11/2020 (to replace missing original) local function bellTriangle(n) local tri = { {1} } for i = 2, n do tri[i] = { tri[i-1][i-1] } for j = 2, i do tri[i][j] = tri[i][j-1] + tri[i-1][j-1] end end return tri end local N = 25 -- in lieu of 50, practical limit with double precision floats local tri = bellTriangle(N) print("First 15 and "..N.."th Bell numbers:") for i = 1, 15 do print(i, tri[i][1]) end print(N, tri[N][1]) print() print("First 10 rows of Bell triangle:") for i = 1, 10 do print("[ " .. table.concat(tri[i],", ") .. " ]") end
Benford's law
Lua
{{Wikipedia|Benford's_law}} '''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability :::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right) For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. ''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. ;See also: * numberphile.com. * A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.
actual = {} expected = {} for i = 1, 9 do actual[i] = 0 expected[i] = math.log10(1 + 1 / i) end n = 0 file = io.open("fibs1000.txt", "r") for line in file:lines() do digit = string.byte(line, 1) - 48 actual[digit] = actual[digit] + 1 n = n + 1 end file:close() print("digit actual expected") for i = 1, 9 do print(i, actual[i] / n, expected[i]) end
Best shuffle
Lua
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did ''not'' change. ;Example: tree, eetr, (0) ;Test cases: abracadabra seesaw elk grrrrrr up a ;Related tasks * [[Anagrams/Deranged anagrams]] * [[Permutations/Derangements]]
math.randomseed(os.time()) local function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end end local function bestshuffle(s, r) local order, shufl, count = {}, {}, 0 for ch in s:gmatch(".") do order[#order+1], shufl[#shufl+1] = ch, ch end if r then shuffle(shufl) end for i = 1, #shufl do for j = 1, #shufl do if i ~= j and shufl[i] ~= order[j] and shufl[j] ~= order[i] then shufl[i], shufl[j] = shufl[j], shufl[i] end end end for i = 1, #shufl do if shufl[i] == order[i] then count = count + 1 end end return table.concat(shufl), count end local words = { "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" } local function test(r) print(r and "RANDOM:" or "DETERMINISTIC:") for _, word in ipairs(words) do local shufl, count = bestshuffle(word, r) print(string.format("%s, %s, (%d)", word, shufl, count)) end print() end test(true) test(false)
Bin given limits
Lua
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ..'' bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] ;Task: The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will ''print the limit of each bin together with the count of items that fell in the range''. Assume the numbers to bin are too large to practically sort. ;Task examples: Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
function binner(limits, data) local bins = setmetatable({}, {__index=function() return 0 end}) local n, flr = #limits+1, math.floor for _, x in ipairs(data) do local lo, hi = 1, n while lo < hi do local mid = flr((lo + hi) / 2) if not limits[mid] or x < limits[mid] then hi=mid else lo=mid+1 end end bins[lo] = bins[lo] + 1 end return bins end function printer(limits, bins) for i = 1, #limits+1 do print(string.format("[%3s,%3s) : %d", limits[i-1] or " -∞", limits[i] or " +∞", bins[i])) end end print("PART 1:") limits = {23, 37, 43, 53, 67, 83} data = {95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55} bins = binner(limits, data) printer(limits, bins) print("\nPART 2:") limits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} data = {445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749} bins = binner(limits, data) printer(limits, bins)
Bioinformatics/Sequence mutation
Lua
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: # Choosing a random base position in the sequence. # Mutate the sequence by doing one of either: ## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base) ## '''D'''elete the chosen base at the position. ## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position. # Randomly generate a test DNA sequence of at least 200 bases # "Pretty print" the sequence and a count of its size, and the count of each base in the sequence # Mutate the sequence ten times. # "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. ;Extra credit: * Give more information on the individual mutations applied. * Allow mutations to be weighted and/or chosen.
math.randomseed(os.time()) bases = {"A","C","T","G"} function randbase() return bases[math.random(#bases)] end function mutate(seq) local i,h = math.random(#seq), "%-6s %3s at %3d" local old,new = seq:sub(i,i), randbase() local ops = { function(s) h=h:format("Swap", old..">"..new, i) return s:sub(1,i-1)..new..s:sub(i+1) end, function(s) h=h:format("Delete", " -"..old, i) return s:sub(1,i-1)..s:sub(i+1) end, function(s) h=h:format("Insert", " +"..new, i) return s:sub(1,i-1)..new..s:sub(i) end, } local weighted = { 1,1,2,3 } local n = weighted[math.random(#weighted)] return ops[n](seq), h end local seq,hist="",{} for i = 1, 200 do seq=seq..randbase() end print("ORIGINAL:") prettyprint(seq) print() for i = 1, 10 do seq,h=mutate(seq) hist[#hist+1]=h end print("MUTATIONS:") for i,h in ipairs(hist) do print(" "..h) end print() print("MUTATED:") prettyprint(seq)
Bioinformatics/base count
Lua
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT ;Task: :* "Pretty print" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence :* print the total count of each base in the string.
function prettyprint(seq) -- approx DDBJ format seq = seq:gsub("%A",""):lower() local sums, n = { a=0, c=0, g=0, t=0 }, 1 seq:gsub("(%a)", function(c) sums[c]=sums[c]+1 end) local function printf(s,...) io.write(s:format(...)) end printf("LOCUS AB000000 %12d bp mRNA linear HUM 01-JAN-2001\n", #seq) printf(" BASE COUNT %12d a %12d c %12d g %12d t\n", sums.a, sums.c, sums.g, sums.t) printf("ORIGIN\n") while n < #seq do local sub60 = seq:sub(n,n+59) printf("%9d %s\n", n, sub60:gsub("(..........)","%1 ")) n = n + #sub60 end end prettyprint[[ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT ]]
Biorhythms
Lua from Phix
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple. It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous! To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. The three cycles and their lengths are as follows: :::{| class="wikitable" ! Cycle ! Length |- |Physical | 23 days |- |Emotional | 28 days |- |Mental | 33 days |} The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory. The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice. Example run of my Raku implementation: raku br.raku 1943-03-09 1972-07-11
cycles = {"Physical day ", "Emotional day", "Mental day "} lengths = {23, 28, 33} quadrants = { {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and falling", "valley"}, {"down but rising", "transition"}, } function parse_date_string (birthDate) local year, month, day = birthDate:match("(%d+)-(%d+)-(%d+)") return {year=tonumber(year), month=tonumber(month), day=tonumber(day)} end function days_diffeternce (d1, d2) if d1.year >= 1970 and d2.year >= 1970 then return math.floor(os.difftime(os.time(d2), os.time(d1))/(60*60*24)) else local t1 = math.max (1970-d1.year, 1970-d2.year) t1 = math.ceil(t1/4)*4 d1.year = d1.year + t1 d2.year = d2.year + t1 return math.floor(os.difftime(os.time(d2), os.time(d1))/(60*60*24)) end end function biorhythms (birthDate, targetDate) local bd = parse_date_string(birthDate) local td = parse_date_string(targetDate) local days = days_diffeternce (bd, td) print('Born: '.. birthDate .. ', Target: ' .. targetDate) print("Day: ", days) for i=1, #lengths do local len = lengths[i] local posn = days%len local quadrant = math.floor(posn/len*4)+1 local percent = math.floor(math.sin(2*math.pi*posn/len)*1000)/10 local cycle = cycles[i] local desc = percent > 95 and "peak" or percent < -95 and "valley" or math.abs(percent) < 5 and "critical transition" or "other" if desc == "other" then local t = math.floor(quadrant/4*len)-posn local qtrend, qnext = quadrants[quadrant][1], quadrants[quadrant][2] desc = percent .. '% (' .. qtrend .. ', next transition in ' .. t ..' days)' end print(cycle, posn..'/'..len, ': '.. desc) end print(' ') end datePairs = { {"1943-03-09", "1972-07-11"}, {"1809-01-12", "1863-11-19"}, {"1809-02-12", "1863-11-19"}, {"2021-02-25", "2022-04-18"}, } for i=1, #datePairs do biorhythms(datePairs[i][1], datePairs[i][2]) end
Bitwise IO
Lua 5.1 and later, including LuaJIT
The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always ''quantized'' by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a '''rough''' (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words'' nine (or more) bits long. * Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. * Errors handling is not mandatory
local function BitWriter() return { accumulator = 0, -- For current byte. bitCount = 0, -- Bits set in current byte. outChars = {}, -- writer:writeBit( bit ) writeBit = function(writer, bit) writer.bitCount = writer.bitCount + 1 if bit > 0 then writer.accumulator = writer.accumulator + 2^(8-writer.bitCount) end if writer.bitCount == 8 then writer:_flush() end end, -- writer:writeLsb( value, width ) writeLsb = function(writer, value, width) for i = 1, width do writer:writeBit(value%2) value = math.floor(value/2) end end, -- dataString = writer:getOutput( ) getOutput = function(writer) writer:_flush() return table.concat(writer.outChars) end, _flush = function(writer) if writer.bitCount == 0 then return end table.insert(writer.outChars, string.char(writer.accumulator)) writer.accumulator = 0 writer.bitCount = 0 end, } end local function BitReader(data) return { bitPosition = 0, -- Absolute position in 'data'. -- bit = reader:readBit( ) -- Returns nil at end-of-data. readBit = function(reader) reader.bitPosition = reader.bitPosition + 1 local bytePosition = math.floor((reader.bitPosition-1)/8) + 1 local byte = data:byte(bytePosition) if not byte then return nil end local bitIndex = ((reader.bitPosition-1)%8) + 1 return math.floor(byte / 2^(8-bitIndex)) % 2 end, -- value = reader:readLsb( width ) -- Returns nil at end-of-data. readLsb = function(reader, width) local accumulator = 0 for i = 1, width do local bit = reader:readBit() if not bit then return nil end if bit > 0 then accumulator = accumulator + 2^(i-1) end end return accumulator end, } end
Box the compass
Lua from Logo
Avast me hearties! There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! ;Task description: # Create a function that takes a heading in degrees and returns the correct 32-point compass heading. # Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: :[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). ;Notes; * The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 * The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
-- List of abbreviated compass point labels compass_points = { "N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN", "E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE", "S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS", "W", "WbN", "W-NW", "NWbW", "NW", "NWbN", "N-NW", "NbW" } -- List of angles to test test_angles = { 0.00, 16.87, 16.88, 33.75, 50.62, 50.63, 67.50, 84.37, 84.38, 101.25, 118.12, 118.13, 135.00, 151.87, 151.88, 168.75, 185.62, 185.63, 202.50, 219.37, 219.38, 236.25, 253.12, 253.13, 270.00, 286.87, 286.88, 303.75, 320.62, 320.63, 337.50, 354.37, 354.38 } -- capitalize a string function capitalize(s) return s:sub(1,1):upper() .. s:sub(2) end -- convert compass point abbreviation to full text of label function expand_point(abbr) for from, to in pairs( { N="north", E="east", S="south", W="west", b=" by " }) do abbr = abbr:gsub(from, to) end return capitalize(abbr) end -- modulus function that returns 1..N instead of 0..N-1 function adjusted_modulo(n, d) return 1 + (n - 1) % d end -- convert a compass angle from degrees into a box index (1..32) function compass_point(degrees) degrees = degrees % 360 return adjusted_modulo(1 + math.floor( (degrees+5.625) / 11.25), 32) end -- Now output the table of test data header_format = "%-7s | %-18s | %s" row_format = "%7.2f | %-18s | %2d" print(header_format:format("Degrees", "Closest Point", "Index")) for i, angle in ipairs(test_angles) do index = compass_point(angle) abbr = compass_points[index] label = expand_point(abbr) print(row_format:format(angle, label, index)) end
Brazilian numbers
Lua from C
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits. ;E.G.: :* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''. :* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same. :* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same. :* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same. :* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same. :* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same. :* ''and so on...'' All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''. More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1''' The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2 ;Task: Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; :* the first '''20''' Brazilian numbers; :* the first '''20 odd''' Brazilian numbers; :* the first '''20 prime''' Brazilian numbers; ;See also: :* '''OEIS:A125134 - Brazilian numbers''' :* '''OEIS:A257521 - Odd Brazilian numbers''' :* '''OEIS:A085104 - Prime Brazilian numbers'''
function sameDigits(n,b) local f = n % b n = math.floor(n / b) while n > 0 do if n % b ~= f then return false end n = math.floor(n / b) end return true end function isBrazilian(n) if n < 7 then return false end if (n % 2 == 0) and (n >= 8) then return true end for b=2,n-2 do if sameDigits(n,b) then return true end end return false end function isPrime(n) if n < 2 then return false end if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end local d = 5 while d * d <= n do if n % d == 0 then return false end d = d + 2 if n % d == 0 then return false end d = d + 4 end return true end function main() local kinds = {" ", " odd ", " prime "} for i=1,3 do print("First 20" .. kinds[i] .. "Brazillion numbers:") local c = 0 local n = 7 while true do if isBrazilian(n) then io.write(n .. " ") c = c + 1 if c == 20 then print() print() break end end if i == 1 then n = n + 1 elseif i == 2 then n = n + 2 elseif i == 3 then repeat n = n + 2 until isPrime(n) end end end end main()
Break OO privacy
Lua
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory. Note that cheating on your type system is almost universally regarded as unidiomatic at best, and poor programming practice at worst. Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
local function Counter() -- These two variables are "private" to this function and can normally -- only be accessed from within this scope, including by any function -- created inside here. local counter = {} local count = 0 function counter:increment() -- 'count' is an upvalue here and can thus be accessed through the -- debug library, as long as we have a reference to this function. count = count + 1 end return counter end -- Create a counter object and try to access the local 'count' variable. local counter = Counter() for i = 1, math.huge do local name, value = debug.getupvalue(counter.increment, i) if not name then break end -- No more upvalues. if name == "count" then print("Found 'count', which is "..tostring(value)) -- If the 'counter.increment' function didn't access 'count' -- directly then we would never get here. break end end
Burrows–Wheeler transform
Lua from Java
{{Wikipedia|Burrows-Wheeler_transform}} The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows-Wheeler transform
STX = string.char(tonumber(2,16)) ETX = string.char(tonumber(3,16)) function bwt(s) if s:find(STX, 1, true) then error("String cannot contain STX") end if s:find(ETX, 1, true) then error("String cannot contain ETX") end local ss = STX .. s .. ETX local tbl = {} for i=1,#ss do local before = ss:sub(i + 1) local after = ss:sub(1, i) table.insert(tbl, before .. after) end table.sort(tbl) local sb = "" for _,v in pairs(tbl) do sb = sb .. string.sub(v, #v, #v) end return sb end function ibwt(r) local le = #r local tbl = {} for i=1,le do table.insert(tbl, "") end for j=1,le do for i=1,le do tbl[i] = r:sub(i,i) .. tbl[i] end table.sort(tbl) end for _,row in pairs(tbl) do if row:sub(le,le) == ETX then return row:sub(2, le - 1) end end return "" end function makePrintable(s) local a = s:gsub(STX, '^') local b = a:gsub(ETX, '|') return b end function main() local tests = { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", STX .. "ABC" .. ETX } for _,test in pairs(tests) do print(makePrintable(test)) io.write(" --> ") local t = "" if xpcall( function () t = bwt(test) end, function (err) print("ERROR: " .. err) end ) then print(makePrintable(t)) end local r = ibwt(t) print(" --> " .. r) print() end end main()
CSV data manipulation
Lua
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. ;Task: Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 Suggestions Show how to add a column, headed 'SUM', of the sums of the rows. If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
local csv={} for line in io.lines('file.csv') do table.insert(csv, {}) local i=1 for j=1,#line do if line:sub(j,j) == ',' then table.insert(csv[#csv], line:sub(i,j-1)) i=j+1 end end table.insert(csv[#csv], line:sub(i,j)) end table.insert(csv[1], 'SUM') for i=2,#csv do local sum=0 for j=1,#csv[i] do sum=sum + tonumber(csv[i][j]) end if sum>0 then table.insert(csv[i], sum) end end local newFileData = '' for i=1,#csv do newFileData=newFileData .. table.concat(csv[i], ',') .. '\n' end local file=io.open('file.csv', 'w') file:write(newFileData)
CSV to HTML translation
Lua
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be ''escaped'' when converted to HTML ;Task: Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. : Character,Speech : The multitude,The messiah! Show us the messiah! : Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! : The multitude,Who are you? : Brians mother,I'm his mother; that's who! : The multitude,Behold his mother! Behold his mother! ;Extra credit: ''Optionally'' allow special formatting for the first row of the table as if it is the tables header row (via preferably; CSS if you must).
FS = "," -- field separator csv = [[ Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! ]] csv = csv:gsub( "<", "&lt;" ) csv = csv:gsub( ">", "&gr;" ) html = { "<table>" } for line in string.gmatch( csv, "(.-\n)" ) do str = "<tr>" for field in string.gmatch( line, "(.-)["..FS.."?\n?]" ) do str = str .. "<td>" .. field .. "</td>" end str = str .. "</tr>" html[#html+1] = str; end html[#html+1] = "</table>" for _, line in pairs(html) do print(line) end
Calculating the value of e
Lua
Calculate the value of ''e''. (''e'' is also known as ''Euler's number'' and ''Napier's constant''.) See details: Calculating the value of e
EPSILON = 1.0e-15; fact = 1 e = 2.0 e0 = 0.0 n = 2 repeat e0 = e fact = fact * n n = n + 1 e = e + 1.0 / fact until (math.abs(e - e0) < EPSILON) io.write(string.format("e = %.15f\n", e))
Call a function
Lua
Demonstrate the different syntax and semantics provided for calling a function. This may include: :* Calling a function that requires no arguments :* Calling a function with a fixed number of arguments :* Calling a function with optional arguments :* Calling a function with a variable number of arguments :* Calling a function with named arguments :* Using a function in statement context :* Using a function in first-class context within an expression :* Obtaining the return value of a function :* Distinguishing built-in functions and user-defined functions :* Distinguishing subroutines and functions ;* Stating whether arguments are passed by value or by reference ;* Is partial application possible and how This task is ''not'' about defining functions.
-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped. function fixed (a, b, c) print(a, b, c) end fixed() --> nil nil nil fixed(1, 2, 3, 4, 5) --> 1 2 3 -- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of values. function vararg (...) print(...) end vararg(1, 2, 3, 4, 5) -- 1 2 3 4 5 -- Lua also allows dropping the parentheses if table or string literals are used as the sole argument print "some string" print { foo = "bar" } -- also serves as a form of named arguments -- First-class functions in expression context print(("this is backwards uppercase"):gsub("%w+", function (s) return s:upper():reverse() end)) -- Functions can return multiple values (including none), which can be counted via select() local iter, obj, start = ipairs { 1, 2, 3 } print(select("#", (function () end)())) --> 0 print(select("#", unpack { 1, 2, 3, 4 })) --> 4 -- Partial application function prefix (pre) return function (suf) return pre .. suf end end local prefixed = prefix "foo" print(prefixed "bar", prefixed "baz", prefixed "quux") -- nil, booleans, and numbers are always passed by value. Everything else is always passed by reference. -- There is no separate notion of subroutines -- Built-in functions are not easily distinguishable from user-defined functions
Cantor set
Lua from python
Draw a Cantor set. See details at this Wikipedia webpage: Cantor set
local WIDTH = 81 local HEIGHT = 5 local lines = {} function cantor(start, length, index) -- must be local, or only one side will get calculated local seg = math.floor(length / 3) if 0 == seg then return nil end -- remove elements that are not in the set for it=0, HEIGHT - index do i = index + it for jt=0, seg - 1 do j = start + seg + jt pos = WIDTH * i + j lines[pos] = ' ' end end -- left side cantor(start, seg, index + 1) -- right side cantor(start + seg * 2, seg, index + 1) return nil end -- initialize the lines for i=0, WIDTH * HEIGHT do lines[i] = '*' end -- calculate cantor(0, WIDTH, 1) -- print the result sets for i=0, HEIGHT-1 do beg = WIDTH * i for j=beg, beg+WIDTH-1 do if j <= WIDTH * HEIGHT then io.write(lines[j]) end end print() end
Cartesian product of two or more lists
Lua
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: ::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: ::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. :: {1, 2} x {} = {} :: {} x {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: :: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1} :: {1, 2, 3} x {30} x {500, 100} :: {1, 2, 3} x {} x {500, 100}
local pk,upk = table.pack, table.unpack local getn = function(t)return #t end local const = function(k)return function(e) return k end end local function attachIdx(f)-- one-time-off function modifier local idx = 0 return function(e)idx=idx+1 ; return f(e,idx)end end local function reduce(t,acc,f) for i=1,t.n or #t do acc=f(acc,t[i])end return acc end local function imap(t,f) local r = {n=t.n or #t, r=reduce, u=upk, m=imap} for i=1,r.n do r[i]=f(t[i])end return r end local function prod(...) local ts = pk(...) local limit = imap(ts,getn) local idx, cnt = imap(limit,const(1)), 0 local max = reduce(limit,1,function(a,b)return a*b end) local function ret(t,i)return t[idx[i]] end return function() if cnt>=max then return end -- no more output if cnt==0 then -- skip for 1st cnt = cnt + 1 else cnt, idx[#idx] = cnt + 1, idx[#idx] + 1 for i=#idx,2,-1 do -- update index list if idx[i]<=limit[i] then break -- no further update need else -- propagate limit overflow idx[i],idx[i-1] = 1, idx[i-1]+1 end end end return cnt,imap(ts,attachIdx(ret)):u() end end --- test for i,a,b in prod({1,2},{3,4}) do print(i,a,b) end print() for i,a,b in prod({3,4},{1,2}) do print(i,a,b) end
Casting out nines
Lua from C
Task (in three parts): ;Part 1 Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky. Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application. With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1. ;Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: : Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]). : note that 318682 has the same checksum as (101558 + 217124); : note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); : note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2. Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. ;Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: : \mathit{co9}(x) is the residual of x mod 9; : the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. ;related tasks * [[First perfect square in base N with N unique digits]] * [[Kaprekar numbers]]
local N = 2 local base = 10 local c1 = 0 local c2 = 0 for k = 1, math.pow(base, N) - 1 do c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 io.write(k .. ' ') end end print() print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.0 * c2 / c1))
Catalan numbers/Pascal's triangle
Lua
Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle. ;See: * Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction. * Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition. * Sequence A000108 on OEIS has a lot of information on Catalan Numbers. ;Related Tasks: [[Pascal's triangle]]
function nextrow (t) local ret = {} t[0], t[#t + 1] = 0, 0 for i = 1, #t do ret[i] = t[i - 1] + t[i] end return ret end function catalans (n) local t, middle = {1} for i = 1, n do middle = math.ceil(#t / 2) io.write(t[middle] - (t[middle + 1] or 0) .. " ") t = nextrow(nextrow(t)) end end catalans(15)
Catamorphism
Lua
''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. ;Task: Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language. ;See also: * Wikipedia article: Fold * Wikipedia article: Catamorphism
table.unpack = table.unpack or unpack -- 5.1 compatibility local nums = {1,2,3,4,5,6,7,8,9} function add(a,b) return a+b end function mult(a,b) return a*b end function cat(a,b) return tostring(a)..tostring(b) end local function reduce(fun,a,b,...) if ... then return reduce(fun,fun(a,b),...) else return fun(a,b) end end local arithmetic_sum = function (...) return reduce(add,...) end local factorial5 = reduce(mult,5,4,3,2,1) print("Σ(1..9) : ",arithmetic_sum(table.unpack(nums))) print("5! : ",factorial5) print("cat {1..9}: ",reduce(cat,table.unpack(nums)))
Chaocipher
Lua
Description: The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ;Task: Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
-- Chaocipher, in Lua, 6/19/2020 db local Chaocipher = { ct = "HXUCZVAMDSLKPEFJRIGTWOBNYQ", pt = "PTLNBQDEOYSFAVZKGJRIHWXUMC", encrypt = function(self, text) return self:_encdec(text, true) end, decrypt = function(self, text) return self:_encdec(text, false) end, _encdec = function(self, text, encflag) local ct, pt, s = self.ct, self.pt, "" local cshl = function(s,i) return s:sub(i) .. s:sub(1,i-1) end local sshl = function(s,i) return s:sub(1,i-1) .. s:sub(i+1,14) .. s:sub(i,i) .. s:sub(15) end for ch in text:gmatch(".") do local i = (encflag and pt or ct):find(ch) s = s .. (encflag and ct or pt):sub(i,i) if encflag then print(ct, pt, ct:sub(i,i), pt:sub(i,i)) end ct, pt = sshl(cshl(ct, i), 2), sshl(cshl(pt, i+1), 3) end return s end, } local plainText = "WELLDONEISBETTERTHANWELLSAID" local encryptText = Chaocipher:encrypt(plainText) local decryptText = Chaocipher:decrypt(encryptText) print() print("The original text was: " .. plainText) print("The encrypted text is: " .. encryptText) print("The decrypted text is: " .. decryptText)
Chaos game
Lua
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. ;Task Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. ;See also * The Game of Chaos
math.randomseed( os.time() ) colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {} function love.load() wid, hei = love.graphics.getWidth(), love.graphics.getHeight() orig[1] = { wid / 2, 3 } orig[2] = { 3, hei - 3 } orig[3] = { wid - 3, hei - 3 } local w, h = math.random( 10, 40 ), math.random( 10, 40 ) if math.random() < .5 then w = -w end if math.random() < .5 then h = -h end orig[4] = { wid / 2 + w, hei / 2 + h } canvas = love.graphics.newCanvas( wid, hei ) love.graphics.setCanvas( canvas ); love.graphics.clear() love.graphics.setColor( 255, 255, 255 ) love.graphics.points( orig ) love.graphics.setCanvas() end function love.draw() local iter = 100 --> make this number bigger to speed up rendering for rp = 1, iter do local r, pts = math.random( 6 ), {} if r == 1 or r == 4 then pt = 1 elseif r == 2 or r == 5 then pt = 2 else pt = 3 end local x, y = ( orig[4][1] + orig[pt][1] ) / 2, ( orig[4][2] + orig[pt][2] ) / 2 orig[4][1] = x; orig[4][2] = y pts[1] = { x, y, colors[pt][1], colors[pt][2], colors[pt][3], 255 } love.graphics.setCanvas( canvas ) love.graphics.points( pts ) end love.graphics.setCanvas() love.graphics.draw( canvas ) end
Cheryl's birthday
Lua
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. ;Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. ;Related task: * [[Sum and Product Puzzle]] ;References * Wikipedia article of the same name. * Tuple Relational Calculus
-- Cheryl's Birthday in Lua 6/15/2020 db local function Date(mon,day) return { mon=mon, day=day, valid=true } end local choices = { Date("May", 15), Date("May", 16), Date("May", 19), Date("June", 17), Date("June", 18), Date("July", 14), Date("July", 16), Date("August", 14), Date("August", 15), Date("August", 17) } local function apply(t, f) for k, v in ipairs(t) do f(k, v) end end local function filter(t, f) local result = {} for k, v in ipairs(t) do if f(k, v) then result[#result+1] = v end end return result end local function map(t, f) local result = {} for k, v in ipairs(t) do result[#result+1] = f(k, v) end return result end local function count(t) return #t end local function isvalid(k, v) return v.valid end local function invalidate(k, v) v.valid = false end local function remaining() return filter(choices, isvalid) end local function listValidChoices() print(" " .. table.concat(map(remaining(), function(k, v) return v.mon .. " " .. v.day end), ", ")) print() end print("Cheryl offers these ten choices:") listValidChoices() print("1) Albert knows that Bernard also cannot yet know, so cannot be a month with a unique day, leaving:") apply(remaining(), function(k, v) if count(filter(choices, function(k2, v2) return v.day==v2.day end)) == 1 then apply(filter(remaining(), function(k2, v2) return v.mon==v2.mon end), invalidate) end end) listValidChoices() print("2) After Albert's revelation, Bernard now knows, so day must be unique, leaving:") apply(remaining(), function(k, v) local subset = filter(remaining(), function(k2, v2) return v.day==v2.day end) if count(subset) > 1 then apply(subset, invalidate) end end) listValidChoices() print("3) After Bernard's revelation, Albert now knows, so month must be unique, leaving only:") apply(remaining(), function(k, v) local subset = filter(remaining(), function(k2, v2) return v.mon==v2.mon end) if count(subset) > 1 then apply(subset, invalidate) end end) listValidChoices()
Chinese remainder theorem
Lua
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv a_2 \pmod{n_2} \\ &{}\ \ \vdots \\ x &\equiv a_k \pmod{n_k} \end{align} Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. ;Task: Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. ''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2]. '''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: ::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows: For each i, the integers n_i and N/n_i are co-prime. Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. Then, one solution to the system of simultaneous congruences is: ::: x = \sum_{i=1}^k a_i s_i N/n_i and the minimal solution, ::: x \pmod{N}.
-- Taken from https://www.rosettacode.org/wiki/Sum_and_product_of_an_array#Lua function prodf(a, ...) return a and a * prodf(...) or 1 end function prodt(t) return prodf(unpack(t)) end function mulInv(a, b) local b0 = b local x0 = 0 local x1 = 1 if b == 1 then return 1 end while a > 1 do local q = math.floor(a / b) local amb = math.fmod(a, b) a = b b = amb local xqx = x1 - q * x0 x1 = x0 x0 = xqx end if x1 < 0 then x1 = x1 + b0 end return x1 end function chineseRemainder(n, a) local prod = prodt(n) local p local sm = 0 for i=1,#n do p = prod / n[i] sm = sm + a[i] * mulInv(p, n[i]) * p end return math.fmod(sm, prod) end n = {3, 5, 7} a = {2, 3, 2} io.write(chineseRemainder(n, a))
Chinese zodiac
Lua from C
Determine the Chinese zodiac sign and related associations for a given year. Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades. Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit. The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang. Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin. ;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). ;Requisite information: * The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. * The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. * Each element gets two consecutive years; a yang followed by a yin. * The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from. Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. ;Information for optional task: * The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". * The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
local ANIMALS = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"} local ELEMENTS = {"Wood","Fire","Earth","Metal","Water"} function element(year) local idx = math.floor(((year - 4) % 10) / 2) return ELEMENTS[idx + 1] end function animal(year) local idx = (year - 4) % 12 return ANIMALS[idx + 1] end function yy(year) if year % 2 == 0 then return "yang" else return "yin" end end function zodiac(year) local e = element(year) local a = animal(year) local y = yy(year) print(year.." is the year of the "..e.." "..a.." ("..y..")") end zodiac(1935) zodiac(1938) zodiac(1968) zodiac(1972) zodiac(1976) zodiac(2017)
Church numerals
Lua
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. * '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. * '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)''' * '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))''' * and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: * Church Zero, * a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), * functions for Addition, Multiplication and Exponentiation over Church numerals, * a function to convert integers to corresponding Church numerals, * and a function to convert Church numerals to corresponding integers. You should: * Derive Church numerals three and four in terms of Church zero and a Church successor function. * use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, * similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, * convert each result back to an integer, and return it or print it to the console.
function churchZero() return function(x) return x end end function churchSucc(c) return function(f) return function(x) return f(c(f)(x)) end end end function churchAdd(c, d) return function(f) return function(x) return c(f)(d(f)(x)) end end end function churchMul(c, d) return function(f) return c(d(f)) end end function churchExp(c, e) return e(c) end function numToChurch(n) local ret = churchZero for i = 1, n do ret = succ(ret) end return ret end function churchToNum(c) return c(function(x) return x + 1 end)(0) end three = churchSucc(churchSucc(churchSucc(churchZero))) four = churchSucc(churchSucc(churchSucc(churchSucc(churchZero)))) print("'three'\t=", churchToNum(three)) print("'four' \t=", churchToNum(four)) print("'three' * 'four' =", churchToNum(churchMul(three, four))) print("'three' + 'four' =", churchToNum(churchAdd(three, four))) print("'three' ^ 'four' =", churchToNum(churchExp(three, four))) print("'four' ^ 'three' =", churchToNum(churchExp(four, three)))
Circles of given radius through two points
Lua from C
2 circles with a given radius through 2 points in 2D space. Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. ;Exceptions: # r==0.0 should be treated as never describing circles (except in the case where the points are coincident). # If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. # If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language. # If the points are too far apart then no circles can be drawn. ;Task detail: * Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''. * Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 ;Related task: * [[Total circles area]]. ;See also: * Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
function distance(p1, p2) local dx = (p1.x-p2.x) local dy = (p1.y-p2.y) return math.sqrt(dx*dx + dy*dy) end function findCircles(p1, p2, radius) local seperation = distance(p1, p2) if seperation == 0.0 then if radius == 0.0 then print("No circles can be drawn through ("..p1.x..", "..p1.y..")") else print("Infinitely many circles can be drawn through ("..p1.x..", "..p1.y..")") end elseif seperation == 2*radius then local cx = (p1.x+p2.x)/2 local cy = (p1.y+p2.y)/2 print("Given points are opposite ends of a diameter of the circle with center ("..cx..", "..cy..") and radius "..radius) elseif seperation > 2*radius then print("Given points are further away from each other than a diameter of a circle with radius "..radius) else local mirrorDistance = math.sqrt(math.pow(radius,2) - math.pow(seperation/2,2)) local dx = p2.x - p1.x local dy = p1.y - p2.y local ax = (p1.x + p2.x) / 2 local ay = (p1.y + p2.y) / 2 local mx = mirrorDistance * dx / seperation local my = mirrorDistance * dy / seperation c1 = {x=ax+my, y=ay+mx} c2 = {x=ax-my, y=ay-mx} print("Two circles are possible.") print("Circle C1 with center ("..c1.x..", "..c1.y.."), radius "..radius) print("Circle C2 with center ("..c2.x..", "..c2.y.."), radius "..radius) end print() end cases = { {x=0.1234, y=0.9876}, {x=0.8765, y=0.2345}, {x=0.0000, y=2.0000}, {x=0.0000, y=0.0000}, {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876}, {x=0.8765, y=0.2345}, {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876} } radii = { 2.0, 1.0, 2.0, 0.5, 0.0 } for i=1, #radii do print("Case "..i) findCircles(cases[i*2-1], cases[i*2], radii[i]) end
Cistercian numerals
Lua from Go
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''. ;How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: :* The '''upper-right''' quadrant represents the '''ones''' place. :* The '''upper-left''' quadrant represents the '''tens''' place. :* The '''lower-right''' quadrant represents the '''hundreds''' place. :* The '''lower-left''' quadrant represents the '''thousands''' place. Please consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg] ;Task :* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). :* Use the routine to show the following Cistercian numerals: ::* 0 ::* 1 ::* 20 ::* 300 ::* 4000 ::* 5555 ::* 6789 ::* And a number of your choice! ;Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output. ;See also :* '''Numberphile - The Forgotten Number System''' :* '''dcode.fr - Online Cistercian numeral converter'''
function initN() local n = {} for i=1,15 do n[i] = {} for j=1,11 do n[i][j] = " " end n[i][6] = "x" end return n end function horiz(n, c1, c2, r) for c=c1,c2 do n[r+1][c+1] = "x" end end function verti(n, r1, r2, c) for r=r1,r2 do n[r+1][c+1] = "x" end end function diagd(n, c1, c2, r) for c=c1,c2 do n[r+c-c1+1][c+1] = "x" end end function diagu(n, c1, c2, r) for c=c1,c2 do n[r-c+c1+1][c+1] = "x" end end function initDraw() local draw = {} draw[1] = function(n) horiz(n, 6, 10, 0) end draw[2] = function(n) horiz(n, 6, 10, 4) end draw[3] = function(n) diagd(n, 6, 10, 0) end draw[4] = function(n) diagu(n, 6, 10, 4) end draw[5] = function(n) draw[1](n) draw[4](n) end draw[6] = function(n) verti(n, 0, 4, 10) end draw[7] = function(n) draw[1](n) draw[6](n) end draw[8] = function(n) draw[2](n) draw[6](n) end draw[9] = function(n) draw[1](n) draw[8](n) end draw[10] = function(n) horiz(n, 0, 4, 0) end draw[20] = function(n) horiz(n, 0, 4, 4) end draw[30] = function(n) diagu(n, 0, 4, 4) end draw[40] = function(n) diagd(n, 0, 4, 0) end draw[50] = function(n) draw[10](n) draw[40](n) end draw[60] = function(n) verti(n, 0, 4, 0) end draw[70] = function(n) draw[10](n) draw[60](n) end draw[80] = function(n) draw[20](n) draw[60](n) end draw[90] = function(n) draw[10](n) draw[80](n) end draw[100] = function(n) horiz(n, 6, 10, 14) end draw[200] = function(n) horiz(n, 6, 10, 10) end draw[300] = function(n) diagu(n, 6, 10, 14) end draw[400] = function(n) diagd(n, 6, 10, 10) end draw[500] = function(n) draw[100](n) draw[400](n) end draw[600] = function(n) verti(n, 10, 14, 10) end draw[700] = function(n) draw[100](n) draw[600](n) end draw[800] = function(n) draw[200](n) draw[600](n) end draw[900] = function(n) draw[100](n) draw[800](n) end draw[1000] = function(n) horiz(n, 0, 4, 14) end draw[2000] = function(n) horiz(n, 0, 4, 10) end draw[3000] = function(n) diagd(n, 0, 4, 10) end draw[4000] = function(n) diagu(n, 0, 4, 14) end draw[5000] = function(n) draw[1000](n) draw[4000](n) end draw[6000] = function(n) verti(n, 10, 14, 0) end draw[7000] = function(n) draw[1000](n) draw[6000](n) end draw[8000] = function(n) draw[2000](n) draw[6000](n) end draw[9000] = function(n) draw[1000](n) draw[8000](n) end return draw end function printNumeral(n) for i,v in pairs(n) do for j,w in pairs(v) do io.write(w .. " ") end print() end print() end function main() local draw = initDraw() for i,number in pairs({0, 1, 20, 300, 4000, 5555, 6789, 9999}) do local n = initN() print(number..":") local thousands = math.floor(number / 1000) number = number % 1000 local hundreds = math.floor(number / 100) number = number % 100 local tens = math.floor(number / 10) local ones = number % 10 if thousands > 0 then draw[thousands * 1000](n) end if hundreds > 0 then draw[hundreds * 100](n) end if tens > 0 then draw[tens * 10](n) end if ones > 0 then draw[ones](n) end printNumeral(n) end end main()
Closures/Value capture
Lua
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. ;Goal: Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: [[Multiple distinct objects]]
funcs={} for i=1,10 do table.insert(funcs, function() return i*i end) end funcs[2]() funcs[3]()
Comma quibbling
Lua
Comma quibbling is a task originally set by Eric Lippert in his blog. ;Task: Write a function to generate a string output which is the concatenation of input words from a list/sequence where: # An input of no words produces the output string of just the two brace characters "{}". # An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". # An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". # An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: * [] # (No input words). * ["ABC"] * ["ABC", "DEF"] * ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
function quibble (strTab) local outString, join = "{" for strNum = 1, #strTab do if strNum == #strTab then join = "" elseif strNum == #strTab - 1 then join = " and " else join = ", " end outString = outString .. strTab[strNum] .. join end return outString .. '}' end local testCases = { {}, {"ABC"}, {"ABC", "DEF"}, {"ABC", "DEF", "G", "H"} } for _, input in pairs(testCases) do print(quibble(input)) end
Command-line arguments
Lua
{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]]. See also [[Program name]]. For parsing command line arguments intelligently, see [[Parsing command-line arguments]]. Example command line: myprogram -c "alpha beta" -h "gamma"
print( "Program name:", arg[0] ) print "Arguments:" for i = 1, #arg do print( i," ", arg[i] ) end
Compare a list of strings
Lua
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. If the input list has less than two elements, the tests should always return true. There is ''no'' need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible. Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers. If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
function identical(t_str) _, fst = next(t_str) if fst then for _, i in pairs(t_str) do if i ~= fst then return false end end end return true end function ascending(t_str) prev = false for _, i in ipairs(t_str) do if prev and prev >= i then return false end prev = i end return true end function check(str) t_str = {} for i in string.gmatch(str, "[%a_]+") do table.insert(t_str, i) end str = str .. ": " if not identical(t_str) then str = str .. "not " end str = str .. "identical and " if not ascending(t_str) then str = str .. "not " end print(str .. "ascending.") end check("ayu dab dog gar panda tui yak") check("oy oy oy oy oy oy oy oy oy oy") check("somehow somewhere sometime") check("Hoosiers") check("AA,BB,CC") check("AA,AA,AA") check("AA,CC,BB") check("AA,ACB,BB,CC") check("single_element")
Compiler/lexical analyzer
Lua
The C and Python versions can be considered reference implementations. ;Related Tasks * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task
-- module basic_token_finder local M = {} -- only items added to M will be public (via 'return M' at end) local table, string = table, string local error, tonumber, select, assert = error, tonumber, select, assert local token_name = require 'token_name' _ENV = {} function next_token(line, pos, line_num) -- match a token at line,pos local function m(pat) from, to, capture = line:find(pat, pos) if from then pos = to + 1 return capture end end local function ptok(str) return {name=token_name[str]} end local function op2c() local text = m'^([<>=!]=)' or m'^(&&)' or m'^(||)' if text then return ptok(text) end end local function op1c_or_symbol() local char = m'^([%*/%%%+%-<>!=%(%){};,])' if char then return ptok(char) end end local function keyword_or_identifier() local text = m'^([%a_][%w_]*)' if text then local name = token_name[text] return name and {name=name} or {name='Identifier', value=text} end end local function integer() local text = m'^(%d+)%f[^%w_]' if text then return {name='Integer', value=tonumber(text)} end end local subst = {['\\\\'] = '\\', ['\\n'] = '\n'} local function qchar() local text = m"^'([^\\])'" or m"^'(\\[\\n])'" if text then local value = #text==1 and text:byte() or subst[text]:byte() return {name='Integer', value=value} end end local function qstr() local text = m'^"([^"\n]*\\?)"' if text then local value = text:gsub('()(\\.?)', function(at, esc) local replace = subst[esc] if replace then return replace else error{err='bad_escseq', line=line_num, column=pos+at-1} end end) return {name='String', value=value} end end local found = (op2c() or op1c_or_symbol() or keyword_or_identifier() or integer() or qchar() or qstr()) if found then return found, pos end end function find_commentrest(line, pos, line_num, socpos) local sfrom, sto = line:find('%*%/', pos) if sfrom then return socpos, sto else error{err='unfinished_comment', line=line_num, column=socpos} end end function find_comment(line, pos, line_num) local sfrom, sto = line:find('^%/%*', pos) if sfrom then local efrom, eto = find_commentrest(line, sto+1, line_num, sfrom) return sfrom, eto end end function find_morecomment(line, pos, line_num) assert(pos==1) return find_commentrest(line, pos, line_num, pos) end function find_whitespace(line, pos, line_num) local spos = pos repeat local eto = select(2, line:find('^%s+', pos)) if not eto then eto = select(2, find_comment(line, pos, line_num)) end if eto then pos = eto + 1 end until not eto return spos, pos - 1 end function M.find_token(line, pos, line_num, in_comment) local spos = pos if in_comment then pos = 1 + select(2, find_morecomment(line, pos, line_num)) end pos = 1 + select(2, find_whitespace(line, pos, line_num)) if pos > #line then return nil else local token, nextpos = next_token(line, pos, line_num) if token then token.line, token.column = line_num, pos return token, nextpos else error{err='invalid_token', line=line_num, column=pos} end end end -- M._ENV = _ENV return M
Continued fraction
Lua from C
A number may be represented as a continued fraction (see Mathworld for more information) as follows: :a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}} The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1. :\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}} For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1. :e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}} For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2. :\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}} ;See also: :* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
function calc(fa, fb, expansions) local a = 0.0 local b = 0.0 local r = 0.0 local i = expansions while i > 0 do a = fa(i) b = fb(i) r = b / (a + r) i = i - 1 end a = fa(0) return a + r end function sqrt2a(n) if n ~= 0 then return 2.0 else return 1.0 end end function sqrt2b(n) return 1.0 end function napiera(n) if n ~= 0 then return n else return 2.0 end end function napierb(n) if n > 1.0 then return n - 1.0 else return 1.0 end end function pia(n) if n ~= 0 then return 6.0 else return 3.0 end end function pib(n) local c = 2.0 * n - 1.0 return c * c end function main() local sqrt2 = calc(sqrt2a, sqrt2b, 1000) local napier = calc(napiera, napierb, 1000) local pi = calc(pia, pib, 1000) print(sqrt2) print(napier) print(pi) end main()
Convert decimal number to rational
Lua
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: * 67 / 74 = 0.9(054) = 0.9054054... * 14 / 27 = 0.(518) = 0.518518... Acceptable output: * 0.9054054 - 4527027 / 5000000 * 0.518518 - 259259 / 500000 Finite decimals are of course no problem: * 0.75 - 3 / 4
for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do local n, d, dmax, eps = 1, 1, 1e7, 1e-15 while math.abs(n/d-v)>eps and d<dmax do d=d+1 n=math.floor(v*d) end print(string.format("%15.13f --> %d / %d", v, n, d)) end
Convert seconds to compound duration
Lua
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrate that it passes the following three test-cases: '''''Test Cases''''' :::::{| class="wikitable" |- ! input number ! output string |- | 7259 | 2 hr, 59 sec |- | 86400 | 1 d |- | 6000000 | 9 wk, 6 d, 10 hr, 40 min |} '''''Details''''' The following five units should be used: :::::{| class="wikitable" |- ! unit ! suffix used in output ! conversion |- | week | wk | 1 week = 7 days |- | day | d | 1 day = 24 hours |- | hour | hr | 1 hour = 60 minutes |- | minute | min | 1 minute = 60 seconds |- | second | sec | |} However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
function duration (secs) local units, dur = {"wk", "d", "hr", "min"}, "" for i, v in ipairs({604800, 86400, 3600, 60}) do if secs >= v then dur = dur .. math.floor(secs / v) .. " " .. units[i] .. ", " secs = secs % v end end if secs == 0 then return dur:sub(1, -3) else return dur .. secs .. " sec" end end print(duration(7259)) print(duration(86400)) print(duration(6000000))
Count the coins
Lua
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and 5 pennies :::# A nickel and 10 pennies :::# 15 pennies ;Task: How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents). ;Optional: Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? (Note: the answer is larger than 232). ;References: * an algorithm from the book ''Structure and Interpretation of Computer Programs''. * an article in the algorithmist. * Change-making problem on Wikipedia.
function countSums (amount, values) local t = {} for i = 1, amount do t[i] = 0 end t[0] = 1 for k, val in pairs(values) do for i = val, amount do t[i] = t[i] + t[i - val] end end return t[amount] end print(countSums(100, {1, 5, 10, 25})) print(countSums(100000, {1, 5, 10, 25, 50, 100}))
Create an HTML table
Lua
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. * The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. * The numbers should be aligned in the same fashion for all columns.
function htmlTable (data) local html = "<table>\n<tr>\n<th></th>\n" for _, heading in pairs(data[1]) do html = html .. "<th>" .. heading .. "</th>" .. "\n" end html = html .. "</tr>\n" for row = 2, #data do html = html .. "<tr>\n<th>" .. row - 1 .. "</th>\n" for _, field in pairs(data[row]) do html = html .. "<td>" .. field .. "</td>\n" end html = html .. "</tr>\n" end return html .. "</table>" end local tableData = { {"X", "Y", "Z"}, {"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"} } print(htmlTable(tableData))
Cullen and Woodall numbers
Lua
A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number. A Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number. So for each '''n''' the associated Cullen number and Woodall number differ by 2. ''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.'' '''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime. It is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated. ;Task * Write procedures to find Cullen numbers and Woodall numbers. * Use those procedures to find and show here, on this page the first 20 of each. ;Stretch * Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''. * Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''. ;See also * OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1 * OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1 * OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime * OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
function T(t) return setmetatable(t, {__index=table}) end table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end function cullen(n) return (n<<n)+1 end print("First 20 Cullen numbers:") print(T{}:range(20):map(cullen):concat(" ")) function woodall(n) return (n<<n)-1 end print("First 20 Woodall numbers:") print(T{}:range(20):map(woodall):concat(" "))
Currency
Lua
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. ;Note: The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact. For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. Use the values: ::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers) ::* 2 milkshakes at $2.86 each, and ::* a tax rate of 7.65%. (That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) Compute and output (show results on this page): ::* the total price before tax ::* the tax ::* the total with tax The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. The output must show dollars and cents with a decimal point. The three results displayed should be: ::* 22000000000000005.72 ::* 1683000000000000.44 ::* 23683000000000006.16 Dollar signs and thousands separators are optional.
C = setmetatable(require("bc"), {__call=function(t,...) return t.new(...) end}) C.digits(6) -- enough for .nn * .nnnn ==> .nnnnnn, follow with trunc(2) to trim trailing zeroes subtot = (C"4000000000000000" * C"5.50" + C"2" * C"2.86"):trunc(2) -- cosmetic trunc tax = (subtot * C"0.0765" + C"0.005"):trunc(2) -- rounding trunc total = (subtot + tax):trunc(2) -- cosmetic trunc print(("Before tax: %20s"):format(subtot:tostring())) print(("Tax : %20s"):format(tax:tostring())) print(("With tax : %20s"):format(total:tostring()))
Currying
Lua
{{Wikipedia|Currying}} ;Task: Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
local curry do local call,env = function(fn,...)return fn(...)end local fmt,cat,rawset,rawget,floor = string.format,table.concat,rawset,rawget,math.floor local curryHelper = setmetatable({},{ __call = function(me, n, m, ...)return me[n*256+m](...)end, __index = function(me,k) local n,m = floor(k / 256), k % 256 local r,s = {},{} for i=1,m do r[i],s[i]='_'..i,'_'..i end s[1+#s]='...' r,s=cat(r,','),cat(s,',') s = n<m and fmt('CALL(%s)',r) or fmt('function(...)return ME(%d,%d+select("#",...),%s)end',n,m,s) local sc = fmt('local %s=... return %s',r,s) rawset(me,k,(loadstring or load)(sc,'_',nil,env) ) return rawget(me,k) end}) env = {CALL=call,ME=curryHelper,select=select} function curry(...) local pn,n,fn = select('#',...),... if pn==1 then n,fn = debug.getinfo(n, 'u'),n ; n = n and n.nparams end if type(n)~='number' or n~=floor(n)then return nil,'invalid curry' elseif n<=0 then return fn -- edge case else return curryHelper(n,1,fn) end end end -- test function add(x,y) return x+y end local adder = curry(add) -- get params count from debug.getinfo assert(adder(3)(4) == 3+4) local add2 = adder(2) assert(add2(3) == 2+3) assert(add2(5) == 2+5)
Cut a rectangle
Lua from C++
A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below. [[file:rect-cut.svg]] Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts. Possibly related task: [[Maze generation]] for depth-first search.
function array1D(w, d) local t = {} for i=1,w do table.insert(t, d) end return t end function array2D(h, w, d) local t = {} for i=1,h do table.insert(t, array1D(w, d)) end return t end function push(s, v) s[#s + 1] = v end function pop(s) return table.remove(s, #s) end function empty(s) return #s == 0 end DIRS = { {0, -1}, {-1, 0}, {0, 1}, {1, 0} } function printResult(aa) for i,u in pairs(aa) do io.write("[") for j,v in pairs(u) do if j > 1 then io.write(", ") end io.write(v) end print("]") end end function cutRectangle(w, h) if w % 2 == 1 and h % 2 == 1 then return nil end local grid = array2D(h, w, 0) local stack = {} local half = math.floor((w * h) / 2) local bits = 2 ^ half - 1 while bits > 0 do for i=1,half do local r = math.floor((i - 1) / w) local c = (i - 1) % w if (bits & (1 << (i - 1))) ~= 0 then grid[r + 1][c + 1] = 1 else grid[r + 1][c + 1] = 0 end grid[h - r][w - c] = 1 - grid[r + 1][c + 1] end push(stack, 0) grid[1][1] = 2 local count = 1 while not empty(stack) do local pos = pop(stack) local r = math.floor(pos / w) local c = pos % w for i,dir in pairs(DIRS) do local nextR = r + dir[1] local nextC = c + dir[2] if nextR >= 0 and nextR < h and nextC >= 0 and nextC < w then if grid[nextR + 1][nextC + 1] == 1 then push(stack, nextR * w + nextC) grid[nextR + 1][nextC + 1] = 2 count = count + 1 end end end end if count == half then printResult(grid) print() end -- loop end bits = bits - 2 end end cutRectangle(2, 2) cutRectangle(4, 3)
Damm algorithm
Lua
The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. ;Task: Verify the checksum, stored as last digit of an input.
local tab = { {0,3,1,7,5,9,8,6,4,2}, {7,0,9,2,1,5,4,8,6,3}, {4,2,0,6,8,7,1,3,5,9}, {1,7,5,0,9,8,3,4,2,6}, {6,1,2,3,0,4,5,9,7,8}, {3,6,7,4,2,0,9,5,8,1}, {5,8,6,9,7,2,0,1,3,4}, {8,9,4,5,3,6,2,0,1,7}, {9,4,3,8,6,1,7,2,0,5}, {2,5,8,1,4,3,6,7,9,0} } function check( n ) local idx, a = 0, tonumber( n:sub( 1, 1 ) ) for i = 1, #n do a = tonumber( n:sub( i, i ) ) if a == nil then return false end idx = tab[idx + 1][a + 1] end return idx == 0 end local n, r while( true ) do io.write( "Enter the number to check: " ) n = io.read(); if n == "0" then break end r = check( n ); io.write( n, " is " ) if not r then io.write( "in" ) end io.write( "valid!\n" ) end
De Bruijn sequences
Lua from C++
{{DISPLAYTITLE:de Bruijn sequences}} The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn. A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on a size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every possible length-''n'' string (computer science, formal theory) on ''A'' occurs exactly once as a contiguous substring. Such a sequence is denoted by ''B''(''k'', ''n'') and has length ''k''''n'', which is also the number of distinct substrings of length ''n'' on ''A''; de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1) / kn distinct de Bruijn sequences ''B''(''k'', ''n''). ;Task: For this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on a PIN-like code lock that does not have an "enter" key and accepts the last ''n'' digits entered. Note: automated teller machines (ATMs) used to work like this, but their software has been updated to not allow a brute-force attack. ;Example: A digital door lock with a 4-digit code would have ''B'' (10, 4) solutions, with a length of '''10,000''' (digits). Therefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to open the lock. Trying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses. ;Task requirements: :* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code. :::* Show the length of the generated de Bruijn sequence. :::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page). :::* Show the first and last '''130''' digits of the de Bruijn sequence. :* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence. :::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros). :* Reverse the de Bruijn sequence. :* Again, perform the (above) verification test. :* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence. :::* Perform the verification test (again). There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly. The verification processes should list any and all missing PIN codes.) Show all output here, on this page. ;References: :* Wikipedia entry: de Bruijn sequence. :* MathWorld entry: de Bruijn sequence. :* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
function tprint(tbl) for i,v in pairs(tbl) do print(v) end end function deBruijn(k, n) local a = {} for i=1, k*n do table.insert(a, 0) end local seq = {} function db(t, p) if t > n then if n % p == 0 then for i=1, p do table.insert(seq, a[i + 1]) end end else a[t + 1] = a[t - p + 1] db(t + 1, p) local j = a[t - p + 1] + 1 while j < k do a[t + 1] = j % 256 db(t + 1, t) j = j + 1 end end end db(1, 1) local buf = "" for i,v in pairs(seq) do buf = buf .. tostring(v) end return buf .. buf:sub(1, n - 1) end function allDigits(s) return s:match('[0-9]+') == s end function validate(db) local le = string.len(db) local found = {} local errs = {} for i=1, 10000 do table.insert(found, 0) end -- Check all strings of 4 consecutive digits within 'db' -- to see if all 10,000 combinations occur without duplication. for i=1, le - 3 do local s = db:sub(i, i + 3) if allDigits(s) then local n = tonumber(s) found[n + 1] = found[n + 1] + 1 end end local count = 0 for i=1, 10000 do if found[i] == 0 then table.insert(errs, " PIN number " .. (i - 1) .. " missing") count = count + 1 elseif found[i] > 1 then table.insert(errs, " PIN number " .. (i - 1) .. " occurs " .. found[i] .. " times") count = count + 1 end end if count == 0 then print(" No errors found") else tprint(errs) end end function main() local db = deBruijn(10,4) print("The length of the de Bruijn sequence is " .. string.len(db)) print() io.write("The first 130 digits of the de Bruijn sequence are: ") print(db:sub(0, 130)) print() io.write("The last 130 digits of the de Bruijn sequence are: ") print(db:sub(-130)) print() print("Validating the de Bruijn sequence:") validate(db) print() print("Validating the reversed de Bruijn sequence:") validate(db:reverse()) print() db = db:sub(1,4443) .. "." .. db:sub(4445) print("Validating the overlaid de Bruijn sequence:") validate(db) print() end main()
Deepcopy
Lua
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: * Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. * Any limitations of the method. * That the structure and its copy are different. * Suitable links to external documentation for common libraries.
function _deepcopy(o, tables) if type(o) ~= 'table' then return o end if tables[o] ~= nil then return tables[o] end local new_o = {} tables[o] = new_o for k, v in next, o, nil do local new_k = _deepcopy(k, tables) local new_v = _deepcopy(v, tables) new_o[new_k] = new_v end return new_o end function deepcopy(o) return _deepcopy(o, {}) end
Department numbers
Lua
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
print( "Fire", "Police", "Sanitation" ) sol = 0 for f = 1, 7 do for p = 1, 7 do for s = 1, 7 do if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then print( f, p, s ); sol = sol + 1 end end end end print( string.format( "\n%d solutions found", sol ) )
Descending primes
Lua
Generate and show all primes with strictly descending decimal digits. ;See also ;* OEIS:A052014 - Primes with distinct digits in descending order ;Related: *[[Ascending primes]]
local function is_prime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end for f = 5, n^0.5, 6 do if n%f==0 or n%(f+2)==0 then return false end end return true end local function descending_primes() local digits, candidates, primes = {9,8,7,6,5,4,3,2,1}, {0}, {} for i = 1, #digits do for j = 1, #candidates do local value = candidates[j] * 10 + digits[i] if is_prime(value) then primes[#primes+1] = value end candidates[#candidates+1] = value end end table.sort(primes) return primes end print(table.concat(descending_primes(), ", "))
Detect division by zero
Lua
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
local function div(a,b) if b == 0 then error() end return a/b end
Determinant and permanent
Lua
permanent of the matrix. The determinant is given by :: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i} while the permanent is given by :: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i} In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known. ;Related task: * [[Permutations by swapping]]
-- Johnson–Trotter permutations generator _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 -- matrix class _MTX={} function MTX(matrix) setmetatable(matrix,{__index=_MTX}) matrix.rows=#matrix matrix.cols=#matrix[1] return matrix end function _MTX:dump() for _,r in ipairs(self) do print(unpack(r)) end end function _MTX:perm() return self:det(1) end function _MTX:det(perm) local det=0 local jt=JT(self.cols) repeat local pi=perm or jt.sign for i,v in ipairs(jt.values) do pi=pi*self[i][v] end det=det+pi until not jt:next() return det end -- test matrix=MTX { { 7, 2, -2, 4}, { 4, 4, 1, 7}, {11, -8, 9, 10}, {10, 5, 12, 13} } matrix:dump(); print("det:",matrix:det(), "permanent:",matrix:perm(),"\n") matrix2=MTX { {-2, 2,-3}, {-1, 1, 3}, { 2, 0,-1} } matrix2:dump(); print("det:",matrix2:det(), "permanent:",matrix2:perm())
Determine if a string has all the same characters
Lua
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
function analyze(s) print(string.format("Examining [%s] which has a length of %d:", s, string.len(s))) if string.len(s) > 1 then local last = string.byte(string.sub(s,1,1)) for i=1,string.len(s) do local c = string.byte(string.sub(s,i,i)) if last ~= c then print(" Not all characters in the string are the same.") print(string.format(" '%s' (0x%x) is different at position %d", string.sub(s,i,i), c, i - 1)) return end end end print(" All characters in the string are the same.") end function main() analyze("") analyze(" ") analyze("2") analyze("333") analyze(".55") analyze("tttTTT") analyze("4444 444k") end main()
Determine if a string has all unique characters
Lua
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as unique ::* process the strings from left-to-right ::* if unique, display a message saying such ::* if not unique, then: ::::* display a message saying such ::::* display what character is duplicated ::::* only the 1st non-unique character need be displayed ::::* display where "both" duplicated characters are in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the duplicated character Use (at least) these five test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 1 which is a single period ('''.''') :::* a string of length 6 which contains: '''abcABC''' :::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX''' :::* a string of length 36 which ''doesn't'' contain the letter "oh": :::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ''' Show all output here on this page.
local find, format = string.find, string.format local function printf(fmt, ...) print(format(fmt,...)) end local pattern = '(.).-%1' -- '(.)' .. '.-' .. '%1' function report_dup_char(subject) local pos1, pos2, char = find(subject, pattern) local prefix = format('"%s" (%d)', subject, #subject) if pos1 then local byte = char:byte() printf("%s: '%s' (0x%02x) duplicates at %d, %d", prefix, char, byte, pos1, pos2) else printf("%s: no duplicates", prefix) end end local show = report_dup_char show('coccyx') show('') show('.') show('abcABC') show('XYZ ZYX') show('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')
Determine if a string is collapsible
Lua from C#
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ''immediately repeated'' character is any character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.} ;Examples: In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated by underscores (above), even though they (those characters) appear elsewhere in the character string. So, after ''collapsing'' the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate ''repeated'' characters and ''collapse'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: string number ++ 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | 5 | --- Harry S Truman | <###### has many repeated blanks +------------------------------------------------------------------------+
function collapse(s) local ns = "" local last = nil for c in s:gmatch"." do if last then if last ~= c then ns = ns .. c end last = c else ns = ns .. c last = c end end return ns end function test(s) print("old: " .. s:len() .. " <<<" .. s .. ">>>") local a = collapse(s) print("new: " .. a:len() .. " <<<" .. a .. ">>>") end function main() test("") test("The better the 4-wheel drive, the further you'll be from help when ya get stuck!") test("headmistressship") test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ") test("..1111111111111111111111111111111111111111111111111111111111111117777888") test("I never give 'em hell, I just tell the truth, and they think it's hell. ") test(" --- Harry S Truman ") end main()
Determine if a string is squeezable
Lua from D
Determine if a character string is ''squeezable''. And if so, squeeze the string (by removing any number of a ''specified'' ''immediately repeated'' character). This task is very similar to the task '''Determine if a character string is collapsible''' except that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''. If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). A specified ''immediately repeated'' character is any specified character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''squeeze'''.} ;Examples: In the following character string with a specified ''immediately repeated'' character of '''e''': The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''e''' is an specified repeated character, indicated by an underscore (above), even though they (the characters) appear elsewhere in the character string. So, after ''squeezing'' the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string, using a specified immediately repeated character '''s''': headmistressship The "squeezed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character and ''squeeze'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the specified repeated character (to be searched for and possibly ''squeezed''): :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: immediately string repeated number character ( | a blank, a minus, a seven, a period) ++ 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-' 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7' 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.' 5 | --- Harry S Truman | (below) <###### has many repeated blanks +------------------------------------------------------------------------+ | | | For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: * a blank * a minus * a lowercase '''r''' Note: there should be seven results shown, one each for the 1st four strings, and three results for the 5th string.
function squeezable(s, rune) print("squeeze: `" .. rune .. "`") print("old: <<<" .. s .. ">>>, length = " .. string.len(s)) local last = nil local le = 0 io.write("new: <<<") for c in s:gmatch"." do if c ~= last or c ~= rune then io.write(c) le = le + 1 end last = c end print(">>>, length = " .. le) print() end function main() squeezable("", ' '); squeezable("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-') squeezable("..1111111111111111111111111111111111111111111111111111111111111117777888", '7') squeezable("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.') local s = " --- Harry S Truman " squeezable(s, ' ') squeezable(s, '-') squeezable(s, 'r') end main()
Determine if two triangles overlap
Lua from C++
Determining if two triangles in the same plane overlap is an important topic in collision detection. ;Task: Determine which of these pairs of triangles overlap in 2D: :::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6) :::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0) :::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6) :::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4) :::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2) :::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer): :::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
function det2D(p1,p2,p3) return p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y) end function checkTriWinding(p1,p2,p3,allowReversed) local detTri = det2D(p1,p2,p3) if detTri < 0.0 then if allowReversed then local t = p3 p3 = p2 p2 = t else error("triangle has wrong winding direction") end end return nil end function boundaryCollideChk(p1,p2,p3,eps) return det2D(p1,p2,p3) < eps end function boundaryDoesntCollideChk(p1,p2,p3,eps) return det2D(p1,p2,p3) <= eps end function triTri2D(t1,t2,eps,allowReversed,onBoundary) eps = eps or 0.0 allowReversed = allowReversed or false onBoundary = onBoundary or true -- triangles must be expressed anti-clockwise checkTriWinding(t1[1], t1[2], t1[3], allowReversed) checkTriWinding(t2[1], t2[2], t2[3], allowReversed) local chkEdge if onBoundary then -- points on the boundary are considered as colliding chkEdge = boundaryCollideChk else -- points on the boundary are not considered as colliding chkEdge = boundaryDoesntCollideChk end -- for edge E of triangle 1 for i=0,2 do local j = (i+1)%3 -- check all points of triangle 2 lay on the external side of the edge E. -- If they do, the triangles do not collide if chkEdge(t1[i+1], t1[j+1], t2[1], eps) and chkEdge(t1[i+1], t1[j+1], t2[2], eps) and chkEdge(t1[i+1], t1[j+1], t2[3], eps) then return false end end -- for edge E of triangle 2 for i=0,2 do local j = (i+1)%3 -- check all points of triangle 1 lay on the external side of the edge E. -- If they do, the triangles do not collide if chkEdge(t2[i+1], t2[j+1], t1[1], eps) and chkEdge(t2[i+1], t2[j+1], t1[2], eps) and chkEdge(t2[i+1], t2[j+1], t1[3], eps) then return false end end -- the triangles collide return true end function formatTri(t) return "Triangle: ("..t[1].x..", "..t[1].y .."), ("..t[2].x..", "..t[2].y .."), ("..t[3].x..", "..t[3].y..")" end function overlap(t1,t2,eps,allowReversed,onBoundary) if triTri2D(t1,t2,eps,allowReversed,onBoundary) then return "overlap\n" else return "do not overlap\n" end end -- Main local t1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}} local t2 = {{x=0,y=0},{x=5,y=0},{x=0,y=6}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2)) t1 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}} t2 = {{x=0,y=0},{x=0,y=5},{x=5,y=0}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2,0.0,true)) t1 = {{x=0,y=0},{x=5,y=0},{x=0,y=5}} t2 = {{x=-10,y=0},{x=-5,y=0},{x=-1,y=6}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2)) t1 = {{x=0,y=0},{x=5,y=0},{x=2.5,y=5}} t2 = {{x=0,y=4},{x=2.5,y=-1},{x=5,y=4}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2)) t1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}} t2 = {{x=2,y=1},{x=3,y=0},{x=3,y=2}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2)) t1 = {{x=0,y=0},{x=1,y=1},{x=0,y=2}} t2 = {{x=2,y=1},{x=3,y=-2},{x=3,y=4}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2)) -- Barely touching t1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}} t2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2,0.0,false,true)) -- Barely touching local t1 = {{x=0,y=0},{x=1,y=0},{x=0,y=1}} local t2 = {{x=1,y=0},{x=2,y=0},{x=1,y=1}} print(formatTri(t1).." and") print(formatTri(t2)) print(overlap(t1,t2,0.0,false,false))
Dice game probabilities
Lua
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
local function simu(ndice1, nsides1, ndice2, nsides2) local function roll(ndice, nsides) local result = 0; for i = 1, ndice do result = result + math.random(nsides) end return result end local wins, coms = 0, 1000000 for i = 1, coms do local roll1 = roll(ndice1, nsides1) local roll2 = roll(ndice2, nsides2) if (roll1 > roll2) then wins = wins + 1 end end print("simulated: p1 = "..ndice1.."d"..nsides1..", p2 = "..ndice2.."d"..nsides2..", prob = "..wins.." / "..coms.." = "..(wins/coms)) end simu(9, 4, 6, 6) simu(5, 10, 6, 7)
Digital root
Lua
The digital root, X, of a number, n, is calculated: : find X as the sum of the digits of n : find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: :627615 has additive persistence 2 and digital root of 9; :39390 has additive persistence 2 and digital root of 6; :588225 has additive persistence 2 and digital root of 3; :393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. ;See: * [[Casting out nines]] for this wiki's use of this procedure. * [[Digital root/Multiplicative digital root]] * [[Sum digits of an integer]] * Digital root sequence on OEIS * Additive persistence sequence on OEIS * [[Iterated digits squaring]]
function digital_root(n, base) p = 0 while n > 9.5 do n = sum_digits(n, base) p = p + 1 end return n, p end print(digital_root(627615, 10)) print(digital_root(39390, 10)) print(digital_root(588225, 10)) print(digital_root(393900588225, 10))
Disarium numbers
Lua
A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. ;E.G. '''135''' is a '''Disarium number''': 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of '''Disarium numbers'''. ;Task * Find and display the first 18 '''Disarium numbers'''. ;Stretch * Find and display all 20 '''Disarium numbers'''. ;See also ;* Geeks for Geeks - Disarium numbers ;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) ;* Related task: Narcissistic decimal number ;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
function isDisarium (x) local str, sum, digit = tostring(x), 0 for pos = 1, #str do digit = tonumber(str:sub(pos, pos)) sum = sum + (digit ^ pos) end return sum == x end local count, n = 0, 0 while count < 19 do if isDisarium(n) then count = count + 1 io.write(n .. " ") end n = n + 1 end
Display a linear combination
Lua from C#
Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots). Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is: :\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots where \alpha^{i_k}\neq 0 The output must comply to the following rules: * don't show null terms, unless the whole combination is null. ::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong. * don't show scalars when they are equal to one or minus one. ::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong. * don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. ::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
function t2s(t) local s = "[" for i,v in pairs(t) do if i > 1 then s = s .. ", " .. v else s = s .. v end end return s .. "]" end function linearCombo(c) local sb = "" for i,n in pairs(c) do local skip = false if n < 0 then if sb:len() == 0 then sb = sb .. "-" else sb = sb .. " - " end elseif n > 0 then if sb:len() ~= 0 then sb = sb .. " + " end else skip = true end if not skip then local av = math.abs(n) if av ~= 1 then sb = sb .. av .. "*" end sb = sb .. "e(" .. i .. ")" end end if sb:len() == 0 then sb = "0" end return sb end function main() local combos = { { 1, 2, 3}, { 0, 1, 2, 3 }, { 1, 0, 3, 4 }, { 1, 2, 0 }, { 0, 0, 0 }, { 0 }, { 1, 1, 1 }, { -1, -1, -1 }, { -1, -2, 0, -3 }, { -1 } } for i,c in pairs(combos) do local arr = t2s(c) print(string.format("%15s -> %s", arr, linearCombo(c))) end end main()
Diversity prediction theorem
Lua from C++
The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies. Scott E. Page introduced the diversity prediction theorem: : ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. Therefore, when the diversity in a group is large, the error of the crowd is small. ;Definitions: ::* Average Individual Error: Average of the individual squared errors ::* Collective Error: Squared error of the collective prediction ::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction ::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then :::::: Collective Error = Average Individual Error - Prediction Diversity ;Task: For a given true value and a number of number of estimates (from a crowd), show (here on this page): :::* the true value and the crowd estimates :::* the average error :::* the crowd error :::* the prediction diversity Use (at least) these two examples: :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51''' :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42''' ;Also see: :* Wikipedia entry: Wisdom of the crowd :* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
function square(x) return x * x end function mean(a) local s = 0 local c = 0 for i,v in pairs(a) do s = s + v c = c + 1 end return s / c end function averageSquareDiff(a, predictions) local results = {} for i,x in pairs(predictions) do table.insert(results, square(x - a)) end return mean(results) end function diversityTheorem(truth, predictions) local average = mean(predictions) print("average-error: " .. averageSquareDiff(truth, predictions)) print("crowd-error: " .. square(truth - average)) print("diversity: " .. averageSquareDiff(average, predictions)) end function main() diversityTheorem(49, {48, 47, 51}) diversityTheorem(49, {48, 47, 51, 42}) end main()
Dot product
Lua
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
function dotprod(a, b) local ret = 0 for i = 1, #a do ret = ret + a[i] * b[i] end return ret end print(dotprod({1, 3, -5}, {4, -2, 1}))
Draw a clock
Lua
Draw a clock. More specific: # Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. # The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. # A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. # A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. ;Key points * animate simple object * timed event * polling system resources * code clarity
==={{libheader|LÖVE}}=== Several nice clocks in the [http://love2d.org/forums/viewtopic.php?f=5&t=77346 LÖVE-forum]
Draw a rotating cube
Lua
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. ;Related tasks * Draw a cuboid * write language name in 3D ASCII
local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt 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),floor(y) if x>0 and y>0 and x<=self.w and y<=self.h then self.pixels[y][x] = value or "#" end end, line = function(self, x1, y1, x2, y2, c) x1,y1,x2,y2 = floor(x1),floor(y1),floor(x2),floor(y2) local dx, sx = abs(x2-x1), x1<x2 and 1 or -1 local dy, sy = abs(y2-y1), y1<y2 and 1 or -1 local err = floor((dx>dy and dx or -dy)/2) while(true) do self:set(x1, y1, c) if (x1==x2 and y1==y2) then break end if (err > -dx) then err, x1 = err-dy, x1+sx if (x1==x2 and y1==y2) then self:set(x1, y1, c) break end end if (err < dy) then err, y1 = err+dx, y1+sy end end end, render = function(self) for y=1,self.h do print(table.concat(self.pixels[y])) end end, } screen = { clear = function() os.execute("cls") -- or? os.execute("clear"), or? io.write("\027[2J\027[H"), or etc? end, } local camera = { fl = 2.5 } local L = 0.5 local cube = { verts = { {L,L,L}, {L,-L,L}, {-L,-L,L}, {-L,L,L}, {L,L,-L}, {L,-L,-L}, {-L,-L,-L}, {-L,L,-L} }, edges = { {1,2}, {2,3}, {3,4}, {4,1}, {5,6}, {6,7}, {7,8}, {8,5}, {1,5}, {2,6}, {3,7}, {4,8} }, rotate = function(self, rx, ry) local cx,sx = cos(rx),sin(rx) local cy,sy = cos(ry),sin(ry) for i,v in ipairs(self.verts) do local x,y,z = v[1],v[2],v[3] v[1], v[2], v[3] = x*cx-z*sx, y*cy-x*sx*sy-z*cx*sy, x*sx*cy+y*sy+z*cx*cy end end, } local renderer = { render = function(self, shape, camera, bitmap) local fl = camera.fl local ox, oy = bitmap.w/2, bitmap.h/2 local mx, my = bitmap.w/2, bitmap.h/2 local rpverts = {} for i,v in ipairs(shape.verts) do local x,y,z = v[1],v[2],v[3] local px = ox + mx * (fl*x)/(fl-z) local py = oy + my * (fl*y)/(fl-z) rpverts[i] = { px,py } end for i,e in ipairs(shape.edges) do local v1, v2 = rpverts[e[1]], rpverts[e[2]] bitmap:line( v1[1], v1[2], v2[1], v2[2], "██" ) end end } -- bitmap:init(40,40) cube:rotate(pi/4, atan(sqrt(2))) for i=1,60 do cube:rotate(pi/60,0) bitmap:clear("··") renderer:render(cube, camera, bitmap) screen:clear() bitmap:render() end
Draw a sphere
Lua 5.1.4
{{requires|Graphics}} ;Task: Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. ;Related tasks: * draw a cuboid * draw a rotating cube * write language name in 3D ASCII * draw a Deathstar
require ("math") shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'} function normalize (vec) len = math.sqrt(vec[1]^2 + vec[2]^2 + vec[3]^2) return {vec[1]/len, vec[2]/len, vec[3]/len} end light = normalize{30, 30, -50} function dot (vec1, vec2) d = vec1[1]*vec2[1] + vec1[2]*vec2[2] + vec1[3]*vec2[3] return d < 0 and -d or 0 end function draw_sphere (radius, k, ambient) for i = math.floor(-radius),-math.floor(-radius) do x = i + .5 local line = '' for j = math.floor(-2*radius),-math.floor(-2*radius) do y = j / 2 + .5 if x^2 + y^2 <= radius^2 then vec = normalize{x, y, math.sqrt(radius^2 - x^2 - y^2)} b = dot(light,vec) ^ k + ambient intensity = math.floor ((1 - b) * #shades) line = line .. (shades[intensity] or shades[1]) else line = line .. ' ' end end print (line) end end draw_sphere (20, 4, 0.1) draw_sphere (10, 2, 0.4)
Dutch national flag problem
Lua
The Dutch national flag is composed of three coloured bands in the order: ::* red (top) ::* then white, and ::* lastly blue (at the bottom). The problem posed by Edsger Dijkstra is: :Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... ;Task # Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''. # Sort the balls in a way idiomatic to your language. # Check the sorted balls ''are'' in the order of the Dutch national flag. ;C.f.: * Dutch national flag problem * Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
-- "1. Generate a randomized order of balls.." math.randomseed(os.time()) N, balls, colors = 10, {}, { "red", "white", "blue" } for i = 1, N do balls[i] = colors[math.random(#colors)] end -- "..ensuring that they are not in the order of the Dutch national flag." order = { red=1, white=2, blue=3 } function issorted(t) for i = 2, #t do if order[t[i]] < order[t[i-1]] then return false end end return true end local function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end end while issorted(balls) do shuffle(balls) end print("RANDOM: "..table.concat(balls,",")) -- "2. Sort the balls in a way idiomatic to your language." table.sort(balls, function(a, b) return order[a] < order[b] end) -- "3. Check the sorted balls are in the order of the Dutch national flag." print("SORTED: "..table.concat(balls,",")) print(issorted(balls) and "Properly sorted." or "IMPROPERLY SORTED!!")
Eban numbers
Lua from lang
Definition: An '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English. Or more literally, spelled numbers that contain the letter '''e''' are banned. The American version of spelling numbers will be used here (as opposed to the British). '''2,000,000,000''' is two billion, ''not'' two milliard. Only numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task. This will allow optimizations to be used. ;Task: :::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count :::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count :::* show a count of all eban numbers up and including '''10,000''' :::* show a count of all eban numbers up and including '''100,000''' :::* show a count of all eban numbers up and including '''1,000,000''' :::* show a count of all eban numbers up and including '''10,000,000''' :::* show all output here. ;See also: :* The MathWorld entry: eban numbers. :* The OEIS entry: A6933, eban numbers. :* [[Number names]].
function makeInterval(s,e,p) return {start=s, end_=e, print_=p} end function main() local intervals = { makeInterval( 2, 1000, true), makeInterval(1000, 4000, true), makeInterval( 2, 10000, false), makeInterval( 2, 1000000, false), makeInterval( 2, 10000000, false), makeInterval( 2, 100000000, false), makeInterval( 2, 1000000000, false) } for _,intv in pairs(intervals) do if intv.start == 2 then print("eban numbers up to and including " .. intv.end_ .. ":") else print("eban numbers between " .. intv.start .. " and " .. intv.end_ .. " (inclusive)") end local count = 0 for i=intv.start,intv.end_,2 do local b = math.floor(i / 1000000000) local r = i % 1000000000 local m = math.floor(r / 1000000) r = i % 1000000 local t = math.floor(r / 1000) r = r % 1000 if m >= 30 and m <= 66 then m = m % 10 end if t >= 30 and t <= 66 then t = t % 10 end if r >= 30 and r <= 66 then r = r % 10 end if b == 0 or b == 2 or b == 4 or b == 6 then if m == 0 or m == 2 or m == 4 or m == 6 then if t == 0 or t == 2 or t == 4 or t == 6 then if r == 0 or r == 2 or r == 4 or r == 6 then if intv.print_ then io.write(i .. " ") end count = count + 1 end end end end end if intv.print_ then print() end print("count = " .. count) print() end end main()
Egyptian division
Lua from Python
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
function egyptian_divmod(dividend,divisor) local pwrs, dbls = {1}, {divisor} while dbls[#dbls] <= dividend do table.insert(pwrs, pwrs[#pwrs] * 2) table.insert(dbls, pwrs[#pwrs] * divisor) end local ans, accum = 0, 0 for i=#pwrs-1,1,-1 do if accum + dbls[i] <= dividend then accum = accum + dbls[i] ans = ans + pwrs[i] end end return ans, math.abs(accum - dividend) end local i, j = 580, 34 local d, m = egyptian_divmod(i, j) print(i.." divided by "..j.." using the Egyptian method is "..d.." remainder "..m)
Elementary cellular automaton
Lua
An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. ;Task: Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of [[one-dimensional cellular automata]]. ;See also * Cellular automata (natureofcode.com)
local CA = { state = "..............................#..............................", bstr = { [0]="...", "..#", ".#.", ".##", "#..", "#.#", "##.", "###" }, new = function(self, rule) local inst = setmetatable({rule=rule}, self) for b = 0,7 do inst[inst.bstr[b]] = rule%2==0 and "." or "#" rule = math.floor(rule/2) end return inst end, evolve = function(self) local n, state, newstate = #self.state, self.state, "" for i = 1,n do local nbhd = state:sub((i+n-2)%n+1,(i+n-2)%n+1) .. state:sub(i,i) .. state:sub(i%n+1,i%n+1) newstate = newstate .. self[nbhd] end self.state = newstate end, } CA.__index = CA ca = { CA:new(18), CA:new(30), CA:new(73), CA:new(129) } for i = 1, 63 do print(string.format("%-66s%-66s%-66s%-61s", ca[1].state, ca[2].state, ca[3].state, ca[4].state)) for j = 1, 4 do ca[j]:evolve() end end
Empty directory
Lua
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.
function scandir(directory) local i, t, popen = 0, {}, io.popen local pfile = popen('ls -a "'..directory..'"') for filename in pfile:lines() do if filename ~= '.' and filename ~= '..' then i = i + 1 t[i] = filename end end pfile:close() return t end function isemptydir(directory) return #scandir(directory) == 0 end
Empty string
Lua
Languages may have features for dealing specifically with empty strings (those containing no characters). ;Task: ::* Demonstrate how to assign an empty string to a variable. ::* Demonstrate how to check that a string is empty. ::* Demonstrate how to check that a string is not empty.
-- create an empty string 3 different ways str = "" str = '' str = [[]] -- test for empty string if str == "" then print "The string is empty" end -- test for nonempty string if str ~= "" then print "The string is not empty" end -- several different ways to check the string's length if string.len(str) == 0 then print "The library function says the string is empty." end if str:len() == 0 then print "The method call says the string is empty." end if #str == 0 then print "The unary operator says the string is empty." end
Entropy/Narcissist
Lua
Write a computer program that computes and shows its own [[entropy]]. ;Related Tasks: :* [[Fibonacci_word]] :* [[Entropy]]
function getFile (filename) local inFile = io.open(filename, "r") local fileContent = inFile:read("*all") inFile:close() return fileContent end function log2 (x) return math.log(x) / math.log(2) end function entropy (X) local N, count, sum, i = X:len(), {}, 0 for char = 1, N do i = X:sub(char, char) if count[i] then count[i] = count[i] + 1 else count[i] = 1 end end for n_i, count_i in pairs(count) do sum = sum + count_i / N * log2(count_i / N) end return -sum end print(entropy(getFile(arg[0])))
Equilibrium index
Lua
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence A: ::::: A_0 = -7 ::::: A_1 = 1 ::::: A_2 = 5 ::::: A_3 = 2 ::::: A_4 = -4 ::::: A_5 = 3 ::::: A_6 = 0 3 is an equilibrium index, because: ::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6 6 is also an equilibrium index, because: ::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. ;Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
function array_sum(t) assert(type(t) == "table", "t must be a table!") local sum = 0 for i=1, #t do sum = sum + t[i] end return sum end function equilibrium_index(t) assert(type(t) == "table", "t must be a table!") local left, right, ret = 0, array_sum(t), -1 for i,j in pairs(t) do right = right - j if left == right then ret = i break end left = left + j end return ret end print(equilibrium_index({-7, 1, 5, 2, -4, 3, 0}))
Esthetic numbers
Lua from C++
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1. ;E.G. :* '''12''' is an esthetic number. One and two differ by 1. :* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour. :* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. ;Task :* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. :* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) :* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''. :* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''. ;Related task: * numbers with equal rises and falls ;See also: :;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 :;*Numbers Aplenty - Esthetic numbers :;*Geeks for Geeks - Stepping numbers
function to(n, b) local BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" if n == 0 then return "0" end local ss = "" while n > 0 do local idx = (n % b) + 1 n = math.floor(n / b) ss = ss .. BASE:sub(idx, idx) end return string.reverse(ss) end function isEsthetic(n, b) function uabs(a, b) if a < b then return b - a end return a - b end if n == 0 then return false end local i = n % b n = math.floor(n / b) while n > 0 do local j = n % b if uabs(i, j) ~= 1 then return false end n = math.floor(n / b) i = j end return true end function listEsths(n, n2, m, m2, perLine, all) local esths = {} function dfs(n, m, i) if i >= n and i <= m then table.insert(esths, i) end if i == 0 or i > m then return end local d = i % 10 local i1 = 10 * i + d - 1 local i2 = i1 + 2 if d == 0 then dfs(n, m, i2) elseif d == 9 then dfs(n, m, i1) else dfs(n, m, i1) dfs(n, m, i2) end end for i=0,9 do dfs(n2, m2, i) end local le = #esths print(string.format("Base 10: %s esthetic numbers between %s and %s:", le, math.floor(n), math.floor(m))) if all then for c,esth in pairs(esths) do io.write(esth.." ") if c % perLine == 0 then print() end end print() else for i=1,perLine do io.write(esths[i] .. " ") end print("\n............") for i = le - perLine + 1, le do io.write(esths[i] .. " ") end print() end print() end for b=2,16 do print(string.format("Base %d: %dth to %dth esthetic numbers:", b, 4 * b, 6 * b)) local n = 1 local c = 0 while c < 6 * b do if isEsthetic(n, b) then c = c + 1 if c >= 4 * b then io.write(to(n, b).." ") end end n = n + 1 end print() end print() -- the following all use the obvious range limitations for the numbers in question listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true) listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false) listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false) listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false)
Euler's identity
Lua
{{Wikipedia|Euler's_identity}} In mathematics, ''Euler's identity'' is the equality: ei\pi + 1 = 0 where e is Euler's number, the base of natural logarithms, ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and \pi is pi, the ratio of the circumference of a circle to its diameter. Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants: The number 0. The number 1. The number \pi (\pi = 3.14159+), The number e (e = 2.71828+), which occurs widely in mathematical analysis. The number ''i'', the imaginary unit of the complex numbers. ;Task Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. If that is the case, or there is some other limitation, show that ei\pi + 1 is ''approximately'' equal to zero and show the amount of error in the calculation. If your language is capable of symbolic calculations, show that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.
local c = { new = function(s,r,i) s.__index=s return setmetatable({r=r, i=i}, s) end, add = function(s,o) return s:new(s.r+o.r, s.i+o.i) end, exp = function(s) local e=math.exp(s.r) return s:new(e*math.cos(s.i), e*math.sin(s.i)) end, mul = function(s,o) return s:new(s.r*o.r+s.i*o.i, s.r*o.i+s.i*o.r) end } local i = c:new(0, 1) local pi = c:new(math.pi, 0) local one = c:new(1, 0) local zero = i:mul(pi):exp():add(one) print(string.format("e^(i*pi)+1 is approximately zero: %.18g%+.18gi", zero.r, zero.i))
Euler's sum of powers conjecture
Lua
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
-- Fast table search (only works if table values are in order) function binarySearch (t, n) local start, stop, mid = 1, #t while start < stop do mid = math.floor((start + stop) / 2) if n == t[mid] then return mid elseif n < t[mid] then stop = mid - 1 else start = mid + 1 end end return nil end -- Test Euler's sum of powers conjecture function euler (limit) local pow5, sum = {} for i = 1, limit do pow5[i] = i^5 end for x0 = 1, limit do for x1 = 1, x0 do for x2 = 1, x1 do for x3 = 1, x2 do sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3] if binarySearch(pow5, sum) then print(x0 .. "^5 + " .. x1 .. "^5 + " .. x2 .. "^5 + " .. x3 .. "^5 = " .. sum^(1/5) .. "^5") return true end end end end end return false end -- Main procedure if euler(249) then print("Time taken: " .. os.clock() .. " seconds") else print("Looks like he was right after all...") end
Even or odd
Lua
Test whether an integer is even or odd. There is more than one way to solve this task: * Use the even and odd predicates, if the language provides them. * Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd. * Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd. * Use modular congruences: ** ''i'' 0 (mod 2) iff ''i'' is even. ** ''i'' 1 (mod 2) iff ''i'' is odd.
-- test for even number if n % 2 == 0 then print "The number is even" end -- test for odd number if not (n % 2 == 0) then print "The number is odd" end
Evolutionary algorithm
Lua 5.1+
Starting with: * The target string: "METHINKS IT IS LIKE A WEASEL". * An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). * A fitness function that computes the 'closeness' of its argument to the target string. * A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. :* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. :* repeat until the parent converges, (hopefully), to the target. ;See also: * Wikipedia entry: Weasel algorithm. * Wikipedia entry: Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, '''changing randomly any characters which don't already match the target''': ''NOTE:'' this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
local target = "METHINKS IT IS LIKE A WEASEL" local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " local c, p = 100, 0.06 local function fitness(s) local score = #target for i = 1,#target do if s:sub(i,i) == target:sub(i,i) then score = score - 1 end end return score end local function mutate(s, rate) local result, idx = "" for i = 1,#s do if math.random() < rate then idx = math.random(#alphabet) result = result .. alphabet:sub(idx,idx) else result = result .. s:sub(i,i) end end return result, fitness(result) end local function randomString(len) local result, idx = "" for i = 1,len do idx = math.random(#alphabet) result = result .. alphabet:sub(idx,idx) end return result end local function printStep(step, s, fit) print(string.format("%04d: ", step) .. s .. " [" .. fit .."]") end math.randomseed(os.time()) local parent = randomString(#target) printStep(0, parent, fitness(parent)) local step = 0 while parent ~= target do local bestFitness, bestChild, child, fitness = #target + 1 for i = 1,c do child, fitness = mutate(parent, p) if fitness < bestFitness then bestFitness, bestChild = fitness, child end end parent, step = bestChild, step + 1 printStep(step, parent, bestFitness) end
Executable library
Lua
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. '''Task detail''' * Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number. * The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task: :: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 :: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. * Create a second executable to calculate the following: ** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000. * Explain any extra setup/run steps needed to complete the task. '''Notes:''' * It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment. * Interpreters are present in the runtime environment.
#!/usr/bin/env luajit bit32=bit32 or bit local lib={ hailstone=function(n) local seq={n} while n>1 do n=bit32.band(n,1)==1 and 3*n+1 or n/2 seq[#seq+1]=n end return seq end } if arg[0] and arg[0]:match("hailstone.lua") then local function printf(fmt, ...) io.write(string.format(fmt, ...)) end local seq=lib.hailstone(27) printf("27 has %d numbers in sequence:\n",#seq) for _,i in ipairs(seq) do printf("%d ", i) end printf("\n") else return lib end
Execute Brain****
Lua
Brainf***}} RCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: {| class="wikitable" !Command !Description |- | style="text-align:center"| > || Move the pointer to the right |- | style="text-align:center"| < || Move the pointer to the left |- | style="text-align:center"| + || Increment the memory cell under the pointer |- | style="text-align:center"| - || Decrement the memory cell under the pointer |- | style="text-align:center"| . || Output the character signified by the cell at the pointer |- | style="text-align:center"| , || Input a character and store it in the cell at the pointer |- | style="text-align:center"| [ || Jump past the matching ] if the cell under the pointer is 0 |- | style="text-align:center"| ] || Jump back to the matching [ if the cell under the pointer is nonzero |} Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
local funs = { ['>'] = 'ptr = ptr + 1; ', ['<'] = 'ptr = ptr - 1; ', ['+'] = 'mem[ptr] = mem[ptr] + 1; ', ['-'] = 'mem[ptr] = mem[ptr] - 1; ', ['['] = 'while mem[ptr] ~= 0 do ', [']'] = 'end; ', ['.'] = 'io.write(string.char(mem[ptr])); ', [','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ', } local prog = [[ local mem = setmetatable({}, { __index = function() return 0 end}) local ptr = 1 ]] local source = io.read('*all') for p = 1, #source do local snippet = funs[source:sub(p,p)] if snippet then prog = prog .. snippet end end load(prog)()
Execute Computer/Zero
Lua
Computer/zero Assembly}} ;Task: Create a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there. :* The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation. :* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. ;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.
vmz = { pc = 0, acc = 0, mem = { [0]=0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0 }, b2oa = function(byte) return math.floor(byte / 32), byte % 32 end, boot = function(self) self.pc, self.acc = 0, 0 for pc=0,31 do self.mem[pc]=0 end return self end, load = function(self, bytes) for pc = 0, 31 do self.mem[pc]=bytes[pc] or 0 end return self end, clam = function(n) if n<0 then n=n+256 elseif n>255 then n=n-256 end return n end, opfn = {[0]= function(self,addr) self.pc=self.pc+1 return true end, -- NOP function(self,addr) self.acc=self.mem[addr] self.pc=self.pc+1 return true end, -- LDA function(self,addr) self.mem[addr]=self.acc self.pc=self.pc+1 return true end, -- STA function(self,addr) self.acc=self.clam(self.acc+self.mem[addr]) self.pc=self.pc+1 return true end, -- ADD function(self,addr) self.acc=self.clam(self.acc-self.mem[addr]) self.pc=self.pc+1 return true end, -- SUB function(self,addr) if (self.acc==0) then self.pc=addr else self.pc=self.pc+1 end return true end, -- BRZ function(self,addr) self.pc=addr return true end, -- JMP function(self,addr) self.pc=self.pc+1 return false end, -- STP }, step = function(self) local oper, addr = self.b2oa(self.mem[self.pc]) return self.opfn[oper](self,addr) end, exec = function(self) while self.pc < 32 and self:step() do end return self end, } -- object code derived from js sim code print("2 + 2 = " .. vmz:boot():load({[0]=35,100,224,2,2}):exec().acc) print("7 x 8 = " .. vmz:boot():load({[0]=44,106,76,43,141,75,168,192,44,224,8,7,0,1}):exec().acc)
Execute HQ9+
Lua
Implement a ''' [[HQ9+]] ''' interpreter or compiler.
function runCode( code ) local acc, lc = 0 for i = 1, #code do lc = code:sub( i, i ):upper() if lc == "Q" then print( lc ) elseif lc == "H" then print( "Hello, World!" ) elseif lc == "+" then acc = acc + 1 elseif lc == "9" then for j = 99, 1, -1 do if j > 1 then print( string.format( "%d bottles of beer on the wall\n%d bottles of beer\nTake one down, pass it around\n%d bottles of beer on the wall\n", j, j, j - 1 ) ) else print( "1 bottle of beer on the wall\n1 bottle of beer\nTake one down and pass it around\nno more bottles of beer on the wall\n\n".. "No more bottles of beer on the wall\nNo more bottles of beer\n".. "Go to the store and buy some more\n99 bottles of beer on the wall.\n" ) end end end end end
Exponentiation order
Lua
This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents. (Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.) ;Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification): ::::* 5**3**2 ::::* (5**3)**2 ::::* 5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. ;See also: * MathWorld entry: exponentiation ;Related tasks: * exponentiation operator * arbitrary-precision integers (included) * [[Exponentiation with infix operators in (or operating on) the base]]
print("5^3^2 = " .. 5^3^2) print("(5^3)^2 = " .. (5^3)^2) print("5^(3^2) = " .. 5^(3^2))
Exponentiation with infix operators in (or operating on) the base
Lua
(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation (raising numbers to some power by the language's exponentiation operator, if the computer programming language has one). Other programming languages may make use of the '''POW''' or some other BIF ('''B'''uilt-'''I'''n '''F'''function), or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an ''infix operator'' operating in (or operating on) the base. ;Example: A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). ;Task: :* compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred. :* Raise the following numbers (integer or real): :::* -5 and :::* +5 :* to the following powers: :::* 2nd and :::* 3rd :* using the following expressions (if applicable in your language): :::* -x**p :::* -(x)**p :::* (-x)**p :::* -(x**p) :* Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. ;Related tasks: * [[Exponentiation order]] * [[Exponentiation operator]] * [[Arbitrary-precision integers (included)]] * [[Parsing/RPN to infix conversion]] * [[Operator precedence]] ;References: * Wikipedia: Order of operations in Programming languages
mathtype = math.type or type -- polyfill <5.3 function test(xs, ps) for _,x in ipairs(xs) do for _,p in ipairs(ps) do print(string.format("%2.f %7s %2.f %7s %4.f %4.f %4.f %4.f", x, mathtype(x), p, mathtype(p), -x^p, -(x)^p, (-x)^p, -(x^p))) end end end print(" x type(x) p type(p) -x^p -(x)^p (-x)^p -(x^p)") print("-- ------- -- ------- ------ ------ ------ ------") test( {-5.,5.}, {2.,3.} ) -- "float" (or "number" if <5.3) if math.type then -- if >=5.3 test( {-5,5}, {2,3} ) -- "integer" end
Extend your language
Lua
{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
-- Extend your language, in Lua, 6/17/2020 db -- not to be taken seriously, ridiculous, impractical, esoteric, obscure, arcane ... but it works ------------------- -- IMPLEMENTATION: ------------------- function if2(cond1, cond2) return function(code) code = code:gsub("then2", "[3]=load[[") code = code:gsub("else1", "]],[2]=load[[") code = code:gsub("else2", "]],[1]=load[[") code = code:gsub("neither", "]],[0]=load[[") code = "return {" .. code .. "]]}" local block, err = load(code) if (err) then error("syntax error in if2 statement: "..err) end local tab = block() tab[(cond1 and 2 or 0) + (cond2 and 1 or 0)]() end end ---------- -- TESTS: ---------- for i = 1, 2 do for j = 1, 2 do print("i="..i.." j="..j) if2 ( i==1, j==1 )[[ then2 print("both conditions are true") else1 print("first is true, second is false") else2 print("first is false, second is true") neither print("both conditions are false") ]] end end
Extreme floating point values
Lua
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. ;See also: * What Every Computer Scientist Should Know About Floating-Point Arithmetic ;Related tasks: * [[Infinity]] * [[Detect division by zero]] * [[Literals/Floating point]]
local inf=math.huge local minusInf=-math.huge local NaN=0/0 local negativeZeroSorta=-1E-240
FASTA format
Lua
In FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. ;Task: Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED
local file = io.open("input.txt","r") local data = file:read("*a") file:close() local output = {} local key = nil -- iterate through lines for line in data:gmatch("(.-)\r?\n") do if line:match("%s") then error("line contained space") elseif line:sub(1,1) == ">" then key = line:sub(2) -- if key already exists, append to the previous input output[key] = output[key] or "" elseif key ~= nil then output[key] = output[key] .. line end end -- print result for k,v in pairs(output) do print(k..": "..v) end
Faces from a mesh
Lua
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 * A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 * B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the '''perimeter format''' as it traces around the perimeter. ;A second format: A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. * A single edge is described by the vertex numbers at its two ends, always in ascending order. * All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the '''edge format'''. ;Task: '''1.''' Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) '''2.''' Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
-- support function T(t) return setmetatable(t, {__index=table}) end table.eql = function(t,u) if #t~=#u then return false end for i=1,#t do if t[i]~=u[i] then return false end end return true end table.rol = function(t,n) local s=T{} for i=1,#t do s[i]=t[(i+n-1)%#t+1] end return s end table.rev = function(t) local s=T{} for i=1,#t do s[#t-i+1]=t[i] end return s end -- 1 function pfeq(pf1, pf2) if #pf1 ~= #pf2 then return false end -- easy case for w = 0,1 do -- exhaustive cases local pfw = pf1 -- w:winding if w==1 then pfw=pfw:rev() end for r = 0,#pfw do local pfr = pfw -- r:rotate if r>0 then pfr=pfr:rol(r) end if pf2:eql(pfr) then return true end end end return false end Q = T{8, 1, 3} R = T{1, 3, 8} U = T{18, 8, 14, 10, 12, 17, 19} V = T{8, 14, 10, 12, 17, 19, 18} print("pfeq(Q,R): ", pfeq(Q, R)) print("pfeq(U,V): ", pfeq(U, V)) -- 2 function ef2pf(ef) local pf, hse = T{}, T{} -- hse:hash of sorted edges for i,e in ipairs(ef) do table.sort(e) hse[e]=e end local function nexte(e) if not e then return ef[1] end for k,v in pairs(hse) do if e[2]==v[1] then return v end if e[2]==v[2] then v[1],v[2]=v[2],v[1] return v end end end local e = nexte() while e do pf[#pf+1] = e[1] hse[e] = nil e = nexte(e) end if #pf ~= #ef then pf=T{"failed to convert edge format to perimeter format"} end return pf end E = {{1, 11}, {7, 11}, {1, 7}} F = {{11, 23}, {1, 17}, {17, 23}, {1, 11}} G = {{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}} H = {{1, 3}, {9, 11}, {3, 11}, {1, 11}} print("ef2pf(E): ", ef2pf(E):concat(",")) print("ef2pf(F): ", ef2pf(F):concat(",")) print("ef2pf(G): ", ef2pf(G):concat(",")) print("ef2pf(H): ", ef2pf(H):concat(","))
Fairshare between two and more
Lua from D
The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: :''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"'' ;Sharing fairly between two or more: Use this method: :''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.'' ;Task Counting from zero; using a function/method/routine to express an integer count in base '''b''', sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people. Show the first 25 terms of the fairshare sequence: :* For two people: :* For three people :* For five people :* For eleven people ;Related tasks: :* [[Non-decimal radices/Convert]] :* [[Thue-Morse]] ;See also: :* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
function turn(base, n) local sum = 0 while n ~= 0 do local re = n % base n = math.floor(n / base) sum = sum + re end return sum % base end function fairShare(base, count) io.write(string.format("Base %2d:", base)) for i=1,count do local t = turn(base, i - 1) io.write(string.format(" %2d", t)) end print() end function turnCount(base, count) local cnt = {} for i=1,base do cnt[i - 1] = 0 end for i=1,count do local t = turn(base, i - 1) if cnt[t] ~= nil then cnt[t] = cnt[t] + 1 else cnt[t] = 1 end end local minTurn = count local maxTurn = -count local portion = 0 for _,num in pairs(cnt) do if num > 0 then portion = portion + 1 end if num < minTurn then minTurn = num end if maxTurn < num then maxTurn = num end end io.write(string.format(" With %d people: ", base)) if minTurn == 0 then print(string.format("Only %d have a turn", portion)) elseif minTurn == maxTurn then print(minTurn) else print(minTurn .. " or " .. maxTurn) end end function main() fairShare(2, 25) fairShare(3, 25) fairShare(5, 25) fairShare(11, 25) print("How many times does each get a turn in 50000 iterations?") turnCount(191, 50000) turnCount(1377, 50000) turnCount(49999, 50000) turnCount(50000, 50000) turnCount(50001, 50000) end main()
Farey sequence
Lua
The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size. The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. Each Farey sequence: :::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1} :::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}. The Farey sequences of orders '''1''' to '''5''' are: :::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1} : :::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1} : :::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1} : :::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1} : :::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1} ;Task * Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive). * Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds. * Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). The length (the number of fractions) of a Farey sequence asymptotically approaches: ::::::::::: 3 x n2 / \pi2 ;See also: * OEIS sequence A006842 numerators of Farey series of order 1, 2, *** * OEIS sequence A006843 denominators of Farey series of order 1, 2, *** * OEIS sequence A005728 number of fractions in Farey series of order n * MathWorld entry Farey sequence * Wikipedia entry Farey sequence
-- Return farey sequence of order n function farey (n) local a, b, c, d, k = 0, 1, 1, n local farTab = {{a, b}} while c <= n do k = math.floor((n + b) / d) a, b, c, d = c, d, k * c - a, k * d - b table.insert(farTab, {a, b}) end return farTab end -- Main procedure for i = 1, 11 do io.write(i .. ": ") for _, frac in pairs(farey(i)) do io.write(frac[1] .. "/" .. frac[2] .. " ") end print() end for i = 100, 1000, 100 do print(i .. ": " .. #farey(i) .. " items") end
Fast Fourier transform
Lua
Calculate the FFT (Fast Fourier Transform) of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
-- operations on complex number complex = {__mt={} } function complex.new (r, i) local new={r=r, i=i or 0} setmetatable(new,complex.__mt) return new end function complex.__mt.__add (c1, c2) return complex.new(c1.r + c2.r, c1.i + c2.i) end function complex.__mt.__sub (c1, c2) return complex.new(c1.r - c2.r, c1.i - c2.i) end function complex.__mt.__mul (c1, c2) return complex.new(c1.r*c2.r - c1.i*c2.i, c1.r*c2.i + c1.i*c2.r) end function complex.expi (i) return complex.new(math.cos(i),math.sin(i)) end function complex.__mt.__tostring(c) return "("..c.r..","..c.i..")" end -- Cooley–Tukey FFT (in-place, divide-and-conquer) -- Higher memory requirements and redundancy although more intuitive function fft(vect) local n=#vect if n<=1 then return vect end -- divide local odd,even={},{} for i=1,n,2 do odd[#odd+1]=vect[i] even[#even+1]=vect[i+1] end -- conquer fft(even); fft(odd); -- combine for k=1,n/2 do local t=even[k] * complex.expi(-2*math.pi*(k-1)/n) vect[k] = odd[k] + t; vect[k+n/2] = odd[k] - t; end return vect end function toComplex(vectr) vect={} for i,r in ipairs(vectr) do vect[i]=complex.new(r) end return vect end -- test data = toComplex{1, 1, 1, 1, 0, 0, 0, 0}; -- this works for old lua versions & luaJIT (depends on version!) -- print("orig:", unpack(data)) -- print("fft:", unpack(fft(data))) -- Beginning with Lua 5.2 you have to write print("orig:", table.unpack(data)) print("fft:", table.unpack(fft(data)))
Feigenbaum constant calculation
Lua
Calculate the Feigenbaum constant. ;See: :* Details in the Wikipedia article: Feigenbaum constant.
function leftShift(n,p) local r = n while p>0 do r = r * 2 p = p - 1 end return r end -- main local MAX_IT = 13 local MAX_IT_J = 10 local a1 = 1.0 local a2 = 0.0 local d1 = 3.2 print(" i d") for i=2,MAX_IT do local a = a1 + (a1 - a2) / d1 for j=1,MAX_IT_J do local x = 0.0 local y = 0.0 for k=1,leftShift(1,i) do y = 1.0 - 2.0 * y * x x = a - x * x end a = a - x / y end d = (a1 - a2) / (a - a1) print(string.format("%2d %.8f", i, d)) d1 = d a2 = a1 a1 = a end
Fibonacci n-step number sequences
Lua
These number series are an expansion of the ordinary [[Fibonacci sequence]] where: # For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2 # For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3 # For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4... # For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}} For small values of n, Greek numeric prefixes are sometimes used to individually name each series. :::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2" |+ Fibonacci n-step sequences |- style="background-color: rgb(255, 204, 255);" ! n !! Series name !! Values |- | 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |- | 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |- | 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |- | 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |- | 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |- | 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |- | 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |- | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |- | 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |} Allied sequences can be generated where the initial values are changed: : '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values. ;Task: # Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. # Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. ;Related tasks: * [[Fibonacci sequence]] * Wolfram Mathworld * [[Hofstadter Q sequence]] * [[Leonardo numbers]] ;Also see: * Lucas Numbers - Numberphile (Video) * Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video) * Wikipedia, Lucas number * MathWorld, Fibonacci Number * Some identities for r-Fibonacci numbers * OEIS Fibonacci numbers * OEIS Lucas numbers
function nStepFibs (seq, limit) local iMax, sum = #seq - 1 while #seq < limit do sum = 0 for i = 0, iMax do sum = sum + seq[#seq - i] end table.insert(seq, sum) end return seq end local fibSeqs = { {name = "Fibonacci", values = {1, 1} }, {name = "Tribonacci", values = {1, 1, 2} }, {name = "Tetranacci", values = {1, 1, 2, 4}}, {name = "Lucas", values = {2, 1} } } for _, sequence in pairs(fibSeqs) do io.write(sequence.name .. ": ") print(table.concat(nStepFibs(sequence.values, 10), " ")) end
Fibonacci word
Lua
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here: Define F_Word1 as '''1''' Define F_Word2 as '''0''' Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01''' Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2 ;Task: Perform the above steps for n = 37. You may display the first few but not the larger values of n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for F_Words '''1''' to '''37''' which shows: ::* The number of characters in the word ::* The word's [[Entropy]] ;Related tasks: * Fibonacci word/fractal * [[Entropy]] * [[Entropy/Narcissist]]
-- Return the base two logarithm of x function log2 (x) return math.log(x) / math.log(2) end -- Return the Shannon entropy of X function entropy (X) local N, count, sum, i = X:len(), {}, 0 for char = 1, N do i = X:sub(char, char) if count[i] then count[i] = count[i] + 1 else count[i] = 1 end end for n_i, count_i in pairs(count) do sum = sum + count_i / N * log2(count_i / N) end return -sum end -- Return a table of the first n Fibonacci words function fibWords (n) local fw = {1, 0} while #fw < n do fw[#fw + 1] = fw[#fw] .. fw[#fw - 1] end return fw end -- Main procedure print("n\tWord length\tEntropy") for k, v in pairs(fibWords(37)) do v = tostring(v) io.write(k .. "\t" .. #v) if string.len(#v) < 8 then io.write("\t") end print("\t" .. entropy(v)) end
File extension is in extensions list
Lua
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''. It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid. For these reasons, this task exists in addition to the [[Extract file extension]] task. ;Related tasks: * [[Extract file extension]] * [[String matching]]
-- Data declarations local extentions = {"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} local testCases = { "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2" } -- Return boolean of whether example has a file extension found in extList function extMatch (extList, example) for _, extension in pairs(extList) do if example:lower():match("%." .. extension:lower() .. "$") then return true end end return false end -- Main procedure for _, case in pairs(testCases) do print(case .. ": " .. tostring(extMatch(extentions, case))) end
Find if a point is within a triangle
Lua from C++
Find if a point is within a triangle. ;Task: ::* Assume points are on a plane defined by (x, y) real number coordinates. ::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. ::* You may use any algorithm. ::* Bonus: explain why the algorithm you chose works. ;Related tasks: * [[Determine_if_two_triangles_overlap]] ;Also see: :* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]] :* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]] :* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]] :* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]
EPS = 0.001 EPS_SQUARE = EPS * EPS function side(x1, y1, x2, y2, x, y) return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1) end function naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) local checkSide1 = side(x1, y1, x2, y2, x, y) >= 0 local checkSide2 = side(x2, y2, x3, y3, x, y) >= 0 local checkSide3 = side(x3, y3, x1, y1, x, y) >= 0 return checkSide1 and checkSide2 and checkSide3 end function pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) local xMin = math.min(x1, x2, x3) - EPS local xMax = math.max(x1, x2, x3) + EPS local yMin = math.min(y1, y2, y3) - EPS local yMax = math.max(y1, y2, y3) + EPS return not (x < xMin or xMax < x or y < yMin or yMax < y) end function distanceSquarePointToSegment(x1, y1, x2, y2, x, y) local p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) local dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength if dotProduct < 0 then return (x - x1) * (x - x1) + (y - y1) * (y - y1) end if dotProduct <= 1 then local p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y) return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength end return (x - x2) * (x - x2) + (y - y2) * (y - y2) end function accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) if not pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) then return false end if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) then return true end if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then return true end return false end function printPoint(x, y) io.write('('..x..", "..y..')') end function printTriangle(x1, y1, x2, y2, x3, y3) io.write("Triangle is [") printPoint(x1, y1) io.write(", ") printPoint(x2, y2) io.write(", ") printPoint(x3, y3) print("]") end function test(x1, y1, x2, y2, x3, y3, x, y) printTriangle(x1, y1, x2, y2, x3, y3) io.write("Point ") printPoint(x, y) print(" is within triangle? " .. tostring(accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y))) end test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0) test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1) test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1) print() test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348) print() test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348) print()
Find limit of recursion
Lua
{{selection|Short Circuit|Console Program Basics}} ;Task: Find the limit of recursion.
local c = 0 function Tail(proper) c = c + 1 if proper then if c < 9999999 then return Tail(proper) else return c end else return 1/c+Tail(proper) -- make the recursive call must keep previous stack end end local ok,check = pcall(Tail,true) print(c, ok, check) c=0 ok,check = pcall(Tail,false) print(c, ok, check)
Find the intersection of a line with a plane
Lua
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. ;Task: Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
function make(xval, yval, zval) return {x=xval, y=yval, z=zval} end function plus(lhs, rhs) return make(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z) end function minus(lhs, rhs) return make(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z) end function times(lhs, scale) return make(scale * lhs.x, scale * lhs.y, scale * lhs.z) end function dot(lhs, rhs) return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z end function tostr(val) return "(" .. val.x .. ", " .. val.y .. ", " .. val.z .. ")" end function intersectPoint(rayVector, rayPoint, planeNormal, planePoint) diff = minus(rayPoint, planePoint) prod1 = dot(diff, planeNormal) prod2 = dot(rayVector, planeNormal) prod3 = prod1 / prod2 return minus(rayPoint, times(rayVector, prod3)) end rv = make(0.0, -1.0, -1.0) rp = make(0.0, 0.0, 10.0) pn = make(0.0, 0.0, 1.0) pp = make(0.0, 0.0, 5.0) ip = intersectPoint(rv, rp, pn, pp) print("The ray intersects the plane at " .. tostr(ip))
Find the intersection of two lines
Lua from C#
Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html] ;Task: Find the point of intersection of two lines in 2D. The 1st line passes though (4,0) and (6,10) . The 2nd line passes though (0,3) and (10,7) .
function intersection (s1, e1, s2, e2) local d = (s1.x - e1.x) * (s2.y - e2.y) - (s1.y - e1.y) * (s2.x - e2.x) local a = s1.x * e1.y - s1.y * e1.x local b = s2.x * e2.y - s2.y * e2.x local x = (a * (s2.x - e2.x) - (s1.x - e1.x) * b) / d local y = (a * (s2.y - e2.y) - (s1.y - e1.y) * b) / d return x, y end local line1start, line1end = {x = 4, y = 0}, {x = 6, y = 10} local line2start, line2end = {x = 0, y = 3}, {x = 10, y = 7} print(intersection(line1start, line1end, line2start, line2end))