Skip to content

Commit

Permalink
reduced previous fix to a one-line-changed compared to state before fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
ndsvw committed Mar 16, 2024
1 parent ac86336 commit 5b71913
Showing 1 changed file with 10 additions and 20 deletions.
30 changes: 10 additions & 20 deletions FluentRandomPicker/Picker/DefaultPicker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,33 +50,23 @@ public PickResult<IEnumerable<T>> Pick()
return new PickResult<IEnumerable<T>>(Enumerable.Empty<T>());

var prioritySum = _pairs.Sum(v => (long)v.Priority);
var values = PickPrioritized(prioritySum);
var values = Enumerable.Range(0, _numberOfElementsToPick).Select(_ => PickPrioritized(prioritySum));
return new PickResult<IEnumerable<T>>(values);
}

private IEnumerable<T> PickPrioritized(long prioritySum)
private T PickPrioritized(long prioritySum)
{
for (var i = 0; i < _numberOfElementsToPick; i++)
{
yield return GetValue();
}

yield break;
var n = (long)(_rng.NextDouble() * prioritySum);

T GetValue()
long localSum = 0;
foreach (var pair in _pairs)
{
var n = (long)(_rng.NextDouble() * prioritySum);
localSum += pair.Priority;

long localSum = 0;
foreach (var pair in _pairs)
{
localSum += pair.Priority;

if (localSum >= n + 1)
return pair.Value;
}

throw new ArgumentException("Sum of priorities was wrong", nameof(prioritySum));
if (localSum >= n + 1)
return pair.Value;
}

throw new ArgumentException("Sum of priorities was wrong", nameof(prioritySum));
}
}

0 comments on commit 5b71913

Please sign in to comment.