Skip to content

Instantly share code, notes, and snippets.

@MiloszKrajewski
Created October 20, 2020 00:01
Show Gist options
  • Save MiloszKrajewski/fb3d2cd6cdcde84c550458cfbed8afc9 to your computer and use it in GitHub Desktop.
Save MiloszKrajewski/fb3d2cd6cdcde84c550458cfbed8afc9 to your computer and use it in GitHub Desktop.
Between (C#)
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