You can just make a list of each:
local titleFormats = {
{nouns, verbs, adverbs},
{nouns, verbs},
}
Given a particle "format" (a list of word-lists, e.g., {nouns, verbs, adverbs}) you can generate a particular example by pulling from the lists:
function choose(list)
return list[math.random(#list)]
end
function randomFromFormat(format)
local out = {}
for i = 1, #format do
out[i] = choose(format[i])
end
return table.concat(out, " ")
end
You can re-use choose to pick a random format from all formats, and then use exampleFromFormat to pick a random choice from there:
function randomTitle()
return randomFromFormat(choose(titleFormats))
end
Cartesian products
Another interpretation is to actually expand a "format" into all of the titles of that format.
Given options from a set A and options from a set B, you can write the set of all pairs of values from A and from B as A × B (in math notation, not Lua), called the Cartesian Product.
In this case, what you want to do is pick a random element from nouns × verbs × adverbs, so an option is to just generate all of these ahead of time.
That isn't really a good idea, because if you have 1000 of each type of word, you have one-billion possible titles, and storing them all is really wasteful (you'll only ever ask for a few).
Still, it's an interesting function, and can be easily written recursively.
function cartesianProduct(firsts, ...)
if not firsts then
return {{}}
end
local out = {}
local rests = cartesianProduct(...)
for _, rest in pairs(rests) do
for _, first in pairs(firsts) do
local copy = {first}
for i = 1, #rest do
copy[i+1] = rest[i]
end
table.insert(out, copy)
end
end
return out
end
for _, title in pairs(cartesianProduct(nouns, verbs, adverbs)) do
print(table.concat(title, " "))
end
1 comment
This is rather awkward to have a large number of different formats -- you have to hand-write each one