fork download
  1.  
  2. math.randomseed(os.time())
  3.  
  4. local function result_pos(num, max)
  5. if num == 0 then
  6. return (max - num) + 1
  7. else
  8. return result_pos(num - 1, max) + (max - num) + 1
  9. end
  10. end
  11.  
  12. local function memoize(fn)
  13. local t = {}
  14. return function(...)
  15. local k = table.concat({...}, ',')
  16. if not t[k] then
  17. t[k] = fn(...)
  18. end
  19. return t[k]
  20. end
  21. end
  22.  
  23. local result_pos = memoize(result_pos)
  24.  
  25. local function crazy_dice(n)
  26. local size = result_pos(n, n)
  27. local rand = math.random(size)
  28. for i = 0, n do
  29. if rand <= result_pos(i, n) then
  30. return i
  31. end
  32. end
  33. error()
  34. end
  35.  
  36. local tally = {}
  37. local count = 100000
  38. local sides = 30
  39. for i = 1, count do
  40. local res = crazy_dice(sides)
  41. if not tally[res] then tally[res] = 1
  42. else tally[res] = tally[res] + 1
  43. end
  44. end
  45.  
  46. for i = 0, sides do
  47. print(i, (tally[i] or 1) / count)
  48. end
Success #stdin #stdout 3.53s 2540KB
stdin
Standard input is empty
stdout
0	0.06203
1	0.06032
2	0.05797
3	0.05522
4	0.05436
5	0.0522
6	0.05003
7	0.04904
8	0.04758
9	0.04517
10	0.04207
11	0.04005
12	0.03795
13	0.03661
14	0.03327
15	0.03348
16	0.02969
17	0.0293
18	0.02532
19	0.02359
20	0.02237
21	0.02013
22	0.0186
23	0.01629
24	0.01481
25	0.01244
26	0.00965
27	0.00797
28	0.00617
29	0.00414
30	0.00218