Skip to content

Commit

Permalink
Merge pull request #7 from AnnulusGames/fix-weightedlist-removerandom
Browse files Browse the repository at this point in the history
Fix: RemoveRandom returns default(T) when the last element is selected
  • Loading branch information
AnnulusGames authored Aug 20, 2024
2 parents c248662 + 1340a52 commit af00c29
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/RandomExtensions/Collections/WeightedList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public void RemoveRandom(out T item)

public void RemoveRandom(IRandom random, out T item)
{
if (Count == 0) throw new InvalidOperationException("Empty list");
if (list.Count == 0) throw new InvalidOperationException("Empty list");

var r = random.NextDouble() * totalWeight;
var current = 0.0;
Expand All @@ -228,7 +228,7 @@ public void RemoveRandom(IRandom random, out T item)
}
}

item = default!;
item = list[^1].Value;
}

IEnumerator IEnumerable.GetEnumerator()
Expand Down
9 changes: 6 additions & 3 deletions tests/RandomExtensions.Tests/WeightedListTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,17 @@ public void Test_RemoveRandom()
{ 3, 3.0 },
};

list.RemoveRandom(out _);
list.RemoveRandom(out var item0);
Assert.That(list, Has.Count.EqualTo(2));
Assert.That(item0, Is.EqualTo(1).Or.EqualTo(2).Or.EqualTo(3));

list.RemoveRandom(out _);
list.RemoveRandom(out var item1);
Assert.That(list, Has.Count.EqualTo(1));
Assert.That(item1, Is.EqualTo(1).Or.EqualTo(2).Or.EqualTo(3));

list.RemoveRandom(out _);
list.RemoveRandom(out var item2);
Assert.That(list, Has.Count.EqualTo(0));
Assert.That(item2, Is.EqualTo(1).Or.EqualTo(2).Or.EqualTo(3));

Assert.Throws<InvalidOperationException>(() => list.RemoveRandom(out _));
}
Expand Down

0 comments on commit af00c29

Please sign in to comment.