The Holier Numbers
Lua, 317 Bytes
I had some troubles doing this, some things in Lua don't work as I think it does. I will have to try and play with them if I want to golf this down.
You can test lua online by replacing arg[1]
by the number of elements you want :).
function f(y)h=0(y..''):reverse():gsub(".",function(c)h=c:find("[08]")and 1+h or h end)return h end
x,a=0,{}while(#a<arg[1]+0)do a[#a+1],x=(x..''):find("^[04689]*$")and x or nil,x+1 end
for i=1,#a do m=1
for j=1,#a do x=a[m]m=(f(x)~=f(a[j])and f(x)>f(a[j])or x>a[j])and j or m
end end print(a[m])table.remove(a,m)end
Ungolfed and explanations
function f(y) -- function returning the enhanced holiness of a holy number
h=0 -- h is the cumulated holyness of processed digits
(y..''):reverse() -- reverse the digits in y
:gsub(".",function(c) -- iterate over each digits
h=c:find("[08]")and 1+h or h -- ternary based on the digit being [08] or [469]
end)
return h -- return h
end
x,a=0,{} -- initialise a counter, and the array of holy numbers
while(#a<arg[1]+0) -- iterate until we have n holy numbers
do
a[#a+1]=(x..'')
:find("^[04689]*$") -- if we can't find an unholy digit
and x or nil -- insert x into a
x=x+1 -- increment x anyway
end
for i=1,#a -- iterate n times(current size of a)
do
m=1 -- m is the index of the lowest value
for j=1,#a -- iterate over a
do
x=a[m] -- x is shorter to write than a[m]
m=(f(x)~=f(a[j]) -- nested ternaries, translated in
and f(x)>f(a[j]) -- nested if below
or x>a[j])and j or m
end
print(a[m]) -- output a[m]
table.remove(a,m) -- remove it from the table a
end
The nested ternaries used for the new value of m
can be translated in nested ifs as:
if(f(a[m])~=f(a[j])) then -- if a[m] and a[j] don't have the same holyness
if(f(a[m])>f(a[j])) then m=j end-- compare by holyness
else
if(a[m]>a[j]) then m=j end -- else, compare by numeric value
Also, I would have loved to replace the nested for
by using table.sort
, but, for a reason I don't know, the following doesn't work despite not producing an infinite loop or crushing the sort function.
table.sort(a,function(i,j)
return f(i)~=f(j)
and f(i)>f(j)
or i>j
end)