5

I'm trying to get a list of unique random integers within an interval with the luarandom package.

Here is a MWE, adapted from the package documentation:

\documentclass{article}
\usepackage{luarandom}
\usepackage{multido}
\begin{document}

\makeRandomNumberList{1}{30}{5}% works % \makeRandomNumberList{2}{30}{5}% hangs \multido{\iA=1+1}{5}{\getNumberFromList{\iA}, }

\end{document}

This gives five unique integers between 1 and 30. But I don't want 1 to be in my list. If I change the {1} to a {2}, as in the commented-out line, LaTeX seems to get into an infinite loop.

The lua code inside the luarandom package (copied below) isn't documented, so I can't trace what's going on easily. But it seems like the allFound(R) may not ever be returning true?

RandomNumbers = {}

function allFound(R) local r1 = R[1] local i for i=2,#R do r1 = r1 and R[i] if not r1 then return false end end return true end

function makeRandomNumberList(l,r,n) RandomNumbers = {} math.randomseed(os.time()) local R = {} local i,j for i=1,n do R[i] = false end repeat local rand = math.random(l,r) if not R[rand] then R[rand] = true RandomNumbers[#RandomNumbers+1] = rand end until allFound(R) end

function makeSimpleRandomNumberList(l,r,n) RandomNumbers = {} math.randomseed(os.time()/3) local i for i=1,n do RandomNumbers[#RandomNumbers+1] = math.random(l,r) end end

function getRand(i) tex.print(RandomNumbers[i]) end

Matthew Leingang
  • 44,937
  • 14
  • 131
  • 195

1 Answers1

6

The package documentation is very sparse but it looks like a Lua programming error, I think the intended definition is

\documentclass{article}
\usepackage{luarandom}
\directlua{
function makeRandomNumberList(l,r,n)
  RandomNumbers = {}
  math.randomseed(os.time())
  local R = {}
  local i,j
  for i=1,n do R[i] = false end
  repeat
    local rand = math.random(l,r)
    if not R[rand+1-l] then
      R[rand+1-l] = true
      RandomNumbers[\string#RandomNumbers+1] = rand
    end
  until allFound(R)
end
}
\usepackage{multido}
\begin{document}

%\makeRandomNumberList{1}{30}{5}% works \makeRandomNumberList{2}{30}{5}% hangs \multido{\iA=1+1}{5}{show\iA\getNumberFromList{\iA}, }

\end{document}

David Carlisle
  • 757,742