challenge n人中m人が当選するくじ

n人の中から公平にm人を選ぶ、くじ引きプログラムを作ってください。

Posted feedbacks - Lua

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function lot(n, m)
  math.randomseed(os.time())
  lot = {}
  for i = 1, n do
    table.insert(lot,i)
  end

  ret = {}
  for i = 1, m do
    pos = math.random(table.getn(lot))
    x = lot[ pos ]
    table.remove(lot, pos)
    table.insert(ret,x)
  end
  return ret
end

function print_lot(n, m)
  table.foreach(lot(n, m), function(k,v) print(v) end)
end

print_lot(9999, 4)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
math.randomseed(os.time())

function iota(n)
  local t = {}
  for i=1,n do
    table.insert(t, i)
  end
  return t
end

function lot(m, n)
  function pick(winners, rest, m)
    if m == 0 then
      return winners
    else
      local picked = table.remove(rest, math.random(#rest))
      table.insert(winners, picked)
      return pick(winners, rest, m-1)
    end
  end
  return pick({}, iota(n), m)
end

function show_array(t)
  print("["..table.concat(t, " ").."]")
end

show_array(lot(arg[1], arg[2]))

Index

Feed

Other

Link

Pathtraq

loading...