Module:JI ratios: Difference between revisions

Ganaram inukshuk (talk | contribs)
mNo edit summary
Ganaram inukshuk (talk | contribs)
Reworked products search as a BFS algorithm
Line 161: Line 161:
return ratios
return ratios
end
-- Go back to having a find-products function
function p.find_products(factors, max_product)
local factors = factors or { 2, 3, 5, 7, 11, 13, 17, 19 }
local max_product = max_product or 10000
-- Perform a breadth-first-search
-- Starting with the number 1 at the root node of a (simulated) search tree,
-- explore the possible products (child nodes) of multiplying that number
-- with exactly one each of the given factors. Any products that are less
-- than the max product are added to the search tree, and the search
-- recurses for each child node by finding its children produced by multi-
-- plying by one of each factor. The search on any one branch stops if the
-- resulting products exceed that of the max product.
local products = {{1}}
local new_products_found = true
while new_products_found do
local new_products = {}
for i = 1, #factors do
for j = 1, #products[#products] do
local new_product = products[#products][j] * factors[i]
if new_product <= max_product then
-- Check whether the product already exists; if not, add it
-- to the table of new products.
local product_already_added = false
for k = 1, #new_products do
product_already_added = product_already_added or new_product == new_products[k]
if product_already_added then break end
end
if not product_already_added then
table.insert(new_products, new_product)
end
end
end
end
if #new_products == 0 then
new_products_found = false
else
table.insert(products, new_products)
end
end
-- Consolidate and sort products
local consolidated_products = {}
for i = 1, #products do
for j = 1, #products[i] do
table.insert(consolidated_products, products[i][j])
end
end
products = consolidated_products
table.sort(products)
return products
end
end