Created
March 26, 2021 09:42
-
-
Save creyke/42e385a9f2f3f475a4b626718df10725 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.Diagnostics.CodeAnalysis; | |
using System.Linq; | |
namespace MarketSort.Solutions | |
{ | |
class SorterE : ISorter | |
{ | |
public IEnumerable<string> Sort(IEnumerable<string> values) | |
{ | |
return values.OrderBy(x => x, new ScoreComparer("-")).ToList(); | |
} | |
class ScoreComparer : IComparer<string> | |
{ | |
private readonly string scoreSeparator; | |
private const int LessThan = -1; | |
private const int EqualTo = 0; | |
private const int GreaterThan = 1; | |
public ScoreComparer(string scoreSeparator) | |
{ | |
this.scoreSeparator = scoreSeparator; | |
} | |
public int Compare([AllowNull] string firstScore, [AllowNull] string secondScore) | |
{ | |
if (!IsScore(firstScore, scoreSeparator)) | |
return LessThan; | |
if (!IsScore(secondScore, scoreSeparator)) | |
return GreaterThan; | |
var firstScoreSplit = SplitStringToIntArray(firstScore, scoreSeparator); | |
var secondScoreSplit = SplitStringToIntArray(secondScore, scoreSeparator); | |
var firstHomeScore = GetHomeScore(firstScoreSplit); | |
var secondHomeScore = GetHomeScore(secondScoreSplit); | |
var firstAwayScore = GetAwayScore(firstScoreSplit); | |
var secondAwayScore = GetAwayScore(secondScoreSplit); | |
var homeScoreComparison = firstHomeScore.CompareTo(secondHomeScore); | |
var awayScoreComparison = firstAwayScore.CompareTo(secondAwayScore); | |
return (homeScoreComparison, awayScoreComparison) switch | |
{ | |
(EqualTo, EqualTo) => EqualTo, | |
(EqualTo, LessThan) => LessThan, | |
(EqualTo, GreaterThan) => GreaterThan, | |
(LessThan, _) => LessThan, | |
(GreaterThan, _) => GreaterThan, | |
(_, _) => GreaterThan | |
}; | |
} | |
private static bool IsScore(string input, string scoreSeparator) | |
{ | |
var splitInput = input.Split(scoreSeparator); | |
return splitInput.Length == 2 | |
&& int.TryParse(splitInput.First(), out _) | |
&& int.TryParse(splitInput.Last(), out _); | |
} | |
private static int[] SplitStringToIntArray(string input, string splitPattern) => input.Split(splitPattern).Select(x => int.Parse(x)).ToArray(); | |
private static int GetHomeScore(int[] splitScore) => splitScore.First(); | |
private static int GetAwayScore(int[] splitScore) => splitScore.Last(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment