% $Id: luarandom.sty 813 2023-11-13 19:33:29Z herbert $
%%
%% This is file `luarandom.sty'.
%%
%% IMPORTANT NOTICE:
%%
%% luarandom Copyright (C) 2018,2023-     Herbert Voss <hvoss@tug.org>
%%
%% This package may be distributed under the terms of the LaTeX Project
%% Public License, as described in lppl.txt in the base LaTeX distribution.
%% Either version 1.3 or, at your option, any later version.
%%

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{luarandom}[2023/11/12 v 0.02 package for random numbers]
\RequirePackage{iftex}

\def\lua@nl{^^J\space\space\space\space}
\newcommand\lua@PackageError[2]{\PackageError{luarandom}{\lua@nl #1^^J}{#2}}
\ifluatex\else
      \lua@PackageError{%
        "You are not using LuaTeX\app@nl
        the lua definitions will not be available!}
       {If you run the source from a GUI then set
        the compiler "lualatex" in the 
        preferences.}%
\fi

\RequirePackage{luacode}
\begin{luacode*}
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,seed)
  RandomNumbers = {}
  if seed == 0 then 
    math.randomseed(os.time())  
  else
    math.randomseed(seed)  
  end
  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[#RandomNumbers+1] = rand
    end
  until allFound(R)
end

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

function getRand(i)
 tex.print(RandomNumbers[i])
end
\end{luacode*}

\newcommand\makeRandomNumberList[4][0]{%
  \directlua{makeRandomNumberList(#2,#3,#4,#1)}}
\newcommand\makeSimpleRandomNumberList[4][0]{%
  \directlua{makeSimpleRandomNumberList(#2,#3,#4,#1)}}
\def\getNumberFromList#1{\directlua{getRand(#1)}}


\endinput
