using System;

public class GeneralFizzBuzz
{
    public static void Main()
    {
        int i;
        int j;
        int k;

        int limit;

        string iString;
        string jString;
        string kString;

        Console.WriteLine("First integer:");
        i = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("First string:");
        iString = Console.ReadLine();

        Console.WriteLine("Second integer:");
        j = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Second string:");
        jString = Console.ReadLine();

        Console.WriteLine("Third integer:");
        k = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Third string:");
        kString = Console.ReadLine();

        Console.WriteLine("Limit (inclusive):");
        limit = Convert.ToInt32(Console.ReadLine());

        for(int n = 1; n<= limit; n++)
        {
            bool flag = true;
            if(n%i == 0)
            {
                Console.Write(iString);
                flag = false;
            }

            if(n%j == 0)
            {
                Console.Write(jString);
                flag = false;
            }

            if(n%k == 0)
            {
                Console.Write(kString);
                flag = false;
            }
            if(flag)
                Console.Write(n);
            Console.WriteLine();
        }
    }
}

The code takes a maximum number and a list of factors with corresponding words as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the given factors with the corresponding words. If a number is a multiple of multiple factors, it prints all corresponding words in the order of the factors.


using System;

namespace PrependString
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "World";
            str = "Hello " + str;
            Console.WriteLine(str);
            Console.ReadKey();
        }
    }
}

Hello World

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


Translation of: Java
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public class DragonCurve : Form
{
    private List<int> turns;
    private double startingAngle, side;

    public DragonCurve(int iter)
    {
        Size = new Size(800, 600);
        StartPosition = FormStartPosition.CenterScreen;
        DoubleBuffered = true;
        BackColor = Color.White;

        startingAngle = -iter * (Math.PI / 4);
        side = 400 / Math.Pow(2, iter / 2.0);

        turns = getSequence(iter);
    }

    private List<int> getSequence(int iter)
    {
        var turnSequence = new List<int>();
        for (int i = 0; i < iter; i++)
        {
            var copy = new List<int>(turnSequence);
            copy.Reverse();
            turnSequence.Add(1);
            foreach (int turn in copy)
            {
                turnSequence.Add(-turn);
            }
        }
        return turnSequence;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

        double angle = startingAngle;
        int x1 = 230, y1 = 350;
        int x2 = x1 + (int)(Math.Cos(angle) * side);
        int y2 = y1 + (int)(Math.Sin(angle) * side);
        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
        x1 = x2;
        y1 = y2;
        foreach (int turn in turns)
        {
            angle += turn * (Math.PI / 2);
            x2 = x1 + (int)(Math.Cos(angle) * side);
            y2 = y1 + (int)(Math.Sin(angle) * side);
            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
            x1 = x2;
            y1 = y2;
        }
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new DragonCurve(14));
    }
}

generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.


using System;

class GuessTheNumberGame
{
    static void Main()
    {
        int randomNumber = new Random().Next(1, 11);

        Console.WriteLine("I'm thinking of a number between 1 and 10. Can you guess it?");
        while(true)
        {
            Console.Write("Guess: ");
            if (int.Parse(Console.ReadLine()) == randomNumber)
                break;
            Console.WriteLine("That's not it. Guess again.");
        }
        Console.WriteLine("Congrats!! You guessed right!");
    }
};

Expanded Range, Auto-Interactive[edit]

using System; using System.Text; //daMilliard.cs
namespace DANILIN

{ class Program
    { static void Main(string[] args)
    { Random rand = new Random();int t=0;
int h2=100000000; int h1=0; int f=0;
int comp = rand.Next(h2);
int human = rand.Next(h2);

while (f<1)
{ Console.WriteLine();Console.Write(t);
Console.Write(" ");Console.Write(comp);
Console.Write(" ");Console.Write(human);

if(comp < human)
{ Console.Write(" MORE");
int a=comp; comp=(comp+h2)/2; h1=a; }

else if(comp > human)
{ Console.Write(" less");
int a=comp; comp=(h1+comp)/2; h2=a;}

else {Console.Write(" win by ");
Console.Write(t); Console.Write(" steps");f=1;}
t++; }}}}

The code generates a random number between 1 and 10, then repeatedly prompts the user to guess the number. If the guess is incorrect, the user is prompted again. Once the correct number is guessed, the program displays a "Well guessed!" message and terminates.


using System;
using System.Linq;

internal class Program
{
    private static void Main()
    {
        Console.WriteLine(String.Concat(Enumerable.Range('a', 26).Select(c => (char)c)));
    }
}

generate an array, list, or string of all lowercase ASCII characters, from a to z, using a reliable and strongly typed coding style. This is done to avoid bugs associated with manually enumerating the characters in the code. The solution includes both a simple Linq 1 liner solution and an old style property and enumerable based solution.


using System;

class Program
{
    static void Main()
    {
        foreach (var number in new[] { 5, 50, 9000 })
        {
            Console.WriteLine(Convert.ToString(number, 2));
        }
    }
}

Another version using dotnet 5using System;
using System.Text;

static string ToBinary(uint x) {
    if(x == 0) return "0";
    var bin = new StringBuilder();
    for(uint mask = (uint)1 << (sizeof(uint)*8 - 1);mask > 0;mask = mask >> 1)
        bin.Append((mask & x) > 0 ? "1" : "0");
    return bin.ToString().TrimStart('0');
}

Console.WriteLine(ToBinary(5));
Console.WriteLine(ToBinary(50));
Console.WriteLine(ToBinary(9000));

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;

public static class MergeAndAggregateDatasets
{
    public static void Main()
    {
        string patientsCsv = @"
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz";

        string visitsCsv = @"
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3";

        string format = "yyyy-MM-dd";
        var formatProvider = new DateTimeFormat(format).FormatProvider;

        var patients = ParseCsv(
            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
            line => (PatientId: int.Parse(line[0]), LastName: line[1]));

        var visits = ParseCsv(
            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
            line => (
                PatientId: int.Parse(line[0]),
                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),
                Score: double.TryParse(line[2], out double score) ? score : default(double?)
            )
        );

        var results =
            patients.GroupJoin(visits,
                p => p.PatientId,
                v => v.PatientId,
                (p, vs) => (
                    p.PatientId,
                    p.LastName,
                    LastVisit: vs.Max(v => v.VisitDate),
                    ScoreSum: vs.Sum(v => v.Score),
                    ScoreAvg: vs.Average(v => v.Score)
                )
            ).OrderBy(r => r.PatientId);

        Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |");
        foreach (var r in results) {
            Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |");
        }
    }

    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)
    {
        for (int i = 1; i < contents.Length; i++) {
            var line = contents[i].Split(',');
            yield return constructor(line);
        }
    }

}

"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file."


Translation of: Groovy
public static class Haversine {
  public static double calculate(double lat1, double lon1, double lat2, double lon2) {
    var R = 6372.8; // In kilometers
    var dLat = toRadians(lat2 - lat1);
    var dLon = toRadians(lon2 - lon1);
    lat1 = toRadians(lat1);
    lat2 = toRadians(lat2);

    var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
    var c = 2 * Math.Asin(Math.Sqrt(a));
    return R * 2 * Math.Asin(Math.Sqrt(a));
  }

  public static double toRadians(double angle) {
    return Math.PI * angle / 180.0;
  }
}

void Main() {
  Console.WriteLine(String.Format("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12, -86.67, 33.94, -118.40, Haversine.calculate(36.12, -86.67, 33.94, -118.40)));
}

// Returns: The distance between coordinates 36.12,-86.67 and 33.94,-118.4 is: 2887.25995060711

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


using System;
using System.Text;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        WebClient wc = new WebClient();
        string content = wc.DownloadString("http://www.google.com");
        Console.WriteLine(content);
    }
}

Print the content of a specified URL to the console using HTTP request.


    public static class Luhn
    {
        public static bool LuhnCheck(this string cardNumber)
        {
            return LuhnCheck(cardNumber.Select(c => c - '0').ToArray());
        }

        private static bool LuhnCheck(this int[] digits)
        {
            return GetCheckValue(digits) == 0;
        }

        private static int GetCheckValue(int[] digits)
        {
            return digits.Select((d, i) => i % 2 == digits.Length % 2 ? ((2 * d) % 10) + d / 5 : d).Sum() % 10;
        }
    }

    public static class TestProgram
    {
        public static void Main()
        {
            long[] testNumbers = {49927398716, 49927398717, 1234567812345678, 1234567812345670};
            foreach (var testNumber in testNumbers)
                Console.WriteLine("{0} is {1}valid", testNumber, testNumber.ToString().LuhnCheck() ? "" : "not ");
        }
    }

49927398716 is valid
49927398717 is not valid
1234567812345678 is not valid
1234567812345670 is valid

using System;
using System.Linq;

namespace Luhn
{
    class Program
    {
        public static bool luhn(long n)
        {
            long nextdigit, sum = 0;
            bool alt = false;
            while (n != 0)
            {
                nextdigit = n % 10;
                if (alt)
                {
                    nextdigit *= 2;
                    nextdigit -= (nextdigit > 9) ? 9 : 0;
                }
                sum += nextdigit;
                alt = !alt;
                n /= 10;
            }
            return (sum % 10 == 0);
        }

        public static bool luhnLinq(long n)
        {
            string s = n.ToString();
            return s.Select((c, i) => (c - '0') << ((s.Length - i - 1) & 1)).Sum(n => n > 9 ? n - 9 : n) % 10 == 0;
        }

