Created
October 20, 2020 00:01
-
-
Save MiloszKrajewski/fb3d2cd6cdcde84c550458cfbed8afc9 to your computer and use it in GitHub Desktop.
Between (C#)
This file contains 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
public static string Between(StringBuilder result, string a, string b) | |
{ | |
if (a == b) return a; | |
if (Compare(a, b) >= 0) | |
throw new InvalidOperationException(); | |
var ai = 0; | |
var bi = 0; | |
while (true) | |
{ | |
if (ai >= a.Length) | |
{ | |
(a, ai) = ("a", 0); | |
continue; | |
} | |
if (bi >= b.Length) | |
{ | |
(b, bi) = ("z", 0); | |
continue; | |
} | |
var ac = a[ai]; | |
var bc = b[bi]; | |
var d = Compare(ac, bc); | |
if (d == 0) | |
{ | |
result.Append(ac); | |
ai++; | |
bi++; | |
continue; | |
} | |
if (d <= 1) | |
{ | |
result.Append(ac); | |
ai++; | |
(b, bi) = ("z", 0); | |
continue; | |
} | |
var m = (char) ((ac + bc) / 2); | |
return result.Append(m).ToString(); | |
} | |
} | |
private static char Middle(char ac, char bc) => (char)((ac + bc) / 2); | |
private static int Compare(string a, string b) => string.CompareOrdinal(a, b); | |
private static int Compare(char a, char b) => b - a; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment