Log In  


I have a table:
a={0,0,1,2,0,6,9,2,0,5,3,0,7,0,0}
I want to sort it so the 0's are moved to the front
This works:

 a={0,0,1,2,0,3,4,0,0,5,6,7,8,0,9,10}
 b={}
 c={}
 for v in all(a) do
  if v==0 then
   add(b,v)
  else
   add(c,v)
  end
 end
 for v in all(c) do
 add(b,v)
 end
 a=b

but is clunky and since this will be in a recursive function, efficiency is essential.
what is a more elegant/quicker way to do this?

1


This isn't a direct answer, but is this going to be generically available and used for a multitude of situations or is it designed for a very narrow scope? This question should determine the direction of your answer, I think.


generically available and used for a multitude of situations.

the example i gave is not the actual code. it will not be numbers and zeroes,
but rather multidimensional arrays. I'll need to move all the internal arrays that have a certain value to the front. So i'm hoping for an answer that deals with the concept, not just the above example.
the real thing is more like:

for m in all(moves) do
 if m.cap!=0 then
  add(b,m)
 else
  add(c,m)
 end
end
-- ..etc ..etc

1

I thought this code would be fine if you wanted to determine if the cap in the table is 0 and sort that element to the top.

for i,v in pairs(moves) do
 add(moves,deli(moves,i),v.cap==0 and 1 or i)
end

Operation verification code:

moves={
{cap=2}
,{cap=0}
,{cap=1}
,{cap=5}
,{cap=0}
,{cap=4}
,{cap=0}
}

?'before:',9
for i,v in pairs(moves) do
 ?v.cap,6
 add(moves,deli(moves,i),v.cap==0 and 1 or i)
end

?'\nafter:',12
for v in all(moves) do
 ?v.cap,6
end

--[[
before:
2
0
1
5
0
4
0

after:
0
0
0
2
1
5
4
]]

1

hello @shiftalow! nice to see you.
very clever, using the deleted move as the add value :)
my code has grown and I have a couple extra criteria now, but
this is great! I can use this idea to make a more streamlined
version. thank you for taking the time as always.



[Please log in to post a comment]