Skip to content

Instantly share code, notes, and snippets.

@WhiteBlackGoose
Last active December 9, 2021 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WhiteBlackGoose/db9b07e5f0161df70dcf353b4536f899 to your computer and use it in GitHub Desktop.
Save WhiteBlackGoose/db9b07e5f0161df70dcf353b4536f899 to your computer and use it in GitHub Desktop.
Parsers and formats a valid sequence of brackets
var r = new Random(110);
ParseValidSeq(new("{aa}[bb(({a}a[(a)(b)(c)(d)])acdsc){sad{a{a{a}}}}][ff({55}aa)][aaa]"));
void ParseValidSeq(StringStepper ss, string prefix = "", Color col = default)
{
Prefix(false);
while (!ss.EOF)
{
if (ss.Current is '{' or '[' or '(')
{
Prefix();
Write(ss.Current, col.Current);
ss.Move();
Console.WriteLine();
ParseValidSeq(ss, prefix + "│ ", col.Inc());
Prefix();
Write(ss.Current, col.Current);
ss.Move();
}
else if (ss.Current is '}' or ']' or ')')
{
return;
}
else
{
Console.Write(ss.Current);
ss.Move();
}
}
void Prefix(bool b = true)
{
var tmp = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.DarkGray;
if (b)
Console.WriteLine();
Console.Write(prefix);
Console.ForegroundColor = tmp;
}
}
static void Write(char c, ConsoleColor col)
{
var tmp = Console.ForegroundColor;
Console.ForegroundColor = col;
Console.Write(c);
Console.ForegroundColor = tmp;
}
struct Color
{
private static readonly ConsoleColor[] cols = new[] { ConsoleColor.Blue, ConsoleColor.Green, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.Magenta };
private int id;
public ConsoleColor Current => cols[id];
public Color Inc() => new Color() { id = (id + 1) % cols.Length };
}
sealed record StringStepper(string Source)
{
private int curr;
public bool EOF => curr == Source.Length;
public char Current => Source[curr];
public void Move() => curr++;
}
{
│ aa
}
[
│ bb
│ (
│ │
│ │ (
│ │ │
│ │ │ {
│ │ │ │ a
│ │ │ }a
│ │ │ [
│ │ │ │
│ │ │ │ (
│ │ │ │ │ a
│ │ │ │ )
│ │ │ │ (
│ │ │ │ │ b
│ │ │ │ )
│ │ │ │ (
│ │ │ │ │ c
│ │ │ │ )
│ │ │ │ (
│ │ │ │ │ d
│ │ │ │ )
│ │ │ ]
│ │ )acdsc
│ )
│ {
│ │ sad
│ │ {
│ │ │ a
│ │ │ {
│ │ │ │ a
│ │ │ │ {
│ │ │ │ │ a
│ │ │ │ }
│ │ │ }
│ │ }
│ }
]
[
│ ff
│ (
│ │
│ │ {
│ │ │ 55
│ │ }aa
│ )
]
[
│ aaa
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment