Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a randi() function to generate random integers #124

Merged
merged 4 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
5 changes: 5 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,11 @@ 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 => SimpleRandom.GetInteger((int)args[0]));
GhostVaibhav marked this conversation as resolved.
Show resolved Hide resolved

/// <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
Loading