首页 > 解决方案 > Lua - 在每次运行/事件中随机选择 3 个数字(共 250 个),但不包括一个

问题描述

我想在每个事件中从 0 到 250 的数组中获取随机 3 个数字(例如 3、177、244),并且不包括 0 到 250 之间的预定义数字(例如 220)。

例如,

  1. 在第一个事件(按钮)中,我从另一个数据集中得到了 220,所以我需要像 a=3、b=177、c=244(a、b、c 不应该是 220)这样的随机数。

  2. 在第二个事件(按钮)中,我从另一个数据集中得到了 15,所以我需要像 a=77、b=109、c=166 这样的随机数(a、b、c 不应该是 15)

你有什么好主意来实现这个吗? 寻找一个好的数学家!干杯。

基于@Evan Wrynn,我尝试了以下操作,但我需要多一步才能在表格中随机获取 3 个数字,对吧。基本上我试着把所有的数字都放在 t 中。d 是我从另一个来源获得的变量。结果应该是包含 3 个随机数的 t(即 t={4, 88, 221}(本例中的 85 除外))。目前 t 似乎得到重复的数字:(。也欢迎完全替代的想法。

d = 85
dt = {}
t = {}
table.insert(dt,d)
while table.getn(t) < 3 do
  function GetMathRandomExclude(lowerbound,upperbound,exclude)
    local x = math.random(lowerbound,upperbound)
    for _,v in pairs(exclude) do
      if v == x then
        return GetMathRandomExclude(lowerbound,upperbound,exclude)
      else
        return table.insert(t,x)
      end
    end
  end
  GetMathRandomExclude(1,250,dt)
end
for i, v in ipairs(t) do
  print(i, v)
end

标签: randomlua

解决方案


function GetMathRandomExclude(lowerbound,upperbound,exclude)
  local x = math.random(lowerbound,upperbound)
  if x == exclude then
    return GetMathRandomExclude(lowerbound,upperbound,exclude)
  end
  return x
end

print(GetMathRandomExclude(1,3,2)) -> (当调用 10 次时,我得到“3”7 次和“1”3 次。

如果数字 = 排除它的数字,则调用该功能。您可以检查一个表以使其具有多个排除项。

编辑:

function GetMathRandomExclude(lowerbound,upperbound,exclude)
  local x = math.random(lowerbound,upperbound)
  if type(exclude) == "table" then
    for _,v in pairs(exclude) do
      if v == x then
        return GetMathRandomExclude(lowerbound,upperbound,exclude)
      end
    end
  else
    if x == exclude then
      return GetMathRandomExclude(lowerbound,upperbound,exclude)
    end
  end
  return x
end

打印(GetMathRandomExclude(1,100,{85,62})) -> 40

GetMathRandomExclude(NUMBER 下限,NUMBER 上限,NUMBER OR TABLE 排除)


推荐阅读