Skip to content

Commit

Permalink
Add random pick / take methods for sets (space-wizards#4821)
Browse files Browse the repository at this point in the history
* Add random pick / take methods for sets

I want it don't at me.

* cleanup (mraow)

* Revert "cleanup (mraow)"

This reverts commit e279957.

* flatpak

* notes
  • Loading branch information
metalgearsloth authored Jan 8, 2024
1 parent c68b3dc commit 7592997
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
1 change: 1 addition & 0 deletions RELEASE-NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ END TEMPLATE-->
### New features

* `TextEdit.OnTextChanged`
* Add Pick and PickAndTake versions for System.Random for ICollections.

### Bugfixes

Expand Down
2 changes: 2 additions & 0 deletions Robust.Shared/Random/IRobustRandom.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using Robust.Shared.Collections;
using Robust.Shared.Maths;
using Robust.Shared.Toolshed.Commands.Generic;

namespace Robust.Shared.Random;

Expand Down
33 changes: 32 additions & 1 deletion Robust.Shared/Random/RandomExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Robust.Shared.Collections;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
Expand Down Expand Up @@ -47,7 +48,7 @@ public static T Pick<T>(this IRobustRandom random, IReadOnlyCollection<T> collec
}
}

throw new InvalidOperationException("This should be unreachable!");
throw new UnreachableException("This should be unreachable!");
}

public static T PickAndTake<T>(this IRobustRandom random, IList<T> list)
Expand All @@ -58,6 +59,36 @@ public static T PickAndTake<T>(this IRobustRandom random, IList<T> list)
return element;
}

/// <summary>
/// Picks a random element from a set and returns it.
/// This is O(n) as it has to iterate the collection until the target index.
/// </summary>
public static T Pick<T>(this System.Random random, ICollection<T> collection)
{
var index = random.Next(collection.Count);
var i = 0;
foreach (var t in collection)
{
if (i++ == index)
{
return t;
}
}

throw new UnreachableException("This should be unreachable!");
}

/// <summary>
/// Picks a random from a collection then removes it and returns it.
/// This is O(n) as it has to iterate the collection until the target index.
/// </summary>
public static T PickAndTake<T>(this System.Random random, ICollection<T> set)
{
var tile = Pick(random, set);
set.Remove(tile);
return tile;
}

/// <summary>
/// Generate a random number from a normal (gaussian) distribution.
/// </summary>
Expand Down

0 comments on commit 7592997

Please sign in to comment.