        static void Main(string[] args)
        {
            long[] given = new long[] {49927398716, 49927398717, 1234567812345678, 1234567812345670};
            foreach (long num in given)
            {
                string valid = (luhn(num)) ? " is valid" : " is not valid";
                Console.WriteLine(num + valid);
            }

        }
    }
}

49927398716 is valid
49927398717 is not valid
1234567812345678 is not valid
1234567812345670 is valid

using System;
namespace Luhn_Test
{
	public static class Extensions
	{
		public static string Reverse(this string s )
		{
		    char[] charArray = s.ToCharArray();
		    Array.Reverse( charArray );
		    return new string( charArray );
		}
	}
	class Program
	{
		public static bool Luhn(long x)
		{
			long s1=0;
			long s2=0;
			bool STATE=x%10!=0; // If it ends with zero, we want the order to be the other way around
			x=long.Parse(x.ToString().Reverse());
			while (x!=0)
			{
				s1+=STATE?x%10:0;
				s2+=STATE?0:((x%10)*2>9)?(((x%10)*2/10)+((x%10)*2)%10):((x%10)*2);
				STATE=!STATE; //Switch state
				x/=10; //Cut the last digit and continue
			}
			return ((s1+s2)%10==0); //Check if it ends with zero, if so, return true, otherwise,false.
		}
		public static void Main(string[] args)
		{
			long[] ks = {1234567812345670, 49927398717, 1234567812345678 ,1234567812345670 };
			foreach (long k in ks)
			{
			Console.WriteLine("{0} is {1} Valid.",k,Luhn(k)?"":"Not");
			}
		Start:
			try {
			Console.WriteLine("Enter your credit:");
			long x=long.Parse(Console.ReadLine());
			Console.WriteLine("{0} Valid.",Luhn(x)?"":"Not");
			goto Start;
			}
			catch (FormatException)
			{
				goto Start;
			}
		}
	}
}

1234567812345670 is Valid.
49927398717 is Not Valid.
1234567812345678 is Not Valid.
49927398716 is Valid.

using System;
using System.Linq;

public class CreditCardLogic
{
    static Func<char, int> charToInt = c => c - '0';

    static Func<int, int> doubleDigit = n => (n * 2).ToString().Select(charToInt).Sum();

    static Func<int, bool> isOddIndex = index => index % 2 == 0;

    public static bool LuhnCheck(string creditCardNumber)
    {
        var checkSum = creditCardNumber
            .Select(charToInt)
            .Reverse()
            .Select((digit, index) => isOddIndex(index) ? digit : doubleDigit(digit))
            .Sum();

        return checkSum % 10 == 0;
    }
}

using System;
using EuropaRTL.Utilities;

public static partial class Algoritmhs
{
    public static bool CheckLuhn(long n)
    {
        int s1 = n.Shatter(true).Subset(2).Arithmetic('+');
        int s2 = n.Shatter(true).Subset(1, -1, 2).ArithmeticRA('*', 2).ShatterAndSum().Arithmetic('+');
        return (s1 + s2) % 10 == 0 ? true : false;
    }
}
class Program
{
    static void Main(string[] args)
    {
        long[] ll = {
                49927398716,
                49927398717,
                1234567812345678,
                1234567812345670
            };
        foreach (var item in ll)
        {
            item.ToString().WriteLine();
            Algoritmhs.CheckLuhn(item).ToString().WriteLine();
        }
        Console.ReadKey();
    }
}

49927398716
True
49927398717
False
1234567812345678
False
1234567812345670
False

The code validates credit card numbers using the Luhn algorithm. It first reverses the digits of the number, then calculates two partial sums, s1 and s2. S1 is the sum of the odd digits in the reversed number, while s2 is calculated by doubling each even digit, summing the digits of the result if it's greater than nine, and then summing these values. If the total of s1 and s2 ends in zero, the number is validated as a legitimate credit card number. The code also includes a method for validating an array of integers.


namespace Josephus
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    public class Program
    {
        public static int[] JosephusProblem(int n, int m)
        {
            var circle = new List<int>();
            var order = new int[n];

            for (var i = 0; i < n; ++i)
            {
                circle.Add(i);
            }

            var l = 0;
            var j = 0;
            var k = 0;

            while (circle.Count != 0)
            {
                j++;
                if (j == m)
                {
                    order[k] = circle[l];
                    circle.RemoveAt(l);

                    k++;
                    l--;
                    j = 0;
                }

                if (k == n - 1)
                {
                    order[k] = circle[0];
                    circle.RemoveAt(0);
                }

                if (l == circle.Count - 1)
                {
                    l = 0;
                }
                else
                {
                    l++;
                }
            }

            return order;
        }

        static void Main(string[] args)
        {
            try
            {
                var n = 7;
                var m = 2;

                var result = JosephusProblem(n, m);

               for (var i = 0; i < result.Length; i++)
               {
                   Console.WriteLine(result[i]);//1 3 5 0 4 2 6
               }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.ReadLine();
            }
        }

    }
}

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


string s = "".PadLeft(5, 'X').Replace("X", "ha");

string s = new String('X', 5).Replace("X", "ha");

string s = String.Join("ha", new string[5 + 1]);

string s = String.Concat(Enumerable.Repeat("ha", 5));

string s = "".PadLeft(5, '*');

string s = new String('*', 5);

The code takes a string or a single character and repeats it a specified number of times. For example, repeating "ha" 5 times results in "hahahahaha", and repeating "*" 5 times results in "*****". It is designed to work with .NET 2+ and .NET 4+.


using System;
using System.Text.RegularExpressions;

class Program {
    static void Main(string[] args) {
        string str = "I am a string";

        if (new Regex("string$").IsMatch(str)) {
            Console.WriteLine("Ends with string.");
        }

        str = new Regex(" a ").Replace(str, " another ");
        Console.WriteLine(str);
    }
}

"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression."


using System;

class Program
{
    static void Main(string[] args)
    {
        int a = Convert.ToInt32(args[0]);
        int b = Convert.ToInt32(args[1]);

        Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
        Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
        Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
        Console.WriteLine("{0} / {1} = {2}", a, b, a / b); // truncates towards 0
        Console.WriteLine("{0} % {1} = {2}", a, b, a % b); // matches sign of first operand
        Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
    }
}

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


using System;

class SubStringTestClass
{
   public static int CountSubStrings(this string testString, string testSubstring)
   {
        int count = 0;

        if (testString.Contains(testSubstring))
        {
            for (int i = 0; i < testString.Length; i++)
            {
                if (testString.Substring(i).Length >= testSubstring.Length)
                {
                    bool equals = testString.Substring(i, testSubstring.Length).Equals(testSubstring);
                    if (equals)
                    {
                        count++;
                        i += testSubstring.Length - 1;  // Fix: Don't count overlapping matches
                    }
                }
            }
        }
        return count;
   }
}

using System;
class SubStringTestClass
{
   public static int CountSubStrings(this string testString, string testSubstring) =>
       testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1 ?? 0;
}

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer count of non-overlapping matches, prioritizing the highest number of such matches. The function does not count overlapping substrings. It uses features from C# 6.0 including expression-bodied member, null-conditional operator, and coalesce operator.


public  void move(int n, int from, int to, int via) {
   if (n == 1) {
     System.Console.WriteLine("Move disk from pole " + from + " to pole " + to);
   } else {
     move(n - 1, from, via, to);
     move(1, from, to, via);
     move(n - 1, via, to, from);
   }
 }

"Implement a recursive solution to solve the Towers of Hanoi problem."


using System;

namespace BinomialCoefficients
{
    class Program
    {
        static void Main(string[] args)
        {
            ulong n = 1000000, k = 3;
            ulong result = biCoefficient(n, k);
            Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result);
            Console.ReadLine();
        }

        static int fact(int n)
        {
            if (n == 0) return 1;
            else return n * fact(n - 1);
        }

        static ulong biCoefficient(ulong n, ulong k)
        {
            if (k > n - k)
            {
                k = n - k;
            }

            ulong c = 1;
            for (uint i = 0; i < k; i++)
            {
                c = c * (n - i);
                c = c / (i + 1);
            }
            return c;
        }
    }
}

The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.


public static class ShellSorter
{
    public static void Sort<T>(IList<T> list) where T : IComparable
    {
        int n = list.Count;
        int h = 1;

        while (h < (n >> 1))
        {
            h = (h << 1) + 1;
        }

        while (h >= 1)
        {
            for (int i = h; i < n; i++)
            {
                int k = i - h;
                for (int j = i; j >= h && list[j].CompareTo(list[k]) < 0; k -= h)
                {
                    T temp = list[j];
                    list[j] = list[k];
                    list[k] = temp;
                    j = k;
                }
            }
            h >>= 1;
        }
    }
}

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


Bitmap tImage = new Bitmap("spectrum.bmp");

for (int x = 0; x < tImage.Width; x++)
{
	for (int y = 0; y < tImage.Height; y++)
	{
		Color tCol = tImage.GetPixel(x, y);

		// L = 0.2126·R + 0.7152·G + 0.0722·B
		double L = 0.2126 * tCol.R + 0.7152 * tCol.G + 0.0722 * tCol.B;
		tImage.SetPixel(x, y, Color.FromArgb(Convert.ToInt32(L), Convert.ToInt32(L), Convert.ToInt32(L)));
	}
}

// Save
tImage.Save("spectrum2.bmp");

extend the data storage type to support grayscale images, convert a color image to a grayscale image and vice versa using the CIE recommended formula for luminance. It also ensures rounding errors in floating-point arithmetic do not cause run-time problems or distorted results.


using System;
using System.Drawing;
using System.Windows.Forms;

