Skip to content

Commit

Permalink
Merge pull request #124 from GhostVaibhav/ghostvaibhav/123
Browse files Browse the repository at this point in the history
Added a randi() function to generate random integers
  • Loading branch information
FlorianRappl authored Jun 28, 2024
2 parents dbb5abb + 084c78a commit 0381d18
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions doc/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/Mages.Core/Runtime/Functions/SimpleRandom.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
7 changes: 7 additions & 0 deletions src/Mages.Core/Runtime/Functions/StandardFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,13 @@ public static class StandardFunctions
(args.Length > 0 ? If.Is<Double>(args, SimpleRandom.CreateVector) : null) ??
SimpleRandom.GetNumber());

/// <summary>
/// Contains the random integer function.
/// </summary>
public static readonly Function Randi = new(args => Curry.MinOne(Randi, args) ??
If.Is<Double>(args, x => SimpleRandom.GetInteger((int)x)) ??
0);

/// <summary>
/// Contains the throw function.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Mages.Core/Runtime/Global.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down

0 comments on commit 0381d18

Please sign in to comment.