diff --git a/src/Microsoft.DotNet.Interactive.AIUtilities.Tests/SamplingTest.cs b/src/Microsoft.DotNet.Interactive.AIUtilities.Tests/SamplingTest.cs new file mode 100644 index 0000000000..8e629b6d76 --- /dev/null +++ b/src/Microsoft.DotNet.Interactive.AIUtilities.Tests/SamplingTest.cs @@ -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); + } +} \ No newline at end of file diff --git a/src/Microsoft.DotNet.Interactive.AIUtilities/Sampling.cs b/src/Microsoft.DotNet.Interactive.AIUtilities/Sampling.cs new file mode 100644 index 0000000000..ae1fb4479c --- /dev/null +++ b/src/Microsoft.DotNet.Interactive.AIUtilities/Sampling.cs @@ -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 Shuffle(this IEnumerable source) + { + var rnd = new Random(); + var list = new List(source); + while (list.Count > 0) + { + var pos = rnd.Next(list.Count); + var sample = list.ElementAt(pos); + list.RemoveAt(pos); + yield return sample; + + } + } +} \ No newline at end of file