Skip to content

Instantly share code, notes, and snippets.

@ChinonsoIke
Last active December 29, 2022 11:36
Show Gist options
  • Save ChinonsoIke/86177bf7e447790d460121d7753283a7 to your computer and use it in GitHub Desktop.
Save ChinonsoIke/86177bf7e447790d460121d7753283a7 to your computer and use it in GitHub Desktop.
An algorithm to print a Christmas tree to the console
using System;
using System.Threading;
using System.Text;
public class Program
{
public static void Main()
{
PrintChristmasTree(20);
}
public static void PrintChristmasTree(int height)
{
Console.ForegroundColor = ConsoleColor.Green;
var colors = new ConsoleColor[] {ConsoleColor.Red, ConsoleColor.Yellow, ConsoleColor.Blue};
int middle = Console.WindowWidth/2, indent = middle > 0 ? middle : 50, initialIndent = indent, width = 1, margin = 4;
string str1 = "MERRY CHRISTMAS", str2 = "AND", str3 = "HAPPY HOLIDAYS!";
char[] extras = new char[] { '*', '&', '#', '%', 'O' };
Console.WriteLine();
for (int i = 1; i <= height && indent > margin; i++)
{
var sb = new StringBuilder();
sb.Append($"{new string('^', width)}");
var random = new Random();
if (i == 1) sb[0] = '*';
else sb.Replace('^', extras[random.Next(extras.Length)], random.Next(sb.Length), 1);
Console.Write($"{new string(' ', indent)}");
foreach(char c in sb.ToString())
{
if (c == '^') Console.Write(c);
else
{
Console.ForegroundColor = colors[random.Next(colors.Length)];
Console.Write(c);
Console.ForegroundColor = ConsoleColor.Green;
}
}
indent--;
width += 2;
Console.WriteLine();
Thread.Sleep(200);
}
Console.WriteLine($"{new string(' ', initialIndent-1)}| |");
Console.WriteLine($"{new string(' ', initialIndent-1)}| |");
Thread.Sleep(200);
Console.WriteLine($"{new string(' ', indent)}{new string('~', width)}");
Console.WriteLine($"{new string(' ', indent + ((width-str1.Length))/2)}{str1}");
Console.WriteLine($"{new string(' ', indent + ((width - str2.Length)) / 2)}{str2}");
Console.WriteLine($"{new string(' ', indent + ((width - str3.Length)) / 2)}{str3}");
Thread.Sleep(200);
Console.WriteLine($"{new string(' ', indent)}{new string('~', width)}");
Console.WriteLine($"{new string(' ', indent)}{new string('~', width)}");
}
}
@ChinonsoIke
Copy link
Author

Output

Screenshot (140)

@NfoTECH
Copy link

NfoTECH commented Dec 29, 2022

Beautiful and nicely done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment