diff --git a/doc/functions.md b/doc/functions.md index dcc75a2..bc57006 100644 --- a/doc/functions.md +++ b/doc/functions.md @@ -261,6 +261,14 @@ Works without any arguments. x = rand() // any number between 0 and 1 ``` +### Generate Single Random Integer + +Works with one argument. + +``` +x = randi(5) // any integer between 0 and 5 +``` + ### Generate Random Vector Works with one argument. diff --git a/src/Mages.Core/Runtime/Functions/SimpleRandom.cs b/src/Mages.Core/Runtime/Functions/SimpleRandom.cs index 260ca47..1f06cec 100644 --- a/src/Mages.Core/Runtime/Functions/SimpleRandom.cs +++ b/src/Mages.Core/Runtime/Functions/SimpleRandom.cs @@ -27,6 +27,12 @@ public static Double GetNumber() return _random.NextDouble(); } + public static Int32 GetInteger(Int32 maximum) + { + EnsureRandom(); + return (Int32)Math.Round(_random.NextDouble() * maximum); + } + private static Double[,] CreateMatrix(Int32 rows, Int32 cols) { var matrix = new Double[rows, cols]; diff --git a/src/Mages.Core/Runtime/Functions/StandardFunctions.cs b/src/Mages.Core/Runtime/Functions/StandardFunctions.cs index 6889b5f..cc102fb 100644 --- a/src/Mages.Core/Runtime/Functions/StandardFunctions.cs +++ b/src/Mages.Core/Runtime/Functions/StandardFunctions.cs @@ -686,6 +686,13 @@ public static class StandardFunctions (args.Length > 0 ? If.Is(args, SimpleRandom.CreateVector) : null) ?? SimpleRandom.GetNumber()); + /// + /// Contains the random integer function. + /// + public static readonly Function Randi = new(args => Curry.MinOne(Randi, args) ?? + If.Is(args, x => SimpleRandom.GetInteger((int)x)) ?? + 0); + /// /// Contains the throw function. /// diff --git a/src/Mages.Core/Runtime/Global.cs b/src/Mages.Core/Runtime/Global.cs index f31b9a9..a0feeae 100644 --- a/src/Mages.Core/Runtime/Global.cs +++ b/src/Mages.Core/Runtime/Global.cs @@ -41,6 +41,7 @@ static class Global { "gamma", StandardFunctions.Gamma }, { "sqrt", StandardFunctions.Sqrt }, { "rand", StandardFunctions.Rand }, + { "randi", StandardFunctions.Randi }, { "sin", StandardFunctions.Sin }, { "cos", StandardFunctions.Cos }, { "tan", StandardFunctions.Tan },