//
// The Tripartite conditional enables Bentley-McIlroy 3-way Partitioning.
// This performs additional compares to isolate islands of keys equal to
// the pivot value.  Use unless key-equivalent classes are of small size.
//
#define Tripartite

namespace RosettaCode {
  using System;
  using System.Diagnostics;

  public class QuickSort<T> where T : IComparable {
    #region Constants
    public const UInt32 INSERTION_LIMIT_DEFAULT = 12;
    private const Int32 SAMPLES_MAX = 19;
    #endregion

    #region Properties
    public UInt32 InsertionLimit { get; }
    private T[] Samples { get; }
    private Int32 Left { get; set; }
    private Int32 Right { get; set; }
    private Int32 LeftMedian { get; set; }
    private Int32 RightMedian { get; set; }
    #endregion

    #region Constructors
    public QuickSort(UInt32 insertionLimit = INSERTION_LIMIT_DEFAULT) {
      this.InsertionLimit = insertionLimit;
      this.Samples = new T[SAMPLES_MAX];
    }
    #endregion

    #region Sort Methods
    public void Sort(T[] entries) {
      Sort(entries, 0, entries.Length - 1);
    }

    public void Sort(T[] entries, Int32 first, Int32 last) {
      var length = last + 1 - first;
      while (length > 1) {
        if (length < InsertionLimit) {
          InsertionSort<T>.Sort(entries, first, last);
          return;
        }

        Left = first;
        Right = last;
        var median = pivot(entries);
        partition(median, entries);
        //[Note]Right < Left

        var leftLength = Right + 1 - first;
        var rightLength = last + 1 - Left;

        //
        // First recurse over shorter partition, then loop
        // on the longer partition to elide tail recursion.
        //
        if (leftLength < rightLength) {
          Sort(entries, first, Right);
          first = Left;
          length = rightLength;
        }
        else {
          Sort(entries, Left, last);
          last = Right;
          length = leftLength;
        }
      }
    }

    /// Return an odd sample size proportional to the log of a large interval size.
    private static Int32 sampleSize(Int32 length, Int32 max = SAMPLES_MAX) {
      var logLen = (Int32)Math.Log10(length);
      var samples = Math.Min(2 * logLen + 1, max);
      return Math.Min(samples, length);
    }

    /// Estimate the median value of entries[Left:Right]
    /// <remarks>A sample median is used as an estimate the true median.</remarks>
    private T pivot(T[] entries) {
      var length = Right + 1 - Left;
      var samples = sampleSize(length);
      // Sample Linearly:
      for (var sample = 0; sample < samples; sample++) {
        // Guard against Arithmetic Overflow:
        var index = (Int64)length * sample / samples + Left;
        Samples[sample] = entries[index];
      }

      InsertionSort<T>.Sort(Samples, 0, samples - 1);
      return Samples[samples / 2];
    }

    private void partition(T median, T[] entries) {
      var first = Left;
      var last = Right;
#if Tripartite
      LeftMedian = first;
      RightMedian = last;
#endif
      while (true) {
        //[Assert]There exists some index >= Left where entries[index] >= median
        //[Assert]There exists some index <= Right where entries[index] <= median
        // So, there is no need for Left or Right bound checks
        while (median.CompareTo(entries[Left]) > 0) Left++;
        while (median.CompareTo(entries[Right]) < 0) Right--;

        //[Assert]entries[Right] <= median <= entries[Left]
        if (Right <= Left) break;

        Swap(entries, Left, Right);
        swapOut(median, entries);
        Left++;
        Right--;
        //[Assert]entries[first:Left - 1] <= median <= entries[Right + 1:last]
      }

      if (Left == Right) {
        Left++;
        Right--;
      }
      //[Assert]Right < Left
      swapIn(entries, first, last);

      //[Assert]entries[first:Right] <= median <= entries[Left:last]
      //[Assert]entries[Right + 1:Left - 1] == median when non-empty
    }
    #endregion

    #region Swap Methods
    [Conditional("Tripartite")]
    private void swapOut(T median, T[] entries) {
      if (median.CompareTo(entries[Left]) == 0) Swap(entries, LeftMedian++, Left);
      if (median.CompareTo(entries[Right]) == 0) Swap(entries, Right, RightMedian--);
    }

    [Conditional("Tripartite")]
    private void swapIn(T[] entries, Int32 first, Int32 last) {
      // Restore Median entries
      while (first < LeftMedian) Swap(entries, first++, Right--);
      while (RightMedian < last) Swap(entries, Left++, last--);
    }

    /// Swap entries at the left and right indicies.
    public void Swap(T[] entries, Int32 left, Int32 right) {
      Swap(ref entries[left], ref entries[right]);
    }

    /// Swap two entities of type T.
    public static void Swap(ref T e1, ref T e2) {
      var e = e1;
      e1 = e2;
      e2 = e;
    }
    #endregion
  }

  #region Insertion Sort
  static class InsertionSort<T> where T : IComparable {
    public static void Sort(T[] entries, Int32 first, Int32 last) {
      for (var next = first + 1; next <= last; next++)
        insert(entries, first, next);
    }

    /// Bubble next entry up to its sorted location, assuming entries[first:next - 1] are already sorted.
    private static void insert(T[] entries, Int32 first, Int32 next) {
      var entry = entries[next];
      while (next > first && entries[next - 1].CompareTo(entry) > 0)
        entries[next] = entries[--next];
      entries[next] = entry;
    }
  }
  #endregion
}

  using Sort;
  using System;

  class Program {
    static void Main(String[] args) {
      var entries = new Int32[] { 1, 3, 5, 7, 9, 8, 6, 4, 2 };
      var sorter = new QuickSort<Int32>();
      sorter.Sort(entries);
      Console.WriteLine(String.Join(" ", entries));
    }
  }

The code implements the quicksort algorithm to sort an array or list of elements. It selects a pivot element and divides the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions. The code also includes an optimized version of quicksort that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified and can vary. The code also compares quicksort with merge sort, highlighting their differences and use cases.


using System;

namespace RosettaCode.DateFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime today = DateTime.Now.Date;
            Console.WriteLine(today.ToString("yyyy-MM-dd"));
            Console.WriteLine(today.ToString("dddd, MMMMM d, yyyy"));
        }
    }
}

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
    return from m in Enumerable.Range(0, 1 << list.Count)
                  select
                      from i in Enumerable.Range(0, list.Count)
                      where (m & (1 << i)) != 0
                      select list[i];
}

public void PowerSetofColors()
{
    var colors = new List<KnownColor> { KnownColor.Red, KnownColor.Green,
        KnownColor.Blue, KnownColor.Yellow };

    var result = GetPowerSet(colors);

    Console.Write( string.Join( Environment.NewLine,
        result.Select(subset =>
            string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}

implement a function that takes a set as input and returns its power set. The power set includes all possible subsets of the input set, including the empty set and the set itself. The function also demonstrates the ability to handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set. The function can be implemented either recursively or non-recursively.


using System;
class Program
{
    static uint[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
    static string[] rum = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };

    static string ToRoman(uint number)
    {
        string value = "";
        for (int i = 0; i < nums.Length && number != 0; i++)
        {
            while (number >= nums[i])
            {
                number -= nums[i];
                value += rum[i];
            }
        }
        return value;
    }

    static void Main()
    {
        for (uint number = 1; number <= 1 << 10; number *= 2)
        {
            Console.WriteLine("{0} = {1}", number, ToRoman(number));
        }
    }
}

Func<int, string> toRoman = (number) =>
  new Dictionary<int, string>
  {
    {1000, "M"},
    {900, "CM"},
    {500, "D"},
    {400, "CD"},
    {100, "C"},
    {90, "XC"},
    {50, "L"},
    {40, "XL"},
    {10, "X"},
    {9, "IX"},
    {5, "V"},
    {4, "IV"},
    {1, "I"}
  }.Aggregate(new string('I', number), (m, _) => m.Replace(new string('I', _.Key), _.Value));

implement a function that converts a positive integer into its equivalent Roman numeral representation.


 int[] numbers = new int[10];

 string[] words = { "these", "are", "arrays" };

  int[] more_numbers = new int[3]{ 21, 14 ,63 };

  int[,] number_matrix = new int[3,2];

  string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };

 string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };

int[] array = new int[10];

array[0] = 1;
array[1] = 3;

Console.WriteLine(array[0]);

using System;
using System.Collections.Generic;

List<int> list = new List<int>();

list.Add(1);
list.Add(3);

list[0] = 2;

Console.WriteLine(list[0]);

demonstrate the basic syntax of arrays in a specific programming language. The codes include creation of both fixed-length and dynamic arrays, assigning values to them, and retrieving an element from them. It also shows the creation of a multi-dimensional array, specifically a 3x2 int matrix, and its initialization. The codes also cover examples of arrays of 10 int types and 3 string types.


using System.IO;

using (var reader = new StreamReader("input.txt"))
using (var writer = new StreamWriter("output.txt"))
{
    var text = reader.ReadToEnd();
    writer.Write(text);
}

using System.IO;

var text = File.ReadAllText("input.txt");
File.WriteAllText("output.txt", text);

demonstrate how to read the contents of "input.txt" file into a variable and then write these contents into a new file called "output.txt".


class Program
{
    static void Main(string[] args)
    {
        string input;
        Console.Write("Enter a series of letters: ");
        input = Console.ReadLine();
        stringCase(input);
    }

    private static void stringCase(string str)
    {
        char[] chars = str.ToCharArray();
        string newStr = "";

        foreach (char i in chars)
            if (char.IsLower(i))
                newStr += char.ToUpper(i);
            else
                newStr += char.ToLower(i);
        Console.WriteLine("Converted: {0}", newStr);
    }
}

System.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG"));

demonstrate the conversion of the string 'alphaBETA' to upper-case and lower-case using the default encoding or ASCII. It also showcases additional case conversion functions available in the language library, such as swapping case or capitalizing the first letter. The code also handles title case conversion differently.


class Segment
{
    public Segment(PointF p1, PointF p2)
    {
        P1 = p1;
        P2 = p2;
    }

    public readonly PointF P1;
    public readonly PointF P2;

    public float Length()
    {
        return (float)Math.Sqrt(LengthSquared());
    }

    public float LengthSquared()
    {
        return (P1.X - P2.X) * (P1.X - P2.X)
            + (P1.Y - P2.Y) * (P1.Y - P2.Y);
    }
}

Segment Closest_BruteForce(List<PointF> points)
{
    int n = points.Count;
    var result = Enumerable.Range( 0, n-1)
        .SelectMany( i => Enumerable.Range( i+1, n-(i+1) )
            .Select( j => new Segment( points[i], points[j] )))
            .OrderBy( seg => seg.LengthSquared())
            .First();

    return result;
}

public static Segment MyClosestDivide(List<PointF> points)
{
   return MyClosestRec(points.OrderBy(p => p.X).ToList());
}

private static Segment MyClosestRec(List<PointF> pointsByX)
{
   int count = pointsByX.Count;
   if (count <= 4)
      return Closest_BruteForce(pointsByX);

   // left and right lists sorted by X, as order retained from full list
   var leftByX = pointsByX.Take(count/2).ToList();
   var leftResult = MyClosestRec(leftByX);

   var rightByX = pointsByX.Skip(count/2).ToList();
   var rightResult = MyClosestRec(rightByX);

   var result = rightResult.Length() < leftResult.Length() ? rightResult : leftResult;

   // There may be a shorter distance that crosses the divider
   // Thus, extract all the points within result.Length either side
   var midX = leftByX.Last().X;
   var bandWidth = result.Length();
   var inBandByX = pointsByX.Where(p => Math.Abs(midX - p.X) <= bandWidth);

   // Sort by Y, so we can efficiently check for closer pairs
   var inBandByY = inBandByX.OrderBy(p => p.Y).ToArray();

   int iLast = inBandByY.Length - 1;
   for (int i = 0; i < iLast; i++ )
   {
      var pLower = inBandByY[i];

      for (int j = i + 1; j <= iLast; j++)
      {
         var pUpper = inBandByY[j];

         // Comparing each point to successivly increasing Y values
         // Thus, can terminate as soon as deltaY is greater than best result
         if ((pUpper.Y - pLower.Y) >= result.Length())
            break;

         if (Segment.Length(pLower, pUpper) < result.Length())
            result = new Segment(pLower, pUpper);
      }
   }

   return result;
}

var randomizer = new Random(10);
var points = Enumerable.Range( 0, 10000).Select( i => new PointF( (float)randomizer.NextDouble(), (float)randomizer.NextDouble())).ToList();
Stopwatch sw = Stopwatch.StartNew();
var r1 = Closest_BruteForce(points);
sw.Stop();
Debugger.Log(1, "", string.Format("Time used (Brute force) (float): {0} ms", sw.Elapsed.TotalMilliseconds));
Stopwatch sw2 = Stopwatch.StartNew();
var result2 = Closest_Recursive(points);
sw2.Stop();
Debugger.Log(1, "", string.Format("Time used (Divide & Conquer): {0} ms",sw2.Elapsed.TotalMilliseconds));
Assert.Equal(r1.Length(), result2.Length());

The code provides a solution for the Closest Pair of Points problem in two dimensions. It includes two algorithms: a brute-force method with a time complexity of O(n^2) and a more efficient divide-and-conquer approach with a time complexity of O(n log n). The code also includes a helper class for distance comparisons and an optimized targeted search method.


// Creates and initializes a new integer Array
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };
//same as
int[] intArray = new int[]{ 1, 2, 3, 4, 5 };
//same as
int[] intArray = { 1, 2, 3, 4, 5 };

//Arrays are zero-based
string[] stringArr = new string[5];
stringArr[0] = "string";

//Create and initialize ArrayList
ArrayList myAl = new ArrayList { "Hello", "World", "!" };

//Create ArrayList and add some values
ArrayList myAL = new ArrayList();
      myAL.Add("Hello");
      myAL.Add("World");
      myAL.Add("!");

//Create and initialize List
List<string> myList = new List<string> { "Hello", "World", "!" };

//Create List and add some values
List<string> myList2 = new List<string>();
            myList2.Add("Hello");
            myList2.Add("World");
            myList2.Add("!");

//Create an initialize Hashtable
Hashtable myHt = new Hashtable() { { "Hello", "World" }, { "Key", "Value" } };

//Create Hashtable and add some Key-Value pairs.
Hashtable myHt2 = new Hashtable();
	myHt2.Add("Hello", "World");
	myHt2.Add("Key", "Value");

//Create an initialize Dictionary
Dictionary<string, string> dict = new Dictionary<string, string>() { { "Hello", "World" }, { "Key", "Value" } };
//Create Dictionary and add some Key-Value pairs.
Dictionary<string, string> dict2 = new Dictionary<string, string>();
	dict2.Add("Hello", "World");
	dict2.Add("Key", "Value");

The code creates a collection and adds values to it. It utilizes various data structures like ArrayList, List, Hashtables, and Dictionary. The ArrayList dynamically increases in size as required and is zero-based. The List class is a strongly typed list of objects accessible by index. Hashtables and Dictionary classes represent collections of unique key/value pairs.


determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.


using System;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; ; i++)
        {
            Console.Write(i);
            if (i == 10) break;
            Console.Write(", ");
        }
        Console.WriteLine();
    }
}

The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.


namespace Algorithms
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class TopologicalSorter<ValueType>
    {
        private class Relations
        {
            public int Dependencies = 0;
            public HashSet<ValueType> Dependents = new HashSet<ValueType>();
        }

        private Dictionary<ValueType, Relations> _map = new Dictionary<ValueType, Relations>();

        public void Add(ValueType obj)
        {
            if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());
        }

        public void Add(ValueType obj, ValueType dependency)
        {
            if (dependency.Equals(obj)) return;

            if (!_map.ContainsKey(dependency)) _map.Add(dependency, new Relations());

            var dependents = _map[dependency].Dependents;

            if (!dependents.Contains(obj))
            {
                dependents.Add(obj);

                if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());

                ++_map[obj].Dependencies;
            }
        }

        public void Add(ValueType obj, IEnumerable<ValueType> dependencies)
        {
            foreach (var dependency in dependencies) Add(obj, dependency);
        }

        public void Add(ValueType obj, params ValueType[] dependencies)
        {
            Add(obj, dependencies as IEnumerable<ValueType>);
        }

        public Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>> Sort()
        {
            List<ValueType> sorted = new List<ValueType>(), cycled = new List<ValueType>();
            var map = _map.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            sorted.AddRange(map.Where(kvp => kvp.Value.Dependencies == 0).Select(kvp => kvp.Key));

            for (int idx = 0; idx < sorted.Count; ++idx) sorted.AddRange(map[sorted[idx]].Dependents.Where(k => --map[k].Dependencies == 0));

            cycled.AddRange(map.Where(kvp => kvp.Value.Dependencies != 0).Select(kvp => kvp.Key));

            return new Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>>(sorted, cycled);
        }

        public void Clear()
        {
            _map.Clear();
        }
    }

}

/*
	Example usage with Task object
*/

namespace ExampleApplication
{
    using Algorithms;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Task
    {
        public string Message;
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Task> tasks = new List<Task>
            {
                new Task{ Message = "A - depends on B and C" },    //0
                new Task{ Message = "B - depends on none" },       //1
                new Task{ Message = "C - depends on D and E" },    //2
                new Task{ Message = "D - depends on none" },       //3
                new Task{ Message = "E - depends on F, G and H" }, //4
                new Task{ Message = "F - depends on I" },          //5
                new Task{ Message = "G - depends on none" },       //6
                new Task{ Message = "H - depends on none" },       //7
                new Task{ Message = "I - depends on none" },       //8
            };

            TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();

            // now setting relations between them as described above
            resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
            //resolver.Add(tasks[1]); // no need for this since the task was already mentioned as a dependency
            resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
            //resolver.Add(tasks[3]); // no need for this since the task was already mentioned as a dependency
            resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
            resolver.Add(tasks[5], tasks[8]);
            //resolver.Add(tasks[6]); // no need for this since the task was already mentioned as a dependency
            //resolver.Add(tasks[7]); // no need for this since the task was already mentioned as a dependency

            //resolver.Add(tasks[3], tasks[0]); // uncomment this line to test cycled dependency

            var result = resolver.Sort();
            var sorted = result.Item1;
            var cycled = result.Item2;

            if (!cycled.Any())
            {
                foreach (var d in sorted) Console.WriteLine(d.Message);
            }
            else
            {
                Console.Write("Cycled dependencies detected: ");

                foreach (var d in cycled) Console.Write($"{d.Message[0]} ");

                Console.WriteLine();
            }

            Console.WriteLine("exiting...");
        }
    }
}

The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.


Works with: Mono version 2.6
class Program
{
	public static void Main (string[] args)
	{
		var value = "abcd".StartsWith("ab");
		value = "abcd".EndsWith("zn"); //returns false
		value = "abab".Contains("bb"); //returns false
		value = "abab".Contains("ab"); //returns true
		int loc = "abab".IndexOf("bb"); //returns -1
		loc = "abab".IndexOf("ab"); //returns 0
		loc = "abab".IndexOf("ab",loc+1); //returns 2
	}
}

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


using System;
using System.Linq;

namespace Four_Squares_Puzzle {
    class Program {
        static void Main(string[] args) {
            fourSquare(1, 7, true, true);
            fourSquare(3, 9, true, true);
            fourSquare(0, 9, false, false);
        }

        private static void fourSquare(int low, int high, bool unique, bool print) {
            int count = 0;

            if (print) {
                Console.WriteLine("a b c d e f g");
            }
            for (int a = low; a <= high; ++a) {
                for (int b = low; b <= high; ++b) {
                    if (notValid(unique, b, a)) continue;

                    int fp = a + b;
                    for (int c = low; c <= high; ++c) {
                        if (notValid(unique, c, b, a)) continue;
                        for (int d = low; d <= high; ++d) {
                            if (notValid(unique, d, c, b, a)) continue;
                            if (fp != b + c + d) continue;

                            for (int e = low; e <= high; ++e) {
                                if (notValid(unique, e, d, c, b, a)) continue;
                                for (int f = low; f <= high; ++f) {
                                    if (notValid(unique, f, e, d, c, b, a)) continue;
                                    if (fp != d + e + f) continue;

                                    for (int g = low; g <= high; ++g) {
                                        if (notValid(unique, g, f, e, d, c, b, a)) continue;
                                        if (fp != f + g) continue;

                                        ++count;
                                        if (print) {
                                            Console.WriteLine("{0} {1} {2} {3} {4} {5} {6}", a, b, c, d, e, f, g);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (unique) {
                Console.WriteLine("There are {0} unique solutions in [{1}, {2}]", count, low, high);
            }
            else {
                Console.WriteLine("There are {0} non-unique solutions in [{1}, {2}]", count, low, high);
            }
        }

        private static bool notValid(bool unique, int needle, params int[] haystack) {
            return unique && haystack.Any(p => p == needle);
        }
    }
}

The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.


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

public class Clock : Form
{
    static readonly float degrees06 = (float)Math.PI / 30;
    static readonly float degrees30 = degrees06 * 5;
    static readonly float degrees90 = degrees30 * 3;

    readonly int margin = 20;

    private Point p0;

    public Clock()
    {
        Size = new Size(500, 500);
        StartPosition = FormStartPosition.CenterScreen;
        Resize += (sender, args) => ResetSize();
        ResetSize();
        var timer = new Timer() { Interval = 1000, Enabled = true };
        timer.Tick += (sender, e) => Refresh();
        DoubleBuffered = true;
    }

    private void ResetSize()
    {
        p0 = new Point(ClientRectangle.Width / 2, ClientRectangle.Height / 2);
        Refresh();
    }

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

        drawFace(e.Graphics);

        var time = DateTime.Now;
        int second = time.Second;
        int minute = time.Minute;
        int hour = time.Hour;

        float angle = degrees90 - (degrees06 * second);
        DrawHand(e.Graphics, Pens.Red, angle, 0.95);

        float minsecs = (minute + second / 60.0F);
        angle = degrees90 - (degrees06 * minsecs);
        DrawHand(e.Graphics, Pens.Black, angle, 0.9);

        float hourmins = (hour + minsecs / 60.0F);
        angle = degrees90 - (degrees30 * hourmins);
        DrawHand(e.Graphics, Pens.Black, angle, 0.6);
    }

    private void drawFace(Graphics g)
    {
        int radius = Math.Min(p0.X, p0.Y) - margin;
        g.FillEllipse(Brushes.White, p0.X - radius, p0.Y - radius, radius * 2, radius * 2);

        for (int h = 0; h < 12; h++)
            DrawHand(g, Pens.LightGray, h * degrees30, -0.05);

        for (int m = 0; m < 60; m++)
            DrawHand(g, Pens.LightGray, m * degrees06, -0.025);
    }

    private void DrawHand(Graphics g, Pen pen, float angle, double size)
    {
        int radius = Math.Min(p0.X, p0.Y) - margin;

        int x0 = p0.X + (size > 0 ? 0 : Convert.ToInt32(radius * (1 + size) * Math.Cos(angle)));
        int y0 = p0.Y + (size > 0 ? 0 : Convert.ToInt32(radius * (1 + size) * Math.Sin(-angle)));

        int x1 = p0.X + Convert.ToInt32(radius * (size > 0 ? size : 1) * Math.Cos(angle));
        int y1 = p0.Y + Convert.ToInt32(radius * (size > 0 ? size : 1) * Math.Sin(-angle));

        g.DrawLine(pen, x0, y0, x1, y1);
    }

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

illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.


using System;

namespace RosettaCode.CSharp
{
    class Program
    {
        static void Count_New_Triangle(ulong A, ulong B, ulong C, ulong Max_Perimeter, ref ulong Total_Cnt, ref ulong Primitive_Cnt)
        {
            ulong Perimeter = A + B + C;

            if (Perimeter <= Max_Perimeter)
            {
                Primitive_Cnt = Primitive_Cnt + 1;
                Total_Cnt = Total_Cnt + Max_Perimeter / Perimeter;
                Count_New_Triangle(A + 2 * C - 2 * B, 2 * A + 2 * C - B, 2 * A + 3 * C - 2 * B, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);
                Count_New_Triangle(A + 2 * B + 2 * C, 2 * A + B + 2 * C, 2 * A + 2 * B + 3 * C, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);
                Count_New_Triangle(2 * B + 2 * C - A, B + 2 * C - 2 * A, 2 * B + 3 * C - 2 * A, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);
            }
        }

        static void Count_Pythagorean_Triples()
        {
            ulong T_Cnt, P_Cnt;

            for (int I = 1; I <= 8; I++)
            {
                T_Cnt = 0;
                P_Cnt = 0;
                ulong ExponentNumberValue = (ulong)Math.Pow(10, I);
                Count_New_Triangle(3, 4, 5, ExponentNumberValue, ref T_Cnt, ref P_Cnt);
                Console.WriteLine("Perimeter up to 10E" + I + " : " + T_Cnt + " Triples, " + P_Cnt + " Primitives");
            }
        }

        static void Main(string[] args)
        {
            Count_Pythagorean_Triples();
        }
    }
}

Perimeter up to 10E1 : 0 Triples, 0 Primitives
Perimeter up to 10E2 : 17 Triples, 7 Primitives
Perimeter up to 10E3 : 325 Triples, 70 Primitives
Perimeter up to 10E4 : 4858 Triples, 703 Primitives
Perimeter up to 10E5 : 64741 Triples, 7026 Primitives
Perimeter up to 10E6 : 808950 Triples, 70229 Primitives
Perimeter up to 10E7 : 9706567 Triples, 702309 Primitives
Perimeter up to 10E8 : 113236940 Triples, 7023027 Primitives

The code determines the number of Pythagorean triples with a perimeter not exceeding 100 and counts how many of these are primitive. It also handles larger values up to a maximum perimeter of 100,000,000. The code is based on an efficient method translated from C, as seen in the Ada example.


Library: Windows Forms
Uses: .NET Framework (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses library" (as page type) with input value "library/.NET Framework/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})
using System;
using System.Windows.Forms;

public class Window {
    [STAThread]
    static void Main() {
        Form form = new Form();

        form.Text = "Window";
        form.Disposed += delegate { Application.Exit(); };

        form.Show();
        Application.Run();
    }
}

"Creates an empty GUI window that can respond to close requests."


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
    {
        var dictionary = new SortedDictionary<TItem, int>();
        foreach (var item in items)
        {
            if (dictionary.ContainsKey(item))
            {
                dictionary[item]++;
            }
            else
            {
                dictionary[item] = 1;
            }
        }
        return dictionary;
    }

    static void Main(string[] arguments)
    {
        var file = arguments.FirstOrDefault();
        if (File.Exists(file))
        {
            var text = File.ReadAllText(file);
            foreach (var entry in GetFrequencies(text))
            {
                Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            }
        }
    }
}

"Opens a text file and counts the frequency of each letter, with some versions also counting all characters including punctuation."


class LinkedListNode
{
    public int Value { get; set; }
    public LinkedListNode Next { get; set; }

    // A constructor is not necessary, but could be useful.
    public Link(int value, LinkedListNode next = null)
    {
        Item = value;
        Next = next;
    }
}

class LinkedListNode<T>
{
    public T Value { get; set; }
    public LinkedListNode Next { get; set; }

    public Link(T value, LinkedListNode next = null)
    {
        Item = value;
        Next = next;
    }
}

unsafe struct link {
    public link* next;
    public int data;
};

Defines a data structure for a singly-linked list element. This element contains a numeric data member and a mutable link to the next element. The code is written in a C-like style.


static void Main (string[] args) {
    do {
        Console.WriteLine ("Number:");
        Int64 p = 0;
        do {
            try {
                p = Convert.ToInt64 (Console.ReadLine ());
                break;
            } catch (Exception) { }

        } while (true);

        Console.WriteLine ("For 1 through " + ((int) Math.Sqrt (p)).ToString () + "");
        for (int x = 1; x <= (int) Math.Sqrt (p); x++) {
            if (p % x == 0)
                Console.WriteLine ("Found: " + x.ToString () + ". " + p.ToString () + " / " + x.ToString () + " = " + (p / x).ToString ());
        }

        Console.WriteLine ("Done.");
    } while (true);
}

compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.


Works with: C# version 2+
using System;
class ColumnAlignerProgram
{
    delegate string Justification(string s, int width);

    static string[] AlignColumns(string[] lines, Justification justification)
    {
        const char Separator = '$';
        // build input table and calculate columns count
        string[][] table = new string[lines.Length][];
        int columns = 0;
        for (int i = 0; i < lines.Length; i++)
        {
            string[] row = lines[i].TrimEnd(Separator).Split(Separator);
            if (columns < row.Length) columns = row.Length;
            table[i] = row;
        }
        // create formatted table
        string[][] formattedTable = new string[table.Length][];
        for (int i = 0; i < formattedTable.Length; i++)
        {
            formattedTable[i] = new string[columns];
        }
        for (int j = 0; j < columns; j++)
        {
            // get max column width
            int columnWidth = 0;
            for (int i = 0; i < table.Length; i++)
            {
                if (j < table[i].Length && columnWidth < table[i][j].Length)
                    columnWidth = table[i][j].Length;
            }
            // justify column cells
            for (int i = 0; i < formattedTable.Length; i++)
            {
                if (j < table[i].Length)
                    formattedTable[i][j] = justification(table[i][j], columnWidth);
                else
                    formattedTable[i][j] = new String(' ', columnWidth);
            }
        }
        // create result
        string[] result = new string[formattedTable.Length];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = String.Join(" ", formattedTable[i]);
        }
        return result;
    }

    static string JustifyLeft(string s, int width) { return s.PadRight(width); }
    static string JustifyRight(string s, int width) { return s.PadLeft(width); }
    static string JustifyCenter(string s, int width)
    {
        return s.PadLeft((width + s.Length) / 2).PadRight(width);
    }

    static void Main()
    {
        string[] input = {
            "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
            "are$delineated$by$a$single$'dollar'$character,$write$a$program",
            "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
            "column$are$separated$by$at$least$one$space.",
            "Further,$allow$for$each$word$in$a$column$to$be$either$left$",
            "justified,$right$justified,$or$center$justified$within$its$column.",
        };

        foreach (string line in AlignColumns(input, JustifyCenter))
        {
            Console.WriteLine(line);
        }
    }
}

Works with: C# version 8+
using System;
using System.Linq;

enum Justification { Left, Center, Right }

public class Program
{
    static void Main()
    {
        string text =
@"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.";

        AlignColumns(text, Justification.Left);
        Console.WriteLine();
        AlignColumns(text, Justification.Center);
        Console.WriteLine();
        AlignColumns(text, Justification.Right);
    }

    public static void AlignColumns(string text, Justification justification) =>
        AlignColumns(text.Split(Environment.NewLine), justification);

    public static void AlignColumns(string[] lines, Justification justification) =>
        AlignColumns(lines.Select(line => line.Split('$')).ToArray(), justification);

    public static void AlignColumns(string[][] table, Justification justification)
    {
        Console.WriteLine(justification + ":");
        int columns = table.Max(line => line.Length);
        var columnWidths =
            Enumerable.Range(0, columns)
            .Select(i => table.Max(line => i < line.Length ? line[i].Length : 0)
            ).ToArray();

        foreach (var line in table) {
            Console.WriteLine(string.Join(" ",
                Enumerable.Range(0, line.Length)
                .Select(i => justification switch {
                    Justification.Left => line[i].PadRight(columnWidths[i]),
                    Justification.Right => line[i].PadLeft(columnWidths[i]),
                    _ => line[i].PadLeft(columnWidths[i] / 2).PadRight(columnWidths[i])
                })
            ));
        }
    }

}

The code reads a text file where fields within a line are separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It allows for each word in a column to be left justified, right justified, or center justified. The code uses C# 2's delegate feature to define the justification and newer features like LINQ, lambdas, and switch expressions. The minimum space between columns is computed from the text and not hard-coded.


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

namespace Cuboid
{
    public partial class Form1 : Form
    {
        double[][] nodes = {
            new double[] {-1, -1, -1}, new double[] {-1, -1, 1}, new double[] {-1, 1, -1},
            new double[] {-1, 1, 1}, new double[] {1, -1, -1}, new double[] {1, -1, 1},
            new double[] {1, 1, -1}, new double[] {1, 1, 1} };

        int[][] edges = {
            new int[] {0, 1}, new int[] {1, 3}, new int[] {3, 2}, new int[] {2, 0}, new int[] {4, 5},
            new int[] {5, 7}, new int[] {7, 6}, new int[] {6, 4}, new int[] {0, 4}, new int[] {1, 5},
            new int[] {2, 6}, new int[] {3, 7}};

        private int mouseX;
        private int prevMouseX;
        private int prevMouseY;
        private int mouseY;

        public Form1()
        {
            Width = Height = 640;
            StartPosition = FormStartPosition.CenterScreen;
            SetStyle(
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.UserPaint |
                ControlStyles.DoubleBuffer,
                true);

            MouseMove += (s, e) =>
            {
                prevMouseX = mouseX;
                prevMouseY = mouseY;
                mouseX = e.X;
                mouseY = e.Y;

                double incrX = (mouseX - prevMouseX) * 0.01;
                double incrY = (mouseY - prevMouseY) * 0.01;

                RotateCuboid(incrX, incrY);
                Refresh();
            };

            MouseDown += (s, e) =>
            {
                mouseX = e.X;
                mouseY = e.Y;
            };

            Scale(80, 120, 160);
            RotateCuboid(Math.PI / 5, Math.PI / 9);
        }

        private void RotateCuboid(double angleX, double angleY)
        {
            double sinX = Math.Sin(angleX);
            double cosX = Math.Cos(angleX);

            double sinY = Math.Sin(angleY);
            double cosY = Math.Cos(angleY);

            foreach (var node in nodes)
            {
                double x = node[0];
                double y = node[1];
                double z = node[2];

                node[0] = x * cosX - z * sinX;
                node[2] = z * cosX + x * sinX;

                z = node[2];

                node[1] = y * cosY - z * sinY;
                node[2] = z * cosY + y * sinY;
            }
        }

        private void Scale(int v1, int v2, int v3)
        {
            foreach (var item in nodes)
            {
                item[0] *= v1;
                item[1] *= v2;
                item[2] *= v3;
            }
        }

        protected override void OnPaint(PaintEventArgs args)
        {
            var g = args.Graphics;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.Clear(Color.White);

            g.TranslateTransform(Width / 2, Height / 2);

            foreach (var edge in edges)
            {
                double[] xy1 = nodes[edge[0]];
                double[] xy2 = nodes[edge[1]];
                g.DrawLine(Pens.Black, (int)Math.Round(xy1[0]), (int)Math.Round(xy1[1]),
                        (int)Math.Round(xy2[0]), (int)Math.Round(xy2[1]));
            }

            foreach (var node in nodes)
            {
                g.FillEllipse(Brushes.Black, (int)Math.Round(node[0]) - 4,
                    (int)Math.Round(node[1]) - 4, 8, 8);
            }
        }
    }
}

generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.


// Requires adding a reference to System.DirectoryServices
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP://DC=onecity,DC=corp,DC=fabrikam,DC=com");

establish a connection to an Active Directory or Lightweight Directory Access Protocol server.


using System;
using System;
using System.IO;
using System.Linq;
using System.Text;

class Program {
    private static char shift(char c) {
		return c.ToString().ToLower().First() switch {
			>= 'a' and <= 'm' => (char)(c + 13),
			>= 'n' and <= 'z' => (char)(c - 13),
			var _ => c
		};
    }

    static string Rot13(string s)
    	=> new string(message.Select(c => shift(c)).ToArray());

    static void Main(string[] args) {
        foreach (var file in args.Where(file => File.Exists(file))) {
            Console.WriteLine(Rot13(File.ReadAllText(file)));
        }
        if (!args.Any()) {
            Console.WriteLine(Rot13(Console.In.ReadToEnd()));
        }
    }
}

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


Works with: C# version 3+
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    struct Entry
    {
        public Entry(string name, double value) { Name = name; Value = value; }
        public string Name;
        public double Value;
    }

    static void Main(string[] args)
    {
        var Elements = new List<Entry>
        {
            new Entry("Krypton", 83.798), new Entry("Beryllium", 9.012182), new Entry("Silicon", 28.0855),
            new Entry("Cobalt", 58.933195), new Entry("Selenium", 78.96), new Entry("Germanium", 72.64)
        };

        var sortedElements = Elements.OrderBy(e => e.Name);

        foreach (Entry e in sortedElements)
            Console.WriteLine("{0,-11}{1}", e.Name, e.Value);
    }
}

Beryllium  9.012182
Cobalt     58.933195
Germanium  72.64
Krypton    83.798
Selenium   78.96
Silicon    28.0855

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.


using System;

class Program {
    static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                Console.Write("*");
            }
            Console.WriteLine();
        }
    }
}

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";

Dictionary<string, string> map = new Dictionary<string,string>();
map[ "key1" ] = "foo";

Works with: C# version 3.0+
var map = new Dictionary<string, string> {{"key1", "foo"}};

create an associative array (dictionary, map, or hash) in .NET 1.x and .NET 2.0 platforms.


Works with: C# version 6+
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;

namespace LinearCongruentialGenerator
{
    static class LinearCongruentialGenerator
    {
        static int _seed = (int)DateTime.Now.Ticks; // from bad random gens might as well have bad seed!
        static int _bsdCurrent = _seed;
        static int _msvcrtCurrent = _seed;

        static int Next(int seed, int a, int b) => (a * seed + b) & int.MaxValue;

        static int BsdRand() => _bsdCurrent = Next(_bsdCurrent, 1103515245, 12345);

        static int MscvrtRand() => _msvcrtCurrent = Next (_msvcrtCurrent << 16,214013,2531011) >> 16;

        static void PrintRandom(int count, bool isBsd)
        {
            var name = isBsd ? "BSD" : "MS";
            WriteLine($"{name} next {count} Random");
            var gen = isBsd ? (Func<int>)(BsdRand) : MscvrtRand;
            foreach (var r in Enumerable.Repeat(gen, count))
                WriteLine(r.Invoke());
        }

        static void Main(string[] args)
        {
            PrintRandom(10, true);
            PrintRandom(10, false);
            Read();
        }
    }
}

BSD next 10 Random
1587930915
19022880
1025044953
1143293854
1642451583
1110934092
773706389
1830436778
1527715739
2072016696
MS next 10 Random
24368
8854
28772
16122
11064
24190
23724
6690
14784
21222

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

namespace FreeCellDeals
{
    public class LCG
    {
        private int _state;
        public bool Microsoft { get; set;}
        public bool BSD
        {
            get
            {
                return !Microsoft;
            }
            set
            {
                Microsoft = !value;
            }
        }

        public LCG(bool microsoft = true)
        {
            _state = (int)DateTime.Now.Ticks;
            Microsoft = microsoft;
        }

        public LCG(int n, bool microsoft = true)
        {
            _state = n;
            Microsoft = microsoft;
        }

        public int Next()
        {
            if (BSD)
            {
                return _state = (1103515245 * _state + 12345) & int.MaxValue;
            }
            return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16;
        }

        public IEnumerable<int> Seq()
        {
            while (true)
            {
                yield return Next();
            }
        }
    }

    class Program
    {
        static void Main()
        {
            LCG ms = new LCG(0, true);
            LCG bsd = new LCG(0,false);
            Console.WriteLine("Microsoft");
            ms.Seq().Take(10).ToList().ForEach(Console.WriteLine);
            Console.WriteLine("\nBSD");
            bsd.Seq().Take(10).ToList().ForEach(Console.WriteLine);
            Console.ReadKey();
        }
    }
}

Microsoft
38
7719
21238
2437
8855
11797
8365
32285
10450
30612

BSD
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
551188310

The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). The code uses the Linear Congruential Generator (LCG) formula to generate a sequence of random numbers. The generated sequence is identical to the original generator when starting from the same seed. The BSD and Microsoft formulas are used with specific constants. The code is not cryptographically secure but is sufficient for simple tasks like the Miller-Rabin primality test or FreeCell deals.


static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
    prev.Next = new Link() { Value = value, Next = prev.Next };
}

static void Main()
{
    //Create A(5)->B(7)
    var A = new LinkedListNode<int>() { Value = 5 };
    InsertAfter(A, 7);
    //Insert C between A and B
    InsertAfter(A, 15);
}

The code defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element 'C' into a list containing elements 'A' and 'B', placing 'C' after 'A'. It utilizes a generic version of the node type and creates nodes from the passed data.


Works with: C# version 3+
Library: System.Linq
using System;
using System.Linq;

namespace RosettaCode.Tasks
{
	public static class EthiopianMultiplication_Task
	{
		public static void Test ( )
		{
			Console.WriteLine ( "Ethiopian Multiplication" );
			int A = 17, B = 34;
			Console.WriteLine ( "Recursion: {0}*{1}={2}", A, B, EM_Recursion ( A, B ) );
			Console.WriteLine ( "Linq: {0}*{1}={2}", A, B, EM_Linq ( A, B ) );
			Console.WriteLine ( "Loop: {0}*{1}={2}", A, B, EM_Loop ( A, B ) );
			Console.WriteLine ( );
		}

		public static int Halve ( this int p_Number )
		{
			return p_Number >> 1;
		}
		public static int Double ( this int p_Number )
		{
			return p_Number << 1;
		}
		public static bool IsEven ( this int p_Number )
		{
			return ( p_Number % 2 ) == 0;
		}

