-1

I would like to know how can I split my table into subtables of 9's.

Example:

{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }

Code shall return:

{ {1, 2, 3, 4, 5, 6, 7, 8, 9}, {10, 11, 12, 13, 14, 15, 16, 17, 18}, { 19, 20} }

How do you think is this done?

Ram Jano
  • 23
  • 2

1 Answers1

3

Your code seems over complicated. The task is to create a subtable every 9 elements. The code below does that:

a={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }
b={}
j=0
k=9

for i=1,#a do
    if k==9 then j=j+1; b[j]={}; k=0 end
    k=k+1
    b[j][k]=a[i]
end

Here, j tracks the number of subtables created and k tracks the number of elements added to a subtable. When k becomes 9, a new subtable is created. k starts at 9 to signal that.

lhf
  • 70,581
  • 9
  • 108
  • 149