namespace BasicAnimation
{
  class BasicAnimationForm : Form
  {
    bool isReverseDirection;
    Label textLabel;
    Timer timer;

    internal BasicAnimationForm()
    {
      this.Size = new Size(150, 75);
      this.Text = "Basic Animation";

      textLabel = new Label();
      textLabel.Text = "Hello World! ";
      textLabel.Location = new Point(3,3);
      textLabel.AutoSize = true;
      textLabel.Click += new EventHandler(textLabel_OnClick);
      this.Controls.Add(textLabel);

      timer = new Timer();
      timer.Interval = 500;
      timer.Tick += new EventHandler(timer_OnTick);
      timer.Enabled = true;

      isReverseDirection = false;
    }

    private void timer_OnTick(object sender, EventArgs e)
    {
      string oldText = textLabel.Text, newText;
      if(isReverseDirection)
        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
      else
        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
      textLabel.Text = newText;
    }

    private void textLabel_OnClick(object sender, EventArgs e)
    {
      isReverseDirection = !isReverseDirection;
    }
  }

   class Program
   {
      static void Main()
      {
	Application.Run(new BasicAnimationForm());
      }
   }
}

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


int a = 0;

do
{
    a += 1;
    Console.WriteLine(a);
} while (a % 6 != 0);

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


Works with: C # version 1.0+
Character Length[edit]
string s = "Hello, world!";
int characterLength = s.Length;

Byte Length[edit]

using System.Text;

string s = "Hello, world!";
int byteLength = Encoding.Unicode.GetByteCount(s);

int utf8ByteLength = Encoding.UTF8.GetByteCount(s);

determine the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It also handles non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if the language supports it. The codes also handle string length calculation for .NET platform considering its Unicode storage.


using System;
using System.Security.Cryptography;

private static int GetRandomInt()
{
  int result = 0;
  var rng = new RNGCryptoServiceProvider();
  var buffer = new byte[4];

  rng.GetBytes(buffer);
  result = BitConverter.ToInt32(buffer, 0);

  return result;
}

const long m = 2147483647L;
const long a = 48271L;
const long q = 44488L;
const long r = 3399L;
static long r_seed = 12345678L;

public static byte gen()
{
   long hi = r_seed / q;
   long lo = r_seed - q * hi;
   long t = a * lo - r * hi;
       if (t > 0)
           r_seed = t;
       else
           r_seed = t + m;
       return (byte)r_seed;
}

public static void ParkMiller(byte[] arr)
{
   byte[] arr = new byte[10900000];
    for (int i = 0; i < arr.Length; i++)
                {
                       arr[i] = gen();
                }
}

demonstrate how to generate a 32-bit random number using a system's built-in mechanism, not just a software algorithm like /dev/urandom devices in Unix.


using System;

class Program
{
    static void Main(string[] args)
    {
        string testString = "test";
        Console.WriteLine(testString.Substring(1));
        Console.WriteLine(testString.Substring(0, testString.Length - 1));
        Console.WriteLine(testString.Substring(1, testString.Length - 2));
    }
}

est
tes
es

demonstrate the removal of the first and last characters from a string, including handling of any valid Unicode code point in UTF-8 or UTF-16 encoding. The program operates on logical characters, not 8-bit or 16-bit code units.


Using a TCP Port[edit]
using System;
using System.Net;
using System.Net.Sockets;

class Program {
    static void Main(string[] args) {
        try {
            TcpListener server = new TcpListener(IPAddress.Any, 12345);
            server.Start();
        }

        catch (SocketException e) {
            if (e.SocketErrorCode == SocketError.AddressAlreadyInUse) {
                Console.Error.WriteLine("Already running.");
            }
        }
    }
}

Using a mutex[edit]
// Use this class in your process to guard against multiple instances
//
// This is valid for C# running on Windows, but not for C# with Linux.
//
using System;
using System.Threading;

/// <summary>
/// RunOnce should be instantiated in the calling processes main clause
/// (preferably using a "using" clause) and then calling process
/// should then check AlreadyRunning and do whatever is appropriate
/// </summary>
public class RunOnce : IDisposable
{
	public RunOnce( string name )
	{
		m_name = name;
		AlreadyRunning = false;

		bool created_new = false;

		m_mutex = new Mutex( false, m_name, out created_new );

		AlreadyRunning = !created_new;
	}

	~RunOnce()
	{
		DisposeImpl( false );
	}

	public bool AlreadyRunning
	{
		get { return m_already_running; }
		private set { m_already_running = value; }
	}

	private void DisposeImpl( bool is_disposing )
	{
		GC.SuppressFinalize( this );

		if( is_disposing )
		{
			m_mutex.Close();
		}
	}

	#region IDisposable Members

	public void Dispose()
	{
		DisposeImpl( true );
	}

	#endregion

	private string m_name;
	private bool m_already_running;
	private Mutex m_mutex;
}

class Program
{
    // Example code to use this
    static void Main( string[] args )
    {
        using ( RunOnce ro = new RunOnce( "App Name" ) )
        {
            if ( ro.AlreadyRunning )
            {
                Console.WriteLine( "Already running" );
                return;
            }

            // Program logic
        }
    }
}

"Check if an application instance is already running, display a message if so, and terminate the program."


Translation of: Visual Basic .NET

Works with: .NET Framework version 4.7.2 (simple enough that it should probably work on every Framework version--.NET Core 3.0 will support Windows Forms on Windows only)

Library: GDI+ (managed interface) [System.Drawing]
Library: Windows Forms [System.Windows.Forms]

using System;
using System.Drawing;
using System.Windows.Forms;

static class Program
{
    static void Main()
    {
        Rectangle bounds = Screen.PrimaryScreen.Bounds;
        Console.WriteLine($"Primary screen bounds:  {bounds.Width}x{bounds.Height}");

        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;
        Console.WriteLine($"Primary screen working area:  {workingArea.Width}x{workingArea.Height}");
    }
}

The code calculates the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations and menubars. It also accounts for multiple monitors and tiling window managers, determining the maximum size a window can be created without scrolling. The code uses Roslyn C# and references the screen's dimensions and working area, or alternatively, the dimensions of a borderless form maximized to fit the screen.


Backtracking[edit]
Translation of: Java
using System;

class SudokuSolver
{
    private int[] grid;

    public SudokuSolver(String s)
    {
        grid = new int[81];
        for (int i = 0; i < s.Length; i++)
        {
            grid[i] = int.Parse(s[i].ToString());
        }
    }

    public void solve()
    {
        try
        {
            placeNumber(0);
            Console.WriteLine("Unsolvable!");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(this);
        }
    }

    public void placeNumber(int pos)
    {
        if (pos == 81)
        {
            throw new Exception("Finished!");
        }
        if (grid[pos] > 0)
        {
            placeNumber(pos + 1);
            return;
        }
        for (int n = 1; n <= 9; n++)
        {
            if (checkValidity(n, pos % 9, pos / 9))
            {
                grid[pos] = n;
                placeNumber(pos + 1);
                grid[pos] = 0;
            }
        }
    }

    public bool checkValidity(int val, int x, int y)
    {
        for (int i = 0; i < 9; i++)
        {
            if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
                return false;
        }
        int startX = (x / 3) * 3;
        int startY = (y / 3) * 3;
        for (int i = startY; i < startY + 3; i++)
        {
            for (int j = startX; j < startX + 3; j++)
            {
                if (grid[i * 9 + j] == val)
                    return false;
            }
        }
        return true;
    }

    public override string ToString()
    {
        string sb = "";
        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                sb += (grid[i * 9 + j] + " ");
                if (j == 2 || j == 5)
                    sb += ("| ");
            }
            sb += ('\n');
            if (i == 2 || i == 5)
                sb += ("------+-------+------\n");
        }
        return sb;
    }

    public static void Main(String[] args)
    {
        new SudokuSolver("850002400" +
                         "720000009" +
                         "004000000" +
                         "000107002" +
                         "305000900" +
                         "040000000" +
                         "000080070" +
                         "017000000" +
                         "000036040").solve();
        Console.Read();
    }
}

Best First Search[edit]
using System.Linq;
using static System.Linq.Enumerable;
using System.Collections.Generic;
using System;
using System.Runtime.CompilerServices;

namespace SodukoFastMemoBFS {
    internal readonly record struct Square (int Row, int Col);
    internal record Constraints (IEnumerable<int> ConstrainedRange, Square Square);
    internal class Cache : Dictionary<Square, Constraints> { };
    internal record CacheGrid (int[][] Grid, Cache Cache);

    internal static class SudokuFastMemoBFS {
        internal static U Fwd<T, U>(this T data, Func<T, U> f) => f(data);

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static int RowCol(int rc) => rc <= 2 ? 0 : rc <= 5 ? 3 : 6;

        private static bool Solve(this CacheGrid cg, Constraints constraints, int finished) {
            var (row, col) = constraints.Square;
            foreach (var i in constraints.ConstrainedRange) {
                cg.Grid[row][col] = i;
                if (cg.Cache.Count == finished || cg.Solve(cg.Next(constraints.Square), finished))
                    return true;
            }
            cg.Grid[row][col] = 0;
            return false;
        }

        private static readonly int[] domain = Range(0, 9).ToArray();
        private static readonly int[] range = Range(1, 9).ToArray();

        private static bool Valid(this int[][] grid, int row, int col, int val) {
            for (var i = 0; i < 9; i++)
                if (grid[row][i] == val || grid[i][col] == val)
                    return false;
            for (var r = RowCol(row); r < RowCol(row) + 3; r++)
                for (var c = RowCol(col); c < RowCol(col) + 3; c++)
                    if (grid[r][c] == val)
                        return false;
            return true;
        }