		public static int EM_Recursion ( int p_NumberA, int p_NumberB )
		{
			//     Anchor Point,                Recurse to find the next row                                 Sum it with the second number according to the rules
			return p_NumberA == 1 ? p_NumberB : EM_Recursion ( p_NumberA.Halve ( ), p_NumberB.Double ( ) ) + ( p_NumberA.IsEven ( ) ? 0 : p_NumberB );
		}
		public static int EM_Linq ( int p_NumberA, int p_NumberB )
		{
			// Creating a range from 1 to x where x the number of times p_NumberA can be halved.
			// This will be 2^x where 2^x <= p_NumberA. Basically, ln(p_NumberA)/ln(2).
			return Enumerable.Range ( 1, Convert.ToInt32 ( Math.Log ( p_NumberA, Math.E ) / Math.Log ( 2, Math.E ) ) + 1 )
				// For every item (Y) in that range, create a new list, comprising the pair (p_NumberA,p_NumberB) Y times.
				.Select ( ( item ) => Enumerable.Repeat ( new { Col1 = p_NumberA, Col2 = p_NumberB }, item )
					// The aggregate method iterates over every value in the target list, passing the accumulated value and the current item's value.
					.Aggregate ( ( agg_pair, orig_pair ) => new { Col1 = agg_pair.Col1.Halve ( ), Col2 = agg_pair.Col2.Double ( ) } ) )
				// Remove all even items
				.Where ( pair => !pair.Col1.IsEven ( ) )
				// And sum!
				.Sum ( pair => pair.Col2 );
		}
		public static int EM_Loop ( int p_NumberA, int p_NumberB )
		{
			int RetVal = 0;
			while ( p_NumberA >= 1 )
			{
				RetVal += p_NumberA.IsEven ( ) ? 0 : p_NumberB;
				p_NumberA = p_NumberA.Halve ( );
				p_NumberB = p_NumberB.Double ( );
			}
			return RetVal;
		}
	}
}

The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.


Works with: C sharp version 8
using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;

public static class Solve24Game
{
    public static void Main2() {
        var testCases = new [] {
            new [] { 1,1,2,7 },
            new [] { 1,2,3,4 },
            new [] { 1,2,4,5 },
            new [] { 1,2,7,7 },
            new [] { 1,4,5,6 },
            new [] { 3,3,8,8 },
            new [] { 4,4,5,9 },
            new [] { 5,5,5,5 },
            new [] { 5,6,7,8 },
            new [] { 6,6,6,6 },
            new [] { 6,7,8,9 },
        };
        foreach (var t in testCases) Test(24, t);
        Test(100, 9,9,9,9,9,9);

        static void Test(int target, params int[] numbers) {
            foreach (var eq in GenerateEquations(target, numbers)) Console.WriteLine(eq);
            Console.WriteLine();
        }
    }

    static readonly char[] ops = { '*', '/', '+', '-' };
    public static IEnumerable<string> GenerateEquations(int target, params int[] numbers) {
        var operators = Repeat(ops, numbers.Length - 1).CartesianProduct().Select(e => e.ToArray()).ToList();
        return (
            from pattern in Patterns(numbers.Length)
            let expression = CreateExpression(pattern)
            from ops in operators
            where expression.WithOperators(ops).HasPreferredTree()
            from permutation in Permutations(numbers)
            let expr = expression.WithValues(permutation)
            where expr.Value == target && expr.HasPreferredValues()
            select $"{expr.ToString()} = {target}")
            .Distinct()
            .DefaultIfEmpty($"Cannot make {target} with {string.Join(", ", numbers)}");
    }

    ///Generates postfix expression trees where 1's represent operators and 0's represent numbers.
    static IEnumerable<int> Patterns(int length) {
        if (length == 1) yield return 0; //0
        if (length == 2) yield return 1; //001
        if (length < 3) yield break;
        //Of each tree, the first 2 bits must always be 0 and the last bit must be 1. Generate the bits in between.
        length -= 2;
        int len = length * 2 + 3;
        foreach (int permutation in BinaryPatterns(length, length * 2)) {
            (int p, int l) = ((permutation << 1) + 1, len);
            if (IsValidPattern(ref p, ref l)) yield return (permutation << 1) + 1;
        }
    }

    ///Generates all numbers with the given number of 1's and total length.
    static IEnumerable<int> BinaryPatterns(int ones, int length) {
        int initial = (1 << ones) - 1;
        int blockMask = (1 << length) - 1;
        for (int v = initial; v >= initial; ) {
            yield return v;
            int w = (v | (v - 1)) + 1;
            w |= (((w & -w) / (v & -v)) >> 1) - 1;
            v = w & blockMask;
        }
    }

    static bool IsValidPattern(ref int pattern, ref int len) {
        bool isNumber = (pattern & 1) == 0;
        pattern >>= 1;
        len--;
        if (isNumber) return true;
        IsValidPattern(ref pattern, ref len);
        IsValidPattern(ref pattern, ref len);
        return len == 0;
    }

