-
-
Save jbrains/b428e1309d1dc8a71ed9c224cfeac59d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using NUnit.Framework; | |
//Using Maybe.cs | |
namespace ArrayStructure | |
{ | |
[TestFixture] | |
public class Tests | |
{ | |
[Test] | |
public void RepeatingNumber_EmptyArray_ReturnsNone() | |
{ | |
Assert.False(FirstNonRepeatingNumber(new int[] {}).HasValue); | |
} | |
[Test] | |
public void RepeatingNumber_ArrayContainsOneValue_ReturnThatValue() | |
{ | |
Assert.True(FirstNonRepeatingNumber(new[] {1}).Value == 1); | |
} | |
[Test] | |
public void RepeatingNumber_ArrayContains_Two_NonRepeatingNumbers_ReturnTheFirst() | |
{ | |
Assert.True(FirstNonRepeatingNumber(new[] {1,2}).Value == 1); | |
} | |
[Test] | |
public void RepeatingNumber_ArrayContainsTwoReapeating_OneNon_ReturnNonRepeating() | |
{ | |
Assert.True(FirstNonRepeatingNumber(new[] {1,1,2}).Value == 2); | |
} | |
[Test] | |
public void RepeatingNumber_ArrayContainsThreeRepeating_NoNon_ReturnNone() | |
{ | |
Assert.False(FirstNonRepeatingNumber(new[] {1,1,2,2,3,3}).HasValue); | |
} | |
[Test] | |
public void RepeatingNumber_ArrayContainsManyMultipleRepeating_ReturnNon_Performs() | |
{ | |
Assert.True(FirstNonRepeatingNumber(new[] {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1}).Value == 2); | |
} | |
[Test] | |
public void RepeatingNumber_ArrayContainsUnOrderedInvariants_ReturnTwo() | |
{ | |
Assert.True(FirstNonRepeatingNumber(new[] {1,3,5,3,1,2,5}).Value == 2); | |
} | |
[Test] | |
public void RepeatingNumber_ArrayContainsANegativeNonRepeating_ReturnNegativeThree() | |
{ | |
Assert.True(FirstNonRepeatingNumber(new[] {2,2,-3,6,6}).Value == -3); | |
} | |
[Test] | |
public void OnlyRepeatingNumbers_NotAllMerelyDuplicated() | |
{ | |
Assert.False(FirstNonRepeatingNumber(new int[] {3,3,5,3,5}).HasValue); | |
} | |
private Maybe<int> FirstNonRepeatingNumber(IReadOnlyList<int> ints) | |
{ | |
if (!ints.Any()) return Maybe<int>.None; | |
var duplicates = new List<int>(); | |
for (var i = 0; i < ints.Count; i++) | |
{ | |
for (var j = i+1; j < ints.Count; j++) | |
{ | |
if (ints[i] == ints[j]) | |
{ | |
duplicates.Add(ints[i]); | |
} | |
} | |
} | |
var nonDuplicates = ints.ToList(); | |
if (duplicates.Count == (double)nonDuplicates.Count / 2) | |
{ | |
return Maybe<int>.None; | |
} | |
foreach (var item in duplicates) | |
{ | |
nonDuplicates.RemoveAll(x => x == item); | |
} | |
return Maybe<int>.Some(nonDuplicates[0]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@aswhitehouse The test OnlyRepeatingNumbers_NotAllMerelyDuplicated fails.