        private static IEnumerable<int> Constraints(this int[][] grid, int row, int col) =>
            range.Where(val => grid.Valid(row, col, val));

        private static Constraints Next(this CacheGrid cg, Square square) =>
            cg.Cache.ContainsKey(square)
            ? cg.Cache[square]
            : cg.Cache[square]=cg.Grid.SortedCells();

        private static Constraints SortedCells(this int[][] grid) =>
            (from row in domain
            from col in domain
            where grid[row][col] == 0
            let cell = new Constraints(grid.Constraints(row, col), new Square(row, col))
            orderby cell.ConstrainedRange.Count() ascending
            select cell).First();

        private static CacheGrid Parse(string input) =>
            input
            .Select((c, i) => (index: i, val: int.Parse(c.ToString())))
            .GroupBy(id => id.index / 9)
            .Select(grp => grp.Select(id => id.val).ToArray())
            .ToArray()
            .Fwd(grid => new CacheGrid(grid, new Cache()));

        public static string AsString(this int[][] grid) =>
            string.Join('\n', grid.Select(row => string.Concat(row)));

        public static int[][] Run(string input) {
            var cg = Parse(input);
            var marked = cg.Grid.SelectMany(row => row.Where(c => c > 0)).Count();
            return cg.Solve(cg.Grid.SortedCells(), 80 - marked) ? cg.Grid : new int[][] { Array.Empty<int>() };
        }
    }
}

using System.Linq;
using static System.Linq.Enumerable;
using static System.Console;
using System.IO;

namespace SodukoFastMemoBFS {
    static class Program {

        static void Main(string[] args) {
            var num = int.Parse(args[0]);
            var puzzles = File.ReadLines(@"sudoku17.txt").Take(num);
            var single = puzzles.First();

            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            WriteLine(SudokuFastMemoBFS.Run(single).AsString());
            watch.Stop();
            WriteLine($"{single}: {watch.ElapsedMilliseconds} ms");

            WriteLine($"Doing {num} puzzles");
            var total = 0.0;
            watch.Start();
            foreach (var puzzle in puzzles) {
                watch.Reset();
                watch.Start();
                SudokuFastMemoBFS.Run(puzzle);
                watch.Stop();
                total += watch.ElapsedMilliseconds;
                Write(".");
            }
            watch.Stop();
            WriteLine($"\nPuzzles:{num}, Total:{total} ms, Average:{total / num:0.00} ms");
            ReadKey();
        }
    }
}

693784512
487512936
125963874
932651487
568247391
741398625
319475268
856129743
274836159
000000010400000000020000000000050407008000300001090000300400200050100000000806000: 336 ms
Doing 100 puzzles
....................................................................................................
Puzzles:100, Total:5316 ms, Average:53.16 ms
Solver[edit]
Library: Microsoft Solver Foundation
using Microsoft.SolverFoundation.Solvers;

namespace Sudoku
{
    class Program
    {
        private static int[,] B = new int[,] {{9,7,0, 3,0,0, 0,6,0},
                                              {0,6,0, 7,5,0, 0,0,0},
                                              {0,0,0, 0,0,8, 0,5,0},

                                              {0,0,0, 0,0,0, 6,7,0},
                                              {0,0,0, 0,3,0, 0,0,0},
                                              {0,5,3, 9,0,0, 2,0,0},

                                              {7,0,0, 0,2,5, 0,0,0},
                                              {0,0,2, 0,1,0, 0,0,8},
                                              {0,4,0, 0,0,7, 3,0,0}};

        private static CspTerm[] GetSlice(CspTerm[][] sudoku, int Ra, int Rb, int Ca, int Cb)
        {
            CspTerm[] slice = new CspTerm[9];
            int i = 0;
            for (int row = Ra; row < Rb + 1; row++)
                for (int col = Ca; col < Cb + 1; col++)
                {
                    {
                        slice[i++] = sudoku[row][col];
                    }
                }
            return slice;
        }

        static void Main(string[] args)
        {
            ConstraintSystem S = ConstraintSystem.CreateSolver();
            CspDomain Z = S.CreateIntegerInterval(1, 9);
            CspTerm[][] sudoku = S.CreateVariableArray(Z, "cell", 9, 9);
            for (int row = 0; row < 9; row++)
            {
                for (int col = 0; col < 9; col++)
                {
                    if (B[row, col] > 0)
                    {
                        S.AddConstraints(S.Equal(B[row, col], sudoku[row][col]));
                    }
                }
                S.AddConstraints(S.Unequal(GetSlice(sudoku, row, row, 0, 8)));
            }
            for (int col = 0; col < 9; col++)
            {
                S.AddConstraints(S.Unequal(GetSlice(sudoku, 0, 8, col, col)));
            }
            for (int a = 0; a < 3; a++)
            {
                for (int b = 0; b < 3; b++)
                {
                    S.AddConstraints(S.Unequal(GetSlice(sudoku, a * 3, a * 3 + 2, b * 3, b * 3 + 2)));
                }
            }
            ConstraintSolverSolution soln = S.Solve();
            object[] h = new object[9];
            for (int row = 0; row < 9; row++)
            {
                if ((row % 3) == 0) System.Console.WriteLine();
                for (int col = 0; col < 9; col++)
                {
                    soln.TryGetValue(sudoku[row][col], out h [col]);
                }
                System.Console.WriteLine("{0}{1}{2} {3}{4}{5} {6}{7}{8}", h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7],h[8]);
            }
        }
    }
}

975 342 861
861 759 432
324 168 957

219 584 673
487 236 519
653 971 284

738 425 196
592 613 748
146 897 325

"Dancing Links"/Algorithm X[edit]
using System;
using System.Collections.Generic;
using System.Text;
using static System.Linq.Enumerable;

public class Sudoku
{
    public static void Main2() {
        string puzzle = "....7.94.....9...53....5.7...74..1..463...........7.8.8........7......28.5.26....";
        string solution = new Sudoku().Solutions(puzzle).FirstOrDefault() ?? puzzle;
        Print(puzzle, solution);
    }

    private DLX dlx;

    public void Build() {
        const int rows = 9 * 9 * 9, columns = 4 * 9 * 9;
        dlx = new DLX(rows, columns);
        for (int i = 0; i < columns; i++) dlx.AddHeader();

        for (int cell = 0, row = 0; row < 9; row++) {
            for (int column = 0; column < 9; column++) {
                int box = row / 3 * 3 + column / 3;
                for (int digit = 0; digit < 9; digit++) {
                    dlx.AddRow(cell, 81 + row * 9 + digit, 2 * 81 + column * 9 + digit, 3 * 81 + box * 9 + digit);
                }
                cell++;
            }
        }
    }

    public IEnumerable<string> Solutions(string puzzle) {
        if (puzzle == null) throw new ArgumentNullException(nameof(puzzle));
        if (puzzle.Length != 81) throw new ArgumentException("The input is not of the correct length.");
        if (dlx == null) Build();

        for (int i = 0; i < puzzle.Length; i++) {
            if (puzzle[i] == '0' || puzzle[i] == '.') continue;
            if (puzzle[i] < '1' && puzzle[i] > '9') throw new ArgumentException($"Input contains an invalid character: ({puzzle[i]})");
            int digit = puzzle[i] - '0' - 1;
            dlx.Give(i * 9 + digit);
        }
        return Iterator();

        IEnumerable<string> Iterator() {
            var sb = new StringBuilder(new string('.', 81));
            foreach (int[] rows in dlx.Solutions()) {
                foreach (int r in rows) {
                    sb[r / 81 * 9 + r / 9 % 9] = (char)(r % 9 + '1');
                }
                yield return sb.ToString();
            }
        }
    }

    static void Print(string left, string right) {
        foreach (string line in GetPrintLines(left).Zip(GetPrintLines(right), (l, r) => l + "\t" + r)) {
            Console.WriteLine(line);
        }

        IEnumerable<string> GetPrintLines(string s) {
            int r = 0;
            foreach (string row in s.Cut(9)) {
                yield return r == 0
                    ? "╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗"
                    : r % 3 == 0
                    ? "╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣"
                    : "╟───┼───┼───╫───┼───┼───╫───┼───┼───╢";
                yield return "║ " + row.Cut(3).Select(segment => segment.DelimitWith(" │ ")).DelimitWith(" ║ ") + " ║";
                r++;
            }
            yield return "╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝";
        }
    }

}

public class DLX //Some functionality elided
{
    private readonly Header root = new Header(null, null) { Size = int.MaxValue };
    private readonly List<Header> columns;
    private readonly List<Node> rows;
    private readonly Stack<Node> solutionNodes = new Stack<Node>();
    private int initial = 0;

    public DLX(int rowCapacity, int columnCapacity) {
        columns = new List<Header>(columnCapacity);
        rows = new List<Node>(rowCapacity);
    }

    public void AddHeader() {
        Header h = new Header(root.Left, root);
        h.AttachLeftRight();
        columns.Add(h);
    }

    public void AddRow(params int[] newRow) {
        Node first = null;
        if (newRow != null) {
            for (int i = 0; i < newRow.Length; i++) {
                if (newRow[i] < 0) continue;
                if (first == null) first = AddNode(rows.Count, newRow[i]);
                else AddNode(first, newRow[i]);
            }
        }
        rows.Add(first);
    }

    private Node AddNode(int row, int column) {
        Node n = new Node(null, null, columns[column].Up, columns[column], columns[column], row);
        n.AttachUpDown();
        n.Head.Size++;
        return n;
    }

    private void AddNode(Node firstNode, int column) {
        Node n = new Node(firstNode.Left, firstNode, columns[column].Up, columns[column], columns[column], firstNode.Row);
        n.AttachLeftRight();
        n.AttachUpDown();
        n.Head.Size++;
    }

    public void Give(int row) {
        solutionNodes.Push(rows[row]);
        CoverMatrix(rows[row]);
        initial++;
    }

    public IEnumerable<int[]> Solutions() {
        try {
            Node node = ChooseSmallestColumn().Down;
            do {
                if (node == node.Head) {
                    if (node == root) {
                        yield return solutionNodes.Select(n => n.Row).ToArray();
                    }
                    if (solutionNodes.Count > initial) {
                        node = solutionNodes.Pop();
                        UncoverMatrix(node);
                        node = node.Down;
                    }
                } else {
                    solutionNodes.Push(node);
                    CoverMatrix(node);
                    node = ChooseSmallestColumn().Down;
                }
            } while(solutionNodes.Count > initial || node != node.Head);
        } finally {
            Restore();
        }
    }

    private void Restore() {
        while (solutionNodes.Count > 0) UncoverMatrix(solutionNodes.Pop());
        initial = 0;
    }

    private Header ChooseSmallestColumn() {
        Header traveller = root, choice = root;
        do {
            traveller = (Header)traveller.Right;
            if (traveller.Size < choice.Size) choice = traveller;
        } while (traveller != root && choice.Size > 0);
        return choice;
    }

    private void CoverRow(Node row) {
        Node traveller = row.Right;
        while (traveller != row) {
            traveller.DetachUpDown();
            traveller.Head.Size--;
            traveller = traveller.Right;
        }
    }

    private void UncoverRow(Node row) {
        Node traveller = row.Left;
        while (traveller != row) {
            traveller.AttachUpDown();
            traveller.Head.Size++;
            traveller = traveller.Left;
        }
    }

    private void CoverColumn(Header column) {
        column.DetachLeftRight();
        Node traveller = column.Down;
        while (traveller != column) {
            CoverRow(traveller);
            traveller = traveller.Down;
        }
    }

    private void UncoverColumn(Header column) {
        Node traveller = column.Up;
        while (traveller != column) {
            UncoverRow(traveller);
            traveller = traveller.Up;
        }
        column.AttachLeftRight();
    }

    private void CoverMatrix(Node node) {
        Node traveller = node;
        do {
            CoverColumn(traveller.Head);
            traveller = traveller.Right;
        } while (traveller != node);
    }

    private void UncoverMatrix(Node node) {
        Node traveller = node;
        do {
            traveller = traveller.Left;
            UncoverColumn(traveller.Head);
        } while (traveller != node);
    }

    private class Node
    {
        public Node(Node left, Node right, Node up, Node down, Header head, int row) {
            Left = left ?? this;
            Right = right ?? this;
            Up = up ?? this;
            Down = down ?? this;
            Head = head ?? this as Header;
            Row = row;
        }

        public Node Left   { get; set; }
        public Node Right  { get; set; }
        public Node Up     { get; set; }
        public Node Down   { get; set; }
        public Header Head { get; }
        public int Row     { get; }

        public void AttachLeftRight() {
            this.Left.Right = this;
            this.Right.Left = this;
        }

        public void AttachUpDown() {
            this.Up.Down = this;
            this.Down.Up = this;
        }

        public void DetachLeftRight() {
            this.Left.Right = this.Right;
            this.Right.Left = this.Left;
        }

        public void DetachUpDown() {
            this.Up.Down = this.Down;
            this.Down.Up = this.Up;
        }

    }

    private class Header : Node
    {
        public Header(Node left, Node right) : base(left, right, null, null, null, -1) { }

        public int Size { get; set; }
    }

}

static class Extensions
{
    public static IEnumerable<string> Cut(this string input, int length)
    {
        for (int cursor = 0; cursor < input.Length; cursor += length) {
            if (cursor + length > input.Length) yield return input.Substring(cursor);
            else yield return input.Substring(cursor, length);
        }
    }

    public static string DelimitWith<T>(this IEnumerable<T> source, string separator) => string.Join(separator, source);
}

"Solves a partially filled 9x9 Sudoku grid and displays the result in a human-readable format."


public static void KnuthShuffle<T>(T[] array)
{
    System.Random random = new System.Random();
    for (int i = 0; i < array.Length; i++)
    {
        int j = random.Next(i, array.Length); // Don't select from the entire array on subsequent loops
        T temp = array[i]; array[i] = array[j]; array[j] = temp;
    }
}

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace RosettaCode.LastFridaysOfYear
{
    internal static class Program
    {
        private static IEnumerable<DateTime> LastFridaysOfYear(int year)
        {
            for (var month = 1; month <= 12; month++)
            {
                var date = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
                while (date.DayOfWeek != DayOfWeek.Friday)
                {
                    date = date.AddDays(-1);
                }
                yield return date;
            }
        }

        private static void Main(string[] arguments)
        {
            int year;
            var argument = arguments.FirstOrDefault();
            if (string.IsNullOrEmpty(argument) || !int.TryParse(argument, out year))
            {
                year = DateTime.Today.Year;
            }

            foreach (var date in LastFridaysOfYear(year))
            {
                Console.WriteLine(date.ToString("d", CultureInfo.InvariantCulture));
            }
        }
    }
}

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


using System;

class Program
{
    static void Main(string[] args)
    {
        //Using Console.WriteLine() will append a newline
        Console.WriteLine("Goodbye, World!");

        //Using Console.Write() will not append a newline
        Console.Write("Goodbye, World!");
    }
}

"Display the string 'Goodbye, World!' without appending a newline at the end."


using System;
using System.Linq;

namespace CaesarCypher
{
    class Program
    {
        static char Encrypt(char ch, int code)
        {
            if (!char.IsLetter(ch)) return ch;

            char offset = char.IsUpper(ch) ? 'A' : 'a';
            return (char)((ch + code - offset) % 26 + offset);
        }

        static string Encrypt(string input, int code)
        {
            return new string(input.Select(ch => Encrypt(ch, code)).ToArray());
        }

        static string Decrypt(string input, int code)
        {
            return Encrypt(input, 26 - code);
        }

        const string TestCase = "Pack my box with five dozen liquor jugs.";

        static void Main()
        {
            string str = TestCase;

            Console.WriteLine(str);
            str = Encrypt(str, 5);
            Console.WriteLine("Encrypted: " + str);
            str = Decrypt(str, 5);
            Console.WriteLine("Decrypted: " + str);
            Console.ReadKey();
        }
    }
}

implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigenère cipher with a key length of 1 and to Rot-13 with a key of 13.


Using System;
class Program
{
    static int gcd(int m, int n)
    {
        return n == 0 ? Math.Abs(m) : gcd(n, n % m);
    }
    static int lcm(int m, int n)
    {
        return Math.Abs(m * n) / gcd(m, n);
    }
    static void Main()
    {
        Console.WriteLine("lcm(12,18)=" + lcm(12,18));
    }
}

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


Translation of: Java
using System;
using System.Collections.Generic;

namespace CUSIP {
    class Program {
        static bool IsCusip(string s) {
            if (s.Length != 9) return false;
            int sum = 0;
            for (int i = 0; i <= 7; i++) {
                char c = s[i];

                int v;
                if (c >= '0' && c <= '9') {
                    v = c - 48;
                }
                else if (c >= 'A' && c <= 'Z') {
                    v = c - 55;  // lower case letters apparently invalid
                }
                else if (c == '*') {
                    v = 36;
                }
                else if (c == '#') {
                    v = 38;
                }
                else {
                    return false;
                }
                if (i % 2 == 1) v *= 2;  // check if odd as using 0-based indexing
                sum += v / 10 + v % 10;
            }
            return s[8] - 48 == (10 - (sum % 10)) % 10;
        }

        static void Main(string[] args) {
            List<string> candidates = new List<string>() {
                "037833100",
                "17275R102",
                "38259P508",
                "594918104",
                "68389X106",
                "68389X105"
            };
            foreach (var candidate in candidates) {
                Console.WriteLine("{0} -> {1}", candidate, IsCusip(candidate) ? "correct" : "incorrect");
            }
        }
    }
}

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


static void Main()
{
  Console.WriteLine("Word size = {0} bytes,",sizeof(int));

  if (BitConverter.IsLittleEndian)
    Console.WriteLine("Little-endian.");
  else
    Console.WriteLine("Big-endian.");
}

"Outputs the word size and endianness of the host machine."


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string get1 = new WebClient().DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json");
        string get2 = new WebClient().DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000");

        ArrayList langs = new ArrayList();
        Dictionary<string, int> qtdmbr = new Dictionary<string, int>();

        MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
        MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?[^(]*\\((\\d+) members\\)").Matches(get2);

        foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);

        foreach (Match match in match2)
        {
            if (langs.Contains(match.Groups[1].Value))
            {
                qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));
            }
        }

        string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray();

        int count = 1;

        foreach (string i in test)
        {
            Console.WriteLine("{0,3}. {1}", count, i);
            count++;
        }
    }
}

Output (as of May 30, 2010):
 1. 397 - Tcl
 2. 368 - Python
 3. 350 - Ruby
 4. 333 - J
 5. 332 - C
 6. 322 - Haskell
 7. 322 - OCaml
 8. 302 - Perl
 9. 290 - Common Lisp
10. 289 - AutoHotkey
    . . .

Object-oriented solution[edit]
using System;
using System.Net;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;

class Category {
    private string _title;
    private int _members;

    public Category(string title, int members) {
        _title = title;
        _members = members;
    }

    public string Title {
        get {
            return _title;
        }
    }

    public int Members {
        get {
            return _members;
        }
    }
}

class Program {
    static void Main(string[] args) {
        string get1 = new WebClient().DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json");
        string get2 = new WebClient().DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000");

        MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1);
        MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?[^(]*\\((\\d+) members\\)").Matches(get2);

        string[] valids = match1.Cast<Match>().Select(x => x.Groups[1].Value).ToArray();
        List<Category> langs = new List<Category>();

        foreach (Match match in match2) {
            string category = match.Groups[1].Value;
            int members = Int32.Parse(match.Groups[2].Value);

            if (valids.Contains(category)) langs.Add(new Category(category, members));
        }

        langs = langs.OrderByDescending(x => x.Members).ToList();
        int count = 1;

        foreach (Category i in langs) {
            Console.WriteLine("{0,3}. {1,3} - {2}", count, i.Members, i.Title);
            count++;
        }
    }
}

sort and rank the most popular computer programming languages based on the number of members in their respective Rosetta Code categories. The ranking can be achieved by either web scraping or using the API method. The code also has the option to filter incorrect results, and if using the API, it can cross-check the results against a complete list of all programming languages. The final output is a complete ranked list of all programming languages.


string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things)
{
    Console.WriteLine(thing);
}

Iterates through each element in a collection in order and prints it, using a "for each" loop or another loop if "for each" is not available in the language.


string str = "Hello,How,Are,You,Today";
// or Regex.Split ( "Hello,How,Are,You,Today", "," );
// (Regex is in System.Text.RegularExpressions namespace)
string[] strings = str.Split(',');
Console.WriteLine(String.Join(".", strings));

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


Iterative[edit]
static void Main()
{
	Console.WriteLine("GCD of {0} and {1} is {2}", 1, 1, gcd(1, 1));
	Console.WriteLine("GCD of {0} and {1} is {2}", 1, 10, gcd(1, 10));
	Console.WriteLine("GCD of {0} and {1} is {2}", 10, 100, gcd(10, 100));
	Console.WriteLine("GCD of {0} and {1} is {2}", 5, 50, gcd(5, 50));
	Console.WriteLine("GCD of {0} and {1} is {2}", 8, 24, gcd(8, 24));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 17, gcd(36, 17));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 18, gcd(36, 18));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 19, gcd(36, 19));
	for (int x = 1; x < 36; x++)
	{
		Console.WriteLine("GCD of {0} and {1} is {2}", 36, x, gcd(36, x));
	}
	Console.Read();
}

/// <summary>
/// Greatest Common Denominator using Euclidian Algorithm
/// </summary>
static int gcd(int a, int b)
{
    while (b != 0) b = a % (a = b);
    return a;
}

GCD of 1 and 1 is 1
GCD of 1 and 10 is 1
GCD of 10 and 100 is 10
GCD of 5 and 50 is 5
GCD of 8 and 24 is 8
GCD of 36 and 1 is 1
GCD of 36 and 2 is 2
..
GCD of 36 and 16 is 4
GCD of 36 and 17 is 1
GCD of 36 and 18 is 18
..
..
GCD of 36 and 33 is 3
GCD of 36 and 34 is 2
GCD of 36 and 35 is 1

Recursive[edit]
static void Main(string[] args)
{
	Console.WriteLine("GCD of {0} and {1} is {2}", 1, 1, gcd(1, 1));
	Console.WriteLine("GCD of {0} and {1} is {2}", 1, 10, gcd(1, 10));
	Console.WriteLine("GCD of {0} and {1} is {2}", 10, 100, gcd(10, 100));
	Console.WriteLine("GCD of {0} and {1} is {2}", 5, 50, gcd(5, 50));
	Console.WriteLine("GCD of {0} and {1} is {2}", 8, 24, gcd(8, 24));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 17, gcd(36, 17));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 18, gcd(36, 18));
	Console.WriteLine("GCD of {0} and {1} is {2}", 36, 19, gcd(36, 19));
	for (int x = 1; x < 36; x++)
	{
		Console.WriteLine("GCD of {0} and {1} is {2}", 36, x, gcd(36, x));
	}
	Console.Read();
}

// Greatest Common Denominator using Euclidian Algorithm
// Gist: https://gist.github.com/SecretDeveloper/6c426f8993873f1a05f7
static int gcd(int a, int b)
{
	return b==0 ? a : gcd(b, a % b);
}

GCD of 1 and 1 is 1
GCD of 1 and 10 is 1
GCD of 10 and 100 is 10
GCD of 5 and 50 is 5
GCD of 8 and 24 is 8
GCD of 36 and 1 is 1
GCD of 36 and 2 is 2
..
GCD of 36 and 16 is 4
GCD of 36 and 17 is 1
GCD of 36 and 18 is 18
..
..
GCD of 36 and 33 is 3
GCD of 36 and 34 is 2
GCD of 36 and 35 is 1

find the greatest common divisor (GCD), also known as greatest common factor (gcf) or greatest common measure, of two integers.


using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static TcpListener listen;
        static Thread serverthread;

        static void Main(string[] args)
        {
            listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 12321);
            serverthread = new Thread(new ThreadStart(DoListen));
            serverthread.Start();
        }

        private static void DoListen()
        {
            // Listen
            listen.Start();
            Console.WriteLine("Server: Started server");

            while (true)
            {
                Console.WriteLine("Server: Waiting...");
                TcpClient client = listen.AcceptTcpClient();
                Console.WriteLine("Server: Waited");

                // New thread with client
                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));
                clientThread.Start(client);
            }
        }

        private static void DoClient(object client)
        {
            // Read data
            TcpClient tClient = (TcpClient)client;

            Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId);
            do
            {
                if (!tClient.Connected)
                {
                    tClient.Close();
                    Thread.CurrentThread.Abort();       // Kill thread.
                }

                if (tClient.Available > 0)
                {
                    // Resend
                    byte pByte = (byte)tClient.GetStream().ReadByte();
                    Console.WriteLine("Client (Thread: {0}): Data {1}", Thread.CurrentThread.ManagedThreadId, pByte);
                    tClient.GetStream().WriteByte(pByte);
                }

                // Pause
                Thread.Sleep(100);
            } while (true);
        }
    }
}

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


public static bool IsNumeric(string s)
{
    double Result;
    return double.TryParse(s, out Result);  // TryParse routines were added in Framework version 2.0.
}

string value = "123";
if (IsNumeric(value))
{
  // do something
}

public static bool IsNumeric(string s)
{
  try
  {
    Double.Parse(s);
    return true;
  }
  catch
  {
    return false;
  }
}

The code implements a boolean function in .NET framework that checks if a given string can be interpreted as a numeric value, including floating point and negative numbers.


Works with: C sharp version 3.0
using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        var client = new WebClient();
        var data = client.DownloadString("https://www.google.com");

        Console.WriteLine(data);
    }
}