    static Expr CreateExpression(int pattern) {
        return Create();

        Expr Create() {
            bool isNumber = (pattern & 1) == 0;
            pattern >>= 1;
            if (isNumber) return new Const(0);
            Expr right = Create();
            Expr left = Create();
            return new Binary('*', left, right);
        }
    }

    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() };
        return sequences.Aggregate(
            emptyProduct,
            (accumulator, sequence) =>
                from acc in accumulator
                from item in sequence
                select acc.Concat(new [] { item }));
    }

    private static List<int> helper = new List<int>();
    public static IEnumerable<T[]> Permutations<T>(params T[] input) {
        if (input == null || input.Length == 0) yield break;
        helper.Clear();
        for (int i = 0; i < input.Length; i++) helper.Add(i);
        while (true) {
            yield return input;
            int cursor = helper.Count - 2;
            while (cursor >= 0 && helper[cursor] > helper[cursor + 1]) cursor--;
            if (cursor < 0) break;
            int i = helper.Count - 1;
            while (i > cursor && helper[i] < helper[cursor]) i--;
            (helper[cursor], helper[i]) = (helper[i], helper[cursor]);
            (input[cursor], input[i]) = (input[i], input[cursor]);
            int firstIndex = cursor + 1;
            for (int lastIndex = helper.Count - 1; lastIndex > firstIndex; ++firstIndex, --lastIndex) {
                (helper[firstIndex], helper[lastIndex]) = (helper[lastIndex], helper[firstIndex]);
                (input[firstIndex], input[lastIndex]) = (input[lastIndex], input[firstIndex]);
            }
        }
    }

    static Expr WithOperators(this Expr expr, char[] operators) {
        int i = 0;
        SetOperators(expr, operators, ref i);
        return expr;

        static void SetOperators(Expr expr, char[] operators, ref int i) {
            if (expr is Binary b) {
                b.Symbol = operators[i++];
                SetOperators(b.Right, operators, ref i);
                SetOperators(b.Left, operators, ref i);
            }
        }
    }

    static Expr WithValues(this Expr expr, int[] values) {
        int i = 0;
        SetValues(expr, values, ref i);
        return expr;

        static void SetValues(Expr expr, int[] values, ref int i) {
            if (expr is Binary b) {
                SetValues(b.Left, values, ref i);
                SetValues(b.Right, values, ref i);
            } else {
                expr.Value = values[i++];
            }
        }
    }

    static bool HasPreferredTree(this Expr expr) => expr switch {
        Const _ => true,

        // a / b * c => a * c / b
        ((_, '/' ,_), '*', _) => false,
        // c + a * b => a * b + c
        (var l, '+', (_, '*' ,_) r) when l.Depth < r.Depth => false,
        // c + a / b => a / b + c
        (var l, '+', (_, '/' ,_) r) when l.Depth < r.Depth => false,
        // a * (b + c) => (b + c) * a
        (var l, '*', (_, '+' ,_) r) when l.Depth < r.Depth => false,
        // a * (b - c) => (b - c) * a
        (var l, '*', (_, '-' ,_) r) when l.Depth < r.Depth => false,
        // (a +- b) + (c */ d) => ((c */ d) + a) +- b
        ((_, var p, _), '+', (_, var q, _)) when "+-".Contains(p) && "*/".Contains(q) => false,
        // a + (b + c) => (a + b) + c
        (var l, '+', (_, '+' ,_) r) => false,
        // a + (b - c) => (a + b) - c
        (var l, '+', (_, '-' ,_) r) => false,
        // a - (b + c) => (a - b) + c
        (_, '-', (_, '+', _)) => false,
        // a * (b * c) => (a * b) * c
        (var l, '*', (_, '*' ,_) r) => false,
        // a * (b / c) => (a * b) / c
        (var l, '*', (_, '/' ,_) r) => false,
        // a / (b / c) => (a * c) / b
        (var l, '/', (_, '/' ,_) r) => false,
        // a - (b - c) * d => (c - b) * d + a
        (_, '-', ((_, '-' ,_), '*', _)) => false,
        // a - (b - c) / d => (c - b) / d + a
        (_, '-', ((_, '-' ,_), '/', _)) => false,
        // a - (b - c) => a + c - b
        (_, '-', (_, '-', _)) => false,
        // (a - b) + c => (a + c) - b
        ((_, '-', var b), '+', var c) => false,

        (var l, _, var r) => l.HasPreferredTree() && r.HasPreferredTree()
    };

    static bool HasPreferredValues(this Expr expr) => expr switch {
        Const _ => true,

        // -a + b => b - a
        (var l, '+', var r) when l.Value < 0 && r.Value >= 0 => false,
        // b * a => a * b
        (var l, '*', var r) when l.Depth == r.Depth && l.Value > r.Value => false,
        // b + a => a + b
        (var l, '+', var r) when l.Depth == r.Depth && l.Value > r.Value => false,
        // (b o c) * (a o d) => (a o d) * (b o c)
        ((var a, _, _) l, '*', (var c, _, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false,
        // (b o c) + (a o d) => (a o d) + (b o c)
        ((var a, var p, _) l, '+', (var c, var q, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false,
        // (a * c) * b => (a * b) * c
        ((_, '*', var c), '*', var b) when b.Value < c.Value => false,
        // (a + c) + b => (a + b) + c
        ((_, '+', var c), '+', var b) when b.Value < c.Value => false,
        // (a - b) - c => (a - c) - b
        ((_, '-', var b), '-', var c) when b.Value < c.Value => false,
        // a / 1 => a * 1
        (_, '/', var b) when b.Value == 1 => false,
        // a * b / b => a + b - b
        ((_, '*', var b), '/', var c) when b.Value == c.Value => false,
        // a * 1 * 1 => a + 1 - 1
        ((_, '*', var b), '*', var c) when b.Value == 1 && c.Value == 1 => false,

        (var l, _, var r) => l.HasPreferredValues() && r.HasPreferredValues()
    };

    private struct Fraction : IEquatable<Fraction>, IComparable<Fraction>
    {
        public readonly int Numerator, Denominator;

        public Fraction(int numerator, int denominator)
            => (Numerator, Denominator) = (numerator, denominator) switch
        {
            (_, 0) => (Math.Sign(numerator), 0),
            (0, _) => (0, 1),
            (_, var d) when d < 0 => (-numerator, -denominator),
            _ => (numerator, denominator)
        };

        public static implicit operator Fraction(int i) => new Fraction(i, 1);
        public static Fraction operator +(Fraction a, Fraction b) =>
            new Fraction(a.Numerator * b.Denominator + a.Denominator * b.Numerator, a.Denominator * b.Denominator);
        public static Fraction operator -(Fraction a, Fraction b) =>
            new Fraction(a.Numerator * b.Denominator + a.Denominator * -b.Numerator, a.Denominator * b.Denominator);
        public static Fraction operator *(Fraction a, Fraction b) =>
            new Fraction(a.Numerator * b.Numerator, a.Denominator * b.Denominator);
        public static Fraction operator /(Fraction a, Fraction b) =>
            new Fraction(a.Numerator * b.Denominator, a.Denominator * b.Numerator);

        public static bool operator ==(Fraction a, Fraction b) => a.CompareTo(b) == 0;
        public static bool operator !=(Fraction a, Fraction b) => a.CompareTo(b) != 0;
        public static bool operator  <(Fraction a, Fraction b) => a.CompareTo(b)  < 0;
        public static bool operator  >(Fraction a, Fraction b) => a.CompareTo(b)  > 0;
        public static bool operator <=(Fraction a, Fraction b) => a.CompareTo(b) <= 0;
        public static bool operator >=(Fraction a, Fraction b) => a.CompareTo(b) >= 0;

        public bool Equals(Fraction other) => Numerator == other.Numerator && Denominator == other.Denominator;
        public override string ToString() => Denominator == 1 ? Numerator.ToString() : $"[{Numerator}/{Denominator}]";

        public int CompareTo(Fraction other) => (Numerator, Denominator, other.Numerator, other.Denominator) switch {
            var (    n1, d1,     n2, d2) when n1 == n2 && d1 == d2 => 0,
                (     0,  0,      _,  _) => (-1),
                (     _,  _,      0,  0) => 1,
            var (    n1, d1,     n2, d2) when d1 == d2 => n1.CompareTo(n2),
                (var n1,  0,      _,  _) => Math.Sign(n1),
                (     _,  _, var n2,  0) => Math.Sign(n2),
            var (    n1, d1,     n2, d2) => (n1 * d2).CompareTo(n2 * d1)
        };
    }

    private abstract class Expr
    {
        protected Expr(char symbol) => Symbol = symbol;
        public char Symbol { get; set; }
        public abstract Fraction Value { get; set; }
        public abstract int Depth { get; }
        public abstract void Deconstruct(out Expr left, out char symbol, out Expr right);
    }

    private sealed class Const : Expr
    {
        public Const(Fraction value) : base('c') => Value = value;
        public override Fraction Value { get; set; }
        public override int Depth => 0;
        public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (this, Symbol, this);
        public override string ToString() => Value.ToString();
    }

    private sealed class Binary : Expr
    {
        public Binary(char symbol, Expr left, Expr right) : base(symbol) => (Left, Right) = (left, right);
        public Expr Left { get; }
        public Expr Right { get; }
        public override int Depth => Math.Max(Left.Depth, Right.Depth) + 1;
        public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (Left, Symbol, Right);

        public override Fraction Value {
            get => Symbol switch {
                '*' => Left.Value * Right.Value,
                '/' => Left.Value / Right.Value,
                '+' => Left.Value + Right.Value,
                '-' => Left.Value - Right.Value,
                _ => throw new InvalidOperationException() };
            set {}
        }

        public override string ToString() => Symbol switch {
            '*' => ToString("+-".Contains(Left.Symbol), "+-".Contains(Right.Symbol)),
            '/' => ToString("+-".Contains(Left.Symbol), "*/+-".Contains(Right.Symbol)),
            '+' => ToString(false, false),
            '-' => ToString(false, "+-".Contains(Right.Symbol)),
            _ => $"[{Value}]"
        };

        private string ToString(bool wrapLeft, bool wrapRight) =>
            $"{(wrapLeft ? $"({Left})" : $"{Left}")} {Symbol} {(wrapRight ? $"({Right})" : $"{Right}")}";
    }
}

The code takes four digits as input, either provided by the user or generated randomly, and computes arithmetic expressions based on the rules of the 24 game. It generates binary trees, creates permutations, forms expressions, and evaluates them. The code also filters out redundant expressions. It can work with other targets and more numbers, but the performance may slow down.


using System;

class Program
{
    static int Factorial(int number)
    {
        if(number < 0)
            throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");

        var accumulator = 1;
        for (var factor = 1; factor <= number; factor++)
        {
            accumulator *= factor;
        }
        return accumulator;
    }

    static void Main()
    {
        Console.WriteLine(Factorial(10));
    }
}

using System;

class Program
{
    static int Factorial(int number)
    {
        if(number < 0)
            throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");

        return number == 0 ? 1 : number * Factorial(number - 1);
    }

    static void Main()
    {
        Console.WriteLine(Factorial(10));
    }
}

Tail using System;

class Program
{
    static int Factorial(int number)
    {
        if(number < 0)
            throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");

        return Factorial(number, 1);
    }

    static int Factorial(int number, int accumulator)
    {
        if(number < 0)
            throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");
        if(accumulator < 1)
            throw new ArgumentOutOfRangeException(nameof(accumulator), accumulator, "Must be a positive number.");

        return number == 0 ? accumulator : Factorial(number - 1, number * accumulator);
    }

    static void Main()
    {
        Console.WriteLine(Factorial(10));
    }
}

using System;
using System.Linq;

class Program
{
    static int Factorial(int number)
    {
        return Enumerable.Range(1, number).Aggregate((accumulator, factor) => accumulator * factor);
    }

    static void Main()
    {
        Console.WriteLine(Factorial(10));
    }
}

Library: System.Numerics

using System;
using System.Numerics;
using System.Linq;
class Program
{
    static BigInteger factorial(int n) // iterative
    {
        BigInteger acc = 1; for (int i = 1; i <= n; i++) acc *= i; return acc;
    }

    static public BigInteger Factorial(int number) // functional
    {
        return Enumerable.Range(1, number).Aggregate(new BigInteger(1), (acc, num) => acc * num);
    }

    static public BI FactorialQ(int number) // functional quick, uses prodtree method
    {
        var s = Enumerable.Range(1, number).Select(num => new BI(num)).ToArray();
        int top = s.Length, nt, i, j;
        while (top > 1) {
            for (i = 0, j = top, nt = top >> 1; i < nt; i++) s[i] *= s[--j];
            top = nt + ((top & 1) == 1 ? 1 : 0);
        }
        return s[0];
    }

    static void Main(string[] args)
    {
        Console.WriteLine(Factorial(250));
    }
}

The code implements a function to calculate the factorial of a given number. The factorial function multiplies a sequence of descending positive integers from the given number down to 1. The function can handle both iterative and recursive solutions, and optionally supports error handling for negative inputs. The code also includes a comparison between the plain method and the product tree method for calculating factorials, demonstrating that the product tree method is more efficient for large inputs.


using System;

namespace BullsnCows
{
    class Program
    {

        static void Main(string[] args)
        {
            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            KnuthShuffle<int>(ref nums);
            int[] chosenNum = new int[4];
            Array.Copy(nums, chosenNum, 4);

            Console.WriteLine("Your Guess ?");
            while (!game(Console.ReadLine(), chosenNum))
            {
                Console.WriteLine("Your next Guess ?");
            }

            Console.ReadKey();
        }

        public static void KnuthShuffle<T>(ref T[] array)
        {
            System.Random random = new System.Random();
            for (int i = 0; i < array.Length; i++)
            {
                int j = random.Next(array.Length);
                T temp = array[i]; array[i] = array[j]; array[j] = temp;
            }
        }

        public static bool game(string guess, int[] num)
        {
            char[] guessed = guess.ToCharArray();
            int bullsCount = 0, cowsCount = 0;

            if (guessed.Length != 4)
            {
                Console.WriteLine("Not a valid guess.");
                return false;
            }

            for (int i = 0; i < 4; i++)
            {
                int curguess = (int) char.GetNumericValue(guessed[i]);
                if (curguess < 1 || curguess > 9)
                {
                    Console.WriteLine("Digit must be ge greater 0 and lower 10.");
                    return false;
                }
                if (curguess == num[i])
                {
                    bullsCount++;
                }
                else
                {
                    for (int j = 0; j < 4; j++)
                    {
                        if (curguess == num[j])
                            cowsCount++;
                    }
                }
            }

            if (bullsCount == 4)
            {
                Console.WriteLine("Congratulations! You have won!");
                return true;
            }
            else
            {
                Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount);
                return false;
            }
        }
    }
}

generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.


private static double randomNormal()
{
	return Math.Cos(2 * Math.PI * tRand.NextDouble()) * Math.Sqrt(-2 * Math.Log(tRand.NextDouble()));
}

static Random tRand = new Random();

static void Main(string[] args)
{
	double[] a = new double[1000];

	double tAvg = 0;
	for (int x = 0; x < a.Length; x++)
	{
		a[x] = randomNormal() / 2 + 1;
		tAvg += a[x];
	}

	tAvg /= a.Length;
	Console.WriteLine("Average: " + tAvg.ToString());

	double s = 0;
	for (int x = 0; x < a.Length; x++)
	{
		s += Math.Pow((a[x] - tAvg), 2);
	}
	s = Math.Sqrt(s / 1000);

	Console.WriteLine("Standard Deviation: " + s.ToString());

	Console.ReadLine();
}

Average: 1,00510073053613
Standard Deviation: 0,502540443430955

generates a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5. If the library only supports uniformly distributed random numbers, it applies a specific algorithm to achieve the normal distribution. It also calculates the average and standard deviation of the generated numbers.


static void Main(string[] args)
{
	Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 }));
	Console.Read();
}

