“Solution to Problem 4”

A Lua response to Problem 4:

Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021.

function eval(a, i)
if not i then i = 1 max = 0 end
if i == #a then
local n = tonumber(table.concat(a))
if n > max then max = n end
for j=i,#a do
a[i],a[j] = a[j],a[i]
eval(a, i+1)
a[i],a[j] = a[j],a[i]
eval({50, 2, 1, 9})
io.write("max is ", max, "\n")

Output is:

max is 95021

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.