send a GET request to the URL "https://www.w3.org/", print the obtained resource to the console, check the host certificate for validity, and do not perform authentication. It does not support URLs requiring a secure (SSL) connection.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Sutherland
{
    public static class SutherlandHodgman
    {
        #region Class: Edge

        /// <summary>
        /// This represents a line segment
        /// </summary>
        private class Edge
        {
            public Edge(Point from, Point to)
            {
                this.From = from;
                this.To = to;
            }

            public readonly Point From;
            public readonly Point To;
        }

        #endregion

        /// <summary>
        /// This clips the subject polygon against the clip polygon (gets the intersection of the two polygons)
        /// </summary>
        /// <remarks>
        /// Based on the psuedocode from:
        /// http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman
        /// </remarks>
        /// <param name="subjectPoly">Can be concave or convex</param>
        /// <param name="clipPoly">Must be convex</param>
        /// <returns>The intersection of the two polygons (or null)</returns>
        public static Point[] GetIntersectedPolygon(Point[] subjectPoly, Point[] clipPoly)
        {
            if (subjectPoly.Length < 3 || clipPoly.Length < 3)
            {
                throw new ArgumentException(string.Format("The polygons passed in must have at least 3 points: subject={0}, clip={1}", subjectPoly.Length.ToString(), clipPoly.Length.ToString()));
            }

            List<Point> outputList = subjectPoly.ToList();

            //	Make sure it's clockwise
            if (!IsClockwise(subjectPoly))
            {
                outputList.Reverse();
            }

            //	Walk around the clip polygon clockwise
            foreach (Edge clipEdge in IterateEdgesClockwise(clipPoly))
            {
                List<Point> inputList = outputList.ToList();		//	clone it
                outputList.Clear();

                if (inputList.Count == 0)
                {
                    //	Sometimes when the polygons don't intersect, this list goes to zero.  Jump out to avoid an index out of range exception
                    break;
                }

                Point S = inputList[inputList.Count - 1];

                foreach (Point E in inputList)
                {
                    if (IsInside(clipEdge, E))
                    {
                        if (!IsInside(clipEdge, S))
                        {
                            Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);
                            if (point == null)
                            {
                                throw new ApplicationException("Line segments don't intersect");		//	may be colinear, or may be a bug
                            }
                            else
                            {
                                outputList.Add(point.Value);
                            }
                        }

                        outputList.Add(E);
                    }
                    else if (IsInside(clipEdge, S))
                    {
                        Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);
                        if (point == null)
                        {
                            throw new ApplicationException("Line segments don't intersect");		//	may be colinear, or may be a bug
                        }
                        else
                        {
                            outputList.Add(point.Value);
                        }
                    }

                    S = E;
                }
            }

            //	Exit Function
            return outputList.ToArray();
        }

        #region Private Methods

        /// <summary>
        /// This iterates through the edges of the polygon, always clockwise
        /// </summary>
        private static IEnumerable<Edge> IterateEdgesClockwise(Point[] polygon)
        {
            if (IsClockwise(polygon))
            {
                #region Already clockwise

                for (int cntr = 0; cntr < polygon.Length - 1; cntr++)
                {
                    yield return new Edge(polygon[cntr], polygon[cntr + 1]);
                }

                yield return new Edge(polygon[polygon.Length - 1], polygon[0]);

                #endregion
            }
            else
            {
                #region Reverse

                for (int cntr = polygon.Length - 1; cntr > 0; cntr--)
                {
                    yield return new Edge(polygon[cntr], polygon[cntr - 1]);
                }

                yield return new Edge(polygon[0], polygon[polygon.Length - 1]);

                #endregion
            }
        }

        /// <summary>
        /// Returns the intersection of the two lines (line segments are passed in, but they are treated like infinite lines)
        /// </summary>
        /// <remarks>
        /// Got this here:
        /// http://stackoverflow.com/questions/14480124/how-do-i-detect-triangle-and-rectangle-intersection
        /// </remarks>
        private static Point? GetIntersect(Point line1From, Point line1To, Point line2From, Point line2To)
        {
            Vector direction1 = line1To - line1From;
            Vector direction2 = line2To - line2From;
            double dotPerp = (direction1.X * direction2.Y) - (direction1.Y * direction2.X);

            // If it's 0, it means the lines are parallel so have infinite intersection points
            if (IsNearZero(dotPerp))
            {
                return null;
            }

            Vector c = line2From - line1From;
            double t = (c.X * direction2.Y - c.Y * direction2.X) / dotPerp;
            //if (t < 0 || t > 1)
            //{
            //    return null;		//	lies outside the line segment
            //}

            //double u = (c.X * direction1.Y - c.Y * direction1.X) / dotPerp;
            //if (u < 0 || u > 1)
            //{
            //    return null;		//	lies outside the line segment
            //}

            //	Return the intersection point
            return line1From + (t * direction1);
        }

        private static bool IsInside(Edge edge, Point test)
        {
            bool? isLeft = IsLeftOf(edge, test);
            if (isLeft == null)
            {
                //	Colinear points should be considered inside
                return true;
            }

            return !isLeft.Value;
        }
        private static bool IsClockwise(Point[] polygon)
        {
            for (int cntr = 2; cntr < polygon.Length; cntr++)
            {
                bool? isLeft = IsLeftOf(new Edge(polygon[0], polygon[1]), polygon[cntr]);
                if (isLeft != null)		//	some of the points may be colinear.  That's ok as long as the overall is a polygon
                {
                    return !isLeft.Value;
                }
            }

            throw new ArgumentException("All the points in the polygon are colinear");
        }

        /// <summary>
        /// Tells if the test point lies on the left side of the edge line
        /// </summary>
        private static bool? IsLeftOf(Edge edge, Point test)
        {
            Vector tmp1 = edge.To - edge.From;
            Vector tmp2 = test - edge.To;

            double x = (tmp1.X * tmp2.Y) - (tmp1.Y * tmp2.X);		//	dot product of perpendicular?

            if (x < 0)
            {
                return false;
            }
            else if (x > 0)
            {
                return true;
            }
            else
            {
                //	Colinear points;
                return null;
            }
        }

        private static bool IsNearZero(double testValue)
        {
            return Math.Abs(testValue) <= .000000001d;
        }

        #endregion
    }
}

<Window x:Class="Sutherland.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Sutherland Hodgman" Background="#B0B0B0" ResizeMode="CanResizeWithGrip" Width="525" Height="450">
    <Grid Margin="4">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <Border Grid.Row="0" CornerRadius="4" BorderBrush="#707070" Background="#FFFFFF" BorderThickness="2">
            <Canvas Name="canvas"/>
        </Border>

        <UniformGrid Grid.Row="1" Rows="1" Margin="0,4,0,0">
            <Button Name="btnTriRect" Content="Triangle - Rectangle" Margin="4,0" Click="btnTriRect_Click"/>
            <Button Name="btnConvex" Content="Concave - Convex" Click="btnConvex_Click"/>
        </UniformGrid>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Sutherland
{
    public partial class MainWindow : Window
    {
        #region Declaration Section

        private Random _rand = new Random();

        private Brush _subjectBack = new SolidColorBrush(ColorFromHex("30427FCF"));
        private Brush _subjectBorder = new SolidColorBrush(ColorFromHex("427FCF"));
        private Brush _clipBack = new SolidColorBrush(ColorFromHex("30D65151"));
        private Brush _clipBorder = new SolidColorBrush(ColorFromHex("D65151"));
        private Brush _intersectBack = new SolidColorBrush(ColorFromHex("609F18CC"));
        private Brush _intersectBorder = new SolidColorBrush(ColorFromHex("9F18CC"));

        #endregion

        #region Constructor

        public MainWindow()
        {
            InitializeComponent();
        }

        #endregion

        #region Event Listeners

        private void btnTriRect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                double width = canvas.ActualWidth;
                double height = canvas.ActualHeight;

                Point[] poly1 = new Point[] {
				    new Point(_rand.NextDouble() * width, _rand.NextDouble() * height),
				    new Point(_rand.NextDouble() * width, _rand.NextDouble() * height),
				    new Point(_rand.NextDouble() * width, _rand.NextDouble() * height) };

                Point rectPoint = new Point(_rand.NextDouble() * (width * .75d), _rand.NextDouble() * (height * .75d));		//	don't let it start all the way at the bottom right
                Rect rect = new Rect(
                    rectPoint,
                    new Size(_rand.NextDouble() * (width - rectPoint.X), _rand.NextDouble() * (height - rectPoint.Y)));

                Point[] poly2 = new Point[] { rect.TopLeft, rect.TopRight, rect.BottomRight, rect.BottomLeft };

                Point[] intersect = SutherlandHodgman.GetIntersectedPolygon(poly1, poly2);

                canvas.Children.Clear();
                ShowPolygon(poly1, _subjectBack, _subjectBorder, 1d);
                ShowPolygon(poly2, _clipBack, _clipBorder, 1d);
                ShowPolygon(intersect, _intersectBack, _intersectBorder, 3d);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void btnConvex_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Point[] poly1 = new Point[] { new Point(50, 150), new Point(200, 50), new Point(350, 150), new Point(350, 300), new Point(250, 300), new Point(200, 250), new Point(150, 350), new Point(100, 250), new Point(100, 200) };
                Point[] poly2 = new Point[] { new Point(100, 100), new Point(300, 100), new Point(300, 300), new Point(100, 300) };

                Point[] intersect = SutherlandHodgman.GetIntersectedPolygon(poly1, poly2);

                canvas.Children.Clear();
                ShowPolygon(poly1, _subjectBack, _subjectBorder, 1d);
                ShowPolygon(poly2, _clipBack, _clipBorder, 1d);
                ShowPolygon(intersect, _intersectBack, _intersectBorder, 3d);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        #region Private Methods

        private void ShowPolygon(Point[] points, Brush background, Brush border, double thickness)
        {
            if (points == null || points.Length == 0)
            {
                return;
            }

            Polygon polygon = new Polygon();
            polygon.Fill = background;
            polygon.Stroke = border;
            polygon.StrokeThickness = thickness;

            foreach (Point point in points)
            {
                polygon.Points.Add(point);
            }

            canvas.Children.Add(polygon);
        }

        /// <summary>
        /// This is just a wrapper to the color converter (why can't they have a method off the color class with all
        /// the others?)
        /// </summary>
        private static Color ColorFromHex(string hexValue)
        {
            if (hexValue.StartsWith("#"))
            {
                return (Color)ColorConverter.ConvertFromString(hexValue);
            }
            else
            {
                return (Color)ColorConverter.ConvertFromString("#" + hexValue);
            }
        }

        #endregion
    }
}

implement the Sutherland-Hodgman clipping algorithm to find the intersection between a subject polygon and a clip polygon. The subject polygon is defined by a sequence of points and is clipped by a rectangle. The program then prints the sequence of points that define the resulting clipped polygon. Additionally, for extra credit, the program displays all three polygons on a graphical surface, each in a different color, and fills the resulting polygon. The origin for display can be either north-west or south-west. The implementation is done in .net 4.0 using wpf.


Translation of: D
using System;
using System.Collections.Generic;
using System.Linq;

namespace RankingMethods {
    class Program {
        static void Main(string[] args) {
            Dictionary<string, int> scores = new Dictionary<string, int> {
                ["Solomon"] = 44,
                ["Jason"] = 42,
                ["Errol"] = 42,
                ["Gary"] = 41,
                ["Bernard"] = 41,
                ["Barry"] = 41,
                ["Stephen"] = 39,
            };

            StandardRank(scores);
            ModifiedRank(scores);
            DenseRank(scores);
            OrdinalRank(scores);
            FractionalRank(scores);
        }

        static void StandardRank(Dictionary<string, int> data) {
            Console.WriteLine("Standard Rank");

            var list = data.Values.Distinct().ToList();
            list.Sort((a, b) => b.CompareTo(a));

            int rank = 1;
            foreach (var value in list) {
                int temp = rank;
                foreach (var k in data.Keys) {
                    if (data[k] == value) {
                        Console.WriteLine("{0} {1} {2}", temp, value, k);
                        rank++;
                    }
                }
            }

            Console.WriteLine();
        }

        static void ModifiedRank(Dictionary<string, int> data) {
            Console.WriteLine("Modified Rank");

            var list = data.Values.Distinct().ToList();
            list.Sort((a, b) => b.CompareTo(a));

            int rank = 0;
            foreach (var value in list) {
                foreach (var k in data.Keys) {
                    if (data[k] == value) {
                        rank++;
                    }
                }

                foreach (var k in data.Keys) {
                    if (data[k] == value) {
                        Console.WriteLine("{0} {1} {2}", rank, data[k], k);
                    }
                }
            }

            Console.WriteLine();
        }

        static void DenseRank(Dictionary<string, int> data) {
            Console.WriteLine("Dense Rank");

            var list = data.Values.Distinct().ToList();
            list.Sort((a, b) => b.CompareTo(a));

            int rank = 1;
            foreach (var value in list) {
                foreach (var k in data.Keys) {
                    if (data[k] == value) {
                        Console.WriteLine("{0} {1} {2}", rank, data[k], k);
                    }
                }
                rank++;
            }

            Console.WriteLine();
        }

        static void OrdinalRank(Dictionary<string, int> data) {
            Console.WriteLine("Ordinal Rank");

            var list = data.Values.Distinct().ToList();
            list.Sort((a, b) => b.CompareTo(a));

            int rank = 1;
            foreach (var value in list) {
                foreach (var k in data.Keys) {
                    if (data[k] == value) {
                        Console.WriteLine("{0} {1} {2}", rank, data[k], k);
                        rank++;
                    }
                }
            }

            Console.WriteLine();
        }

        static void FractionalRank(Dictionary<string, int> data) {
            Console.WriteLine("Fractional Rank");

            var list = data.Values.Distinct().ToList();
            list.Sort((a, b) => b.CompareTo(a));

            int rank = 0;
            foreach (var value in list) {
                double avg = 0;
                int cnt = 0;

                foreach (var k in data.Keys) {
                    if (data[k] == value) {
                        rank++;
                        cnt++;
                        avg += rank;
                    }
                }
                avg /= cnt;

                foreach (var k in data.Keys) {
                    if (data[k] == value) {
                        Console.WriteLine("{0:F1} {1} {2}", avg, data[k], k);
                    }
                }
            }

            Console.WriteLine();
        }
    }
}

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


using System;

namespace RosettaCode {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("=== radians ===");
            Console.WriteLine("sin (pi/3) = {0}", Math.Sin(Math.PI / 3));
            Console.WriteLine("cos (pi/3) = {0}", Math.Cos(Math.PI / 3));
            Console.WriteLine("tan (pi/3) = {0}", Math.Tan(Math.PI / 3));
            Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5));
            Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5));
            Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5));
            Console.WriteLine("");
            Console.WriteLine("=== degrees ===");
            Console.WriteLine("sin (60) = {0}", Math.Sin(60 * Math.PI / 180));
            Console.WriteLine("cos (60) = {0}", Math.Cos(60 * Math.PI / 180));
            Console.WriteLine("tan (60) = {0}", Math.Tan(60 * Math.PI / 180));
            Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5) * 180/ Math.PI);
            Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5) * 180 / Math.PI);
            Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5) * 180 / Math.PI);

            Console.ReadLine();
        }
    }
}

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


using System;  // 4790@3.6
class program
{
    static void Main()
    {
        knapSack(40);
        var sw = System.Diagnostics.Stopwatch.StartNew();
        Console.Write(knapSack(400) + "\n" + sw.Elapsed);  // 51 µs
        Console.Read();
    }

    static string knapSack(uint w1)
    {
        init(); change();
        uint n = (uint)w.Length; var K = new uint[n + 1, w1 + 1];
        for (uint vi, wi, w0, x, i = 0; i < n; i++)
            for (vi = v[i], wi = w[i], w0 = 1; w0 <= w1; w0++)
            {
                x = K[i, w0];
                if (wi <= w0) x = max(vi + K[i, w0 - wi], x);
                K[i + 1, w0] = x;
            }
        string str = "";
        for (uint v1 = K[n, w1]; v1 > 0; n--)
            if (v1 != K[n - 1, w1])
            {
                v1 -= v[n - 1]; w1 -= w[n - 1]; str += items[n - 1] + "\n";
            }
        return str;
    }

    static uint max(uint a, uint b) { return a > b ? a : b; }

    static byte[] w, v; static string[] items;

    static byte[] p = { 1, 1, 2, 2, 2, 3, 3, 3, 1, 3, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2 };

    static void init()
    {
        w = new byte[] { 9, 13, 153, 50, 15, 68, 27, 39, 23, 52, 11,
                          32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30 };

        v = new byte[] { 150, 35, 200, 60, 60, 45, 60, 40, 30, 10, 70,
                          30, 15, 10, 40, 70, 75, 80, 20, 12, 50, 10 };

        items = new string[] {"map","compass","water","sandwich","glucose","tin",
                              "banana","apple","cheese","beer","suntan cream",
                              "camera","T-shirt","trousers","umbrella",
                              "waterproof trousers","waterproof overclothes",
                              "note-case","sunglasses","towel","socks","book"};
    }

    static void change()
    {
        int n = w.Length, s = 0, i, j, k; byte xi;
        for (i = 0; i < n; i++) s += p[i];
        {
            byte[] x = new byte[s];
            for (k = i = 0; i < n; i++)
                for (xi = w[i], j = p[i]; j > 0; j--) x[k++] = xi;
            w = x;
        }
        {
            byte[] x = new byte[s];
            for (k = i = 0; i < n; i++)
                for (xi = v[i], j = p[i]; j > 0; j--) x[k++] = xi;
            v = x;
        }
        string[] pItems = new string[s]; string itemI;
        for (k = i = 0; i < n; i++)
            for (itemI = items[i], j = p[i]; j > 0; j--) pItems[k++] = itemI;
        items = pItems;
    }
}

The code determines the optimal combination of items a tourist can carry in his knapsack, without exceeding a weight limit of 4 kg, to maximize the total value. The items, their weights, values, and quantities are given in a list. The solution does not allow for fractional items. This is a variant of the Bounded Knapsack problem.


using System; //DateTime, Console, Environment classes
class Program
{
    static DateTime start;
    static void Main(string[] args)
    {
        start = DateTime.Now;
        //Add event handler for Ctrl+C command
        Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
        int counter = 0;
        while (true)
        {
            Console.WriteLine(++counter);
            System.Threading.Thread.Sleep(500);
        }
    }
    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        var end = DateTime.Now;
        Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
        Environment.Exit(0);
    }
}

The code outputs an integer every half second. It also handles SIGINT or SIGQUIT signals, often generated by user's ctrl-C or ctrl-\ inputs. On receiving these signals, the code stops outputting integers, displays the total runtime in seconds, and then terminates. This signal handling is achieved through event handler functions, referred to as 'events' in C#.


string s = "12345";
s = (int.Parse(s) + 1).ToString();
// The above functions properly for strings >= Int32.MinValue and
//  < Int32.MaxValue. ( -2147483648 to 2147483646 )

// The following will work for any arbitrary-length integer string.
//  (Assuming that the string fits in memory, leaving enough space
//  for the temporary BigInteger created, plus the resulting string):
using System.Numerics;
string bis = "123456789012345678999999999";
bis = (BigInteger.Parse(bis) + 1).ToString();
// Note that extremely long strings will take a long time to parse
//  and convert from a BigInteger back into a string.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RosettaCodeTasks
{

	class Program
	{
		static void Main ( string[ ] args )
		{
			FindCommonDirectoryPath.Test ( );
		}

	}

	class FindCommonDirectoryPath
	{
		public static void Test ( )
		{
			Console.WriteLine ( "Find Common Directory Path" );
			Console.WriteLine ( );
			List<string> PathSet1 = new List<string> ( );
			PathSet1.Add ( "/home/user1/tmp/coverage/test" );
			PathSet1.Add ( "/home/user1/tmp/covert/operator" );
			PathSet1.Add ( "/home/user1/tmp/coven/members" );
			Console.WriteLine("Path Set 1 (All Absolute Paths):");
			foreach ( string path in PathSet1 )
			{
				Console.WriteLine ( path );
			}
			Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) );
		}
		public static string FindCommonPath ( string Separator, List<string> Paths )
		{
			string CommonPath = String.Empty;
			List<string> SeparatedPath = Paths
				.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )
				.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )
				.ToList ( );

			foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )
			{
				if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )
				{
					CommonPath = PathSegment;
				}
				else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )
				{
					CommonPath += Separator + PathSegment;
				}
				else
				{
					break;
				}
			}

			return CommonPath;
		}
	}
}

The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.


private static readonly Random Rand = new Random();

void sattoloCycle<T>(IList<T> items) {
    for (var i = items.Count; i-- > 1;) {
        int j = Rand.Next(i);
        var tmp = items[i];
        items[i] = items[j];
        items[j] = tmp;
    }
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


using System;
using System.Linq;

namespace Test
{
    class Program
    {
        static void Main()
        {
            double[] myArr = new double[] { 1, 5, 3, 6, 4, 2 };

            myArr = myArr.OrderBy(i => i).ToArray();
            // or Array.Sort(myArr) for in-place sort

            int mid = myArr.Length / 2;
            double median;

            if (myArr.Length % 2 == 0)
            {
                //we know its even
                median = (myArr[mid] + myArr[mid - 1]) / 2.0;
            }
            else
            {
                //we know its odd
                median = myArr[mid];
            }

            Console.WriteLine(median);
            Console.ReadLine();
        }
    }
}

The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.