private static decimal DotProduct(decimal[] vec1, decimal[] vec2)
{
	if (vec1 == null)
		return 0;

	if (vec2 == null)
		return 0;

	if (vec1.Length != vec2.Length)
		return 0;

	decimal tVal = 0;
	for (int x = 0; x < vec1.Length; x++)
	{
		tVal += vec1[x] * vec2[x];
	}

	return tVal;
}

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // For stdin, you could use
        // new StreamReader(Console.OpenStandardInput(), Console.InputEncoding)

        using (var b = new StreamReader("file.txt"))
        {
            string line;
            while ((line = b.ReadLine()) != null)
                Console.WriteLine(line);
        }
    }
}

"Continuously read words or lines from a text stream until there is no more data available."


using System.Xml;
using System.Xml.Serialization;
[XmlRoot("root")]
public class ExampleXML
{
    [XmlElement("element")]
    public string element = "Some text here";
    static void Main(string[] args)
    {
        var xmlnamespace = new XmlSerializerNamespaces();
        xmlnamespace.Add("", ""); //used to stop default namespaces from printing
        var writer = XmlWriter.Create("output.xml");
        new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace);
    }
    //

The code creates a simple DOM and serializes it into XML format using the System.Xml.Serialization library of .Net. The resulting XML contains a root element with a nested element that contains some text.


the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.


static int[] sedol_weights = { 1, 3, 1, 7, 3, 9 };
static int sedolChecksum(string sedol)
{
    int len = sedol.Length;
    int sum = 0;

    if (len == 7) //SEDOL code already checksummed?
        return (int)sedol[6];

    if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, "[AEIOUaeiou]+")) //invalid SEDOL
        return -1;

    for (int i = 0; i < 6; i++)
    {
        if (Char.IsDigit(sedol[i]))
            sum += (((int)sedol[i] - 48) * sedol_weights[i]);

        else if (Char.IsLetter(sedol[i]))
            sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]);

        else
            return -1;

    }

    return (10 - (sum % 10)) % 10;
}

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.


using System;

namespace Sphere {
    internal class Program {
        private const string Shades = ".:!*oe%&#@";
        private static readonly double[] Light = {30, 30, -50};

        private static void Normalize(double[] v) {
            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
            v[0] /= len;
            v[1] /= len;
            v[2] /= len;
        }

        private static double Dot(double[] x, double[] y) {
            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
            return d < 0 ? -d : 0;
        }

        public static void DrawSphere(double r, double k, double ambient) {
            var vec = new double[3];
            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {
                double x = i + .5;
                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {
                    double y = j/2.0 + .5;
                    if(x*x + y*y <= r*r) {
                        vec[0] = x;
                        vec[1] = y;
                        vec[2] = Math.Sqrt(r*r - x*x - y*y);
                        Normalize(vec);
                        double b = Math.Pow(Dot(Light, vec), k) + ambient;
                        int intensity = (b <= 0)
                                            ? Shades.Length - 2
                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);
                        Console.Write(Shades[intensity]);
                    }
                    else
                        Console.Write(' ');
                }
                Console.WriteLine();
            }
        }

        private static void Main() {
            Normalize(Light);
            DrawSphere(6, 4, .1);
            DrawSphere(10, 2, .4);
            Console.ReadKey();
        }
    }
}

"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection."


using System;
using System.Linq;

class Program
{
    private static string Ordinalize(int i)
    {
        i = Math.Abs(i);

        if (new[] {11, 12, 13}.Contains(i%100))
            return i + "th";

        switch (i%10)
        {
            case 1:
                return i + "st";
            case 2:
                return i + "nd";
            case 3:
                return i + "rd";
            default:
                return i + "th";
        }
    }

    static void Main()
    {
        Console.WriteLine(string.Join(" ", Enumerable.Range(0, 26).Select(Ordinalize)));
        Console.WriteLine(string.Join(" ", Enumerable.Range(250, 16).Select(Ordinalize)));
        Console.WriteLine(string.Join(" ", Enumerable.Range(1000, 26).Select(Ordinalize)));
    }
}

using System;

static string Ordinalize(int i)
{
    return i + (
        i % 100 is >= 11 and <= 13 ? "th" :
        i % 10 == 1 ? "st" :
        i % 10 == 2 ? "nd" :
        i % 10 == 3 ? "rd" :
        "th");
}

static void PrintRange(int begin, int end)
{
    for(var i = begin; i <= end; i++)
        Console.Write(Ordinalize(i) + (i == end ? "" : " "));
    Console.WriteLine();
}

PrintRange(0, 25);
PrintRange(250, 265);
PrintRange(1000, 1025);

The code defines a function that takes an integer greater than or equal to zero as input and returns a string representation of the number appended with its ordinal suffix. The function is used to generate and display the ordinal representation of numbers in the ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional. The implementation does not use LINQ and is compatible with Dotnet 5.


using System;

public static string RemoveCharactersFromString(string testString, string removeChars)
{
    char[] charAry = removeChars.ToCharArray();
    string returnString = testString;
    foreach (char c in charAry)
    {
        while (returnString.IndexOf(c) > -1)
        {
            returnString = returnString.Remove(returnString.IndexOf(c), 1);
        }
    }
    return returnString;
}

using System;

class Program
{
    static void Main(string[] args)
    {
        string testString = "She was a soul stripper. She took my heart!";
        string removeChars = "aei";
        Console.WriteLine(RemoveCharactersFromString(testString, removeChars));
    }
}

The code defines a function that removes a specific set of characters from a given string. The function takes two arguments: the original string and a string of characters to be removed. The function returns the original string with all instances of the characters in the second string removed.


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.


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!");
    }
};

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."


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.