题目一、给一个表,表里有5个数,在[0-13]之间,其中0可以表示任意数,判断这个表是否连续 思路: 连续的条件: 1、表中都是0 2、表中有4个0 3、0个数不大于3,经过排序之后除去0之外,最大值减去最小值的差小于5 注意:要排除掉除去0之外的数里面有相同的数 local list = {0,0,2,5,1} function toCheck () table.sort(list) -- 把数组从小到大排序 local zero_num = 0 for k,v in pairs(list) do if v == 0 then zero_num = zero_num + 1 elseif v ~= 0 then for i = k+1,#list do if v == list[i] then print("该表不连续") return end end end end if zero_num == 4 or zero_num ==5 then print("该表连续") elseif list[#list] - list[zero_num + 1] < 5 then print("该表连续") else print("该表不连续") end end toCheck()
题目二、如何将一组数据等概率打乱? t = {1,2,3,4,5,6,7,8,9} local function shuffle(t) if not t then return end local cnt = #t for i=1,cnt do local j = math.random(i,cnt) t[i],t[j] = t[j],t[i] end end shuffle(t) for k,v in pairs(t) do print(v) end
题目三、将一个数组从小到大排序,然后将重复出现的数字全部删除(后续数字往前移) local t = {4,2,3,4,1,6,5,8,7} local newArray = {} table.sort(t) newArray[1] = t[1] for i = 2,#t do if t[i] ~= t[i - 1] then newArray[i] = t[i] end end for k,v in pairs(newArray) do print(v) end
题目四、编写一个函数,将某个数组分成两个数组,一个存放偶数,一个存放奇数 local t = {4,2,3,4,1,6,5,8,7} function device(array) local oushuArr = {} local jishuArr = {} for i = 1,#array do if t[i] % 2 == 0 then oushuArr[#oushuArr + 1] = array[i] else jishuArr[#jishuArr + 1] = array[i] end end return oushuArr,jishuArr end local a,b = device(t) for k,v in pairs(a) do print(v) end print("=========") for k,v in pairs(b) do print(v) end