lua笔记2

来源:互联网 发布:单片机支持snmp协议 编辑:程序博客网 时间:2024/05/17 04:24
之前留下的坑太多了,现在都含着泪慢慢填。今天的是第二次练习,变化不大。第二题更加明确一些。所以可以更新的方法更多。然后代码习惯有所改进吧。

 --第一题一个长度为10的整型数组a[10]={3,4,6,7,8,4,2,1,9,10}
 --将重复出现的数字全部删除(后续数字往前移)
 local a={3,4,6,7,8,4,2,1,9,10}
 for i=1,10 do
 for j=i+1,10 do
     if a[i]==a[j] then
      table.remove(a,j)
     end
 end
 end
 for i,v in ipairs(a) do
 print(i,v)
end
--现有一个元素数量不为0的表,每个元素均为整数,其中0可以表示任意数,
--请写出方法isTableOrder_Ex判断这个表中的数据是否是一个单调递增且公差为1的等差数列。(<=20 lines)
--[[如果第一个数为零,则对零计数,若记到零个数与表个数相等,返回(true)
     记录到第一个非零数的位置,与后一个数做差,后一个数为零则给他赋值为前一个数加1.
     并记录结果为1的次数,与零的个数相加,若为表的长度,则返回(true),否则(false)
     第一个数不为零,直接按上述找到非零数的步骤执行,从1开始计数--]]
function istableorder_Ex( t )
x=1 z=1
if(t[1]==0) then
           i=1
            while(t[i]==0) do
                  i=i+1
                  if(i==#t) then
                    return(true)
                  else x=i 
                  end 
            end  
                for i=x,#t-1 do
                    if(t[i+1]==0) then 
                        t[i+1]=t[i]+1 
                    end
                    if(t[i+1]-t[i]==1) then
                        x=x+1
                        if x==#t then
                           return (true)
                        end  
                    else return(false)
                    end    
                end 
        else   for i=1,#t-1 do
                    if(t[i+1]==0) then 
                       t[i+1]=t[i]+1 
                    end
                    if(t[i+1]-t[i]==1) then
                        z=z+1
                        if z==#t then
                            return (true)
                        end    
                    else return(false)
                    end    
               end  
        end
        --]]
end
                     
               
                        
a= {-2,0,0,1,2,3,0,5,0,0,8}
print(istableorder_Ex(a))  
--第二题改进
function istableorder_Ex2( t )
  for i=1,#t do
      if(t[i]~=0) then
         for j=i,#t-1 do
             if(t[i+1]==0) then
                t[i+1]=t[i]+1
             end   
             if t[i+1]-t[i]~=1 then
                return(false)
             else return(true)
             end
          end   
      else return(true)
      end  
  end
end
print(istableorder_Ex2(a))
0 0