5 求随机迭代数组的方法

发布于 2020-06-15 23:43:11

有一个数组t={"a","b","c","d","e","f","g",} 求随机迭代所有值的方法.不能删除数组里的值.

查看更多

关注者
1
被浏览
807
Evan
Evan 认证专家 2020-06-16

不知道你说的随机迭代是什么意思.姑且按照随机打乱数组顺序吧.

function randomTable(_table, _num) 
  local _result = {}
  local _index = 1
  local _num = _num or #_table
  while #_table ~= 0 do
      local ran = math.random(0, #_table)
      if _table[ran] ~= nil then
          _result[_index] = _table[ran]
          table.remove(_table,ran)
          _index = _index + 1
          if _index > _num then 
              break
          end 
      end
  end
  return _result
end
function copy_table(ori_tab)
    if type(ori_tab) ~= "table" then
        return
    end
    local new_tab = {}
    for k, v in pairs(ori_tab) do
        local vtype = type(v)
        if vtype == "table" then
            new_tab[k] = copy_table[v]
        else
            new_tab[k] = v
        end
    end
    return new_tab
end
function main()
  t = {"a","b","c","d","e","f","g"}
  f = randomTable(copy_table(t))
  logDebug(table.concat(t,','))
  logDebug(table.concat(f,','))
end

然后按顺序输出新数组f 就等于是随机t数组的内容且不重复了

2 个回答
create658
create658 认证专家 2020-06-20

function main()

t={"a","b","c","d","e","f","g"} 
for i=1,#t do
    notifyMessage(t[i])
end

end

function main()

t={"a","b","c","d","e","f","g"} 

for k,v in pairs(t) do

notifyMessage(v)
end

end

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览