Add method for creating a random array of distinct values.

This commit is contained in:
Kristian Stolen
2022-01-12 19:00:51 +08:00
parent b1cfa83ac5
commit 1d4651bfef
4 changed files with 65 additions and 1 deletions

View File

@@ -0,0 +1,10 @@
using FsCheck;
namespace Reverse.Tests.Generators
{
public static class PositiveIntegerGenerator
{
public static Arbitrary<int> Generate() =>
Arb.Default.Int32().Filter(x => x > 0);
}
}

View File

@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FsCheck.Xunit" Version="2.16.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">

View File

@@ -1,3 +1,5 @@
using FsCheck.Xunit;
using Reverse.Tests.Generators;
using System.Linq;
using Xunit;
@@ -48,6 +50,34 @@ namespace Reverse.Tests
Assert.True(input.SequenceEqual(output));
}
[Property(Arbitrary = new[] { typeof(PositiveIntegerGenerator) })]
public void CreateRandomArray_ReturnsRandomArrayOfSpecifiedLength()
{
var result = Reverser.CreateRandomArray(5);
Assert.Equal(5, result.Length);
}
[Property(Arbitrary = new[] { typeof(PositiveIntegerGenerator) })]
public void CreateRandomArray_MaxElementValueIsEqualToSize(int size)
{
var result = Reverser.CreateRandomArray(size);
Assert.Equal(size, result.Max());
}
[Property(Arbitrary = new[] { typeof(PositiveIntegerGenerator) })]
public void CreateRandomArray_ReturnsRandomArrayWithDistinctElements(int size)
{
var array = Reverser.CreateRandomArray(size);
var arrayGroup = array.GroupBy(x => x);
var duplicateFound = arrayGroup.Any(x => x.Count() > 1);
Assert.False(duplicateFound);
}
[Theory]
[InlineData(new int[] { 1 })]
[InlineData(new int[] { 1, 2 })]

View File

@@ -1,4 +1,6 @@
namespace Reverse
using System;
namespace Reverse
{
public class Reverser
{
@@ -18,6 +20,27 @@
}
}
public static int[] CreateRandomArray(int size)
{
var array = new int[size];
for (int i = 1; i <= size; i++)
{
array[i - 1] = i;
}
var rnd = new Random();
for (int i = size; i > 1;)
{
int k = rnd.Next(i);
--i;
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
return array;
}
public static bool IsArrayInAscendingOrder(int[] array)
{
for (int i = 1; i < array.Length; i++)