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

support for collection shuffle #3294

Merged
merged 2 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions src/Microsoft.DotNet.Interactive.AIUtilities.Tests/SamplingTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using FluentAssertions;
using Xunit;

namespace Microsoft.DotNet.Interactive.AIUtilities.Tests;

public class SamplingTest
{
[Fact]
public void can_shuffle_collection()
{
var src = Enumerable.Range(0, 10);
var shuffled = src.Shuffle().ToArray();
shuffled.Should().NotBeInAscendingOrder();
}

[Fact]
public void does_not_duplicate_items()
{
var src = Enumerable.Range(0, 10).ToArray();
var shuffled = src.Shuffle().Distinct().ToArray();
shuffled.Should().HaveCount(src.Length);
}
}
21 changes: 21 additions & 0 deletions src/Microsoft.DotNet.Interactive.AIUtilities/Sampling.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DotNet.Interactive.AIUtilities;

public static class Sampling
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
var rnd = new Random();
var list = new List<T>(source);
while (list.Count > 0)
{
var pos = rnd.Next(list.Count);
var sample = list.ElementAt(pos);
list.RemoveAt(pos);
yield return sample;

}
}
}