title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Babbage problem
C sharp|C#
Charles Babbage Charles Babbage's analytical engine. Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: {{quote | What is the smallest positive integer whose square ends in the digits 269,696? | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. }} He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. ;Task The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L]. ;Motivation The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
namespace Babbage_Problem { class iterateNumbers { public iterateNumbers() { long baseNumberSquared = 0; //the base number multiplied by itself long baseNumber = 0; //the number to be squared, this one will be iterated do //this sets up the loop { baseNumber += 1; //add one to the base number baseNumberSquared = baseNumber * baseNumber; //multiply the base number by itself and store the value as baseNumberSquared } while (Right6Digits(baseNumberSquared) != 269696); //this will continue the loop until the right 6 digits of the base number squared are 269,696 Console.WriteLine("The smallest integer whose square ends in 269,696 is " + baseNumber); Console.WriteLine("The square is " + baseNumberSquared); } private long Right6Digits(long baseNumberSquared) { string numberAsString = baseNumberSquared.ToString(); //this is converts the number to a different type so it can be cut up if (numberAsString.Length < 6) { return baseNumberSquared; }; //if the number doesn't have 6 digits in it, just return it to try again. numberAsString = numberAsString.Substring(numberAsString.Length - 6); //this extracts the last 6 digits from the number return long.Parse(numberAsString); //return the last 6 digits of the number } } }}
Balanced brackets
C sharp|C#
'''Task''': * Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. * Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. ;Examples: (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
using System; using System.Linq; class Program { static bool IsBalanced(string text, char open = '[', char close = ']') { var level = 0; foreach (var character in text) { if (character == close) { if (level == 0) { return false; } level--; } if (character == open) { level++; } } return level == 0; } static string RandomBrackets(int count, char open = '[', char close = ']') { var random = new Random(); return string.Join(string.Empty, (new string(open, count) + new string(close, count)).OrderBy(c => random.Next())); } static void Main() { for (var count = 0; count < 9; count++) { var text = RandomBrackets(count); Console.WriteLine("\"{0}\" is {1}balanced.", text, IsBalanced(text) ? string.Empty : "not "); } } }
Balanced ternary
C sharp|C#
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. ;Examples: Decimal 11 = 32 + 31 - 30, thus it can be written as "++-" Decimal 6 = 32 - 31 + 0 x 30, thus it can be written as "+-0" ;Task: Implement balanced ternary representation of integers with the following: # Support arbitrarily large integers, both positive and negative; # Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). # Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated. # Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first. # Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable"). '''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-": * write out ''a'', ''b'' and ''c'' in decimal notation; * calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations. '''Note:''' The pages floating point balanced ternary.
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; // empty = 0 public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } // create from String public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } // convert long integer public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } // copy constructor public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } // only for internal use private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } // invert the values private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } // convert to string override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } // convert to long public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } // unary minus public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } // addition of digits private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } // addition of balanced ternary numbers public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } // subtraction of balanced ternary numbers public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } // multiplication of balanced ternary numbers public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Barnsley fern
C sharp|C#
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). ;Task: Create this fractal fern, using the following transformations: * f1 (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn * f2 (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = -0.04 xn + 0.85 yn + 1.6 * f3 (chosen 7% of the time) xn + 1 = 0.2 xn - 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 * f4 (chosen 7% of the time) xn + 1 = -0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
using System; using System.Diagnostics; using System.Drawing; namespace RosettaBarnsleyFern { class Program { static void Main(string[] args) { const int w = 600; const int h = 600; var bm = new Bitmap(w, h); var r = new Random(); double x = 0; double y = 0; for (int count = 0; count < 100000; count++) { bm.SetPixel((int)(300 + 58 * x), (int)(58 * y), Color.ForestGreen); int roll = r.Next(100); double xp = x; if (roll < 1) { x = 0; y = 0.16 * y; } else if (roll < 86) { x = 0.85 * x + 0.04 * y; y = -0.04 * xp + 0.85 * y + 1.6; } else if (roll < 93) { x = 0.2 * x - 0.26 * y; y = 0.23 * xp + 0.22 * y + 1.6; } else { x = -0.15 * x + 0.28 * y; y = 0.26 * xp + 0.24 * y + 0.44; } } const string filename = "Fern.png"; bm.Save(filename); Process.Start(filename); } } }
Base64 decode data
C sharp|C# from Visual Basic .NET
See [[Base64 encode data]]. Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
using System; using System.Text; namespace Base64DecodeData { class Program { static void Main(string[] args) { var data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="; Console.WriteLine(data); Console.WriteLine(); var decoded = Encoding.ASCII.GetString(Convert.FromBase64String(data)); Console.WriteLine(decoded); } } }
Bell numbers
C sharp|C# from D
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''. ;So: :'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }''' :'''B1 = 1''' There is only one way to partition a set with one element. '''{a}''' :'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}''' :'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}''' : and so on. A simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. ;Task: Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. If you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle. ;See also: :* '''OEIS:A000110 Bell or exponential numbers''' :* '''OEIS:A011971 Aitken's array'''
using System; using System.Numerics; namespace BellNumbers { public static class Utility { public static void Init<T>(this T[] array, T value) { if (null == array) return; for (int i = 0; i < array.Length; ++i) { array[i] = value; } } } class Program { static BigInteger[][] BellTriangle(int n) { BigInteger[][] tri = new BigInteger[n][]; for (int i = 0; i < n; ++i) { tri[i] = new BigInteger[i]; tri[i].Init(BigInteger.Zero); } tri[1][0] = 1; for (int i = 2; i < n; ++i) { tri[i][0] = tri[i - 1][i - 2]; for (int j = 1; j < i; ++j) { tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]; } } return tri; } static void Main(string[] args) { var bt = BellTriangle(51); Console.WriteLine("First fifteen and fiftieth Bell numbers:"); for (int i = 1; i < 16; ++i) { Console.WriteLine("{0,2}: {1}", i, bt[i][0]); } Console.WriteLine("50: {0}", bt[50][0]); Console.WriteLine(); Console.WriteLine("The first ten rows of Bell's triangle:"); for (int i = 1; i < 11; ++i) { //Console.WriteLine(bt[i]); var it = bt[i].GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", "); Console.Write(it.Current); } Console.WriteLine("]"); } } } }
Best shuffle
C sharp|C#
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did ''not'' change. ;Example: tree, eetr, (0) ;Test cases: abracadabra seesaw elk grrrrrr up a ;Related tasks * [[Anagrams/Deranged anagrams]] * [[Permutations/Derangements]]
using System; using System.Text; using System.Collections.Generic; namespace BestShuffle_RC { public class ShuffledString { private string original; private StringBuilder shuffled; private int ignoredChars; public string Original { get { return original; } } public string Shuffled { get { return shuffled.ToString(); } } public int Ignored { get { return ignoredChars; } } private void Swap(int pos1, int pos2) { char temp = shuffled[pos1]; shuffled[pos1] = shuffled[pos2]; shuffled[pos2] = temp; } //Determine if a swap between these two would put a letter in a "bad" place //If true, a swap is OK. private bool TrySwap(int pos1, int pos2) { if (original[pos1] == shuffled[pos2] || original[pos2] == shuffled[pos1]) return false; else return true; } //Constructor carries out calls Shuffle function. public ShuffledString(string word) { original = word; shuffled = new StringBuilder(word); Shuffle(); DetectIgnores(); } //Does the hard work of shuffling the string. private void Shuffle() { int length = original.Length; int swaps; Random rand = new Random(); List<int> used = new List<int>(); for (int i = 0; i < length; i++) { swaps = 0; while(used.Count <= length - i)//Until all possibilities have been tried { int j = rand.Next(i, length - 1); //If swapping would make a difference, and wouldn't put a letter in a "bad" place, //and hasn't already been tried, then swap if (original[i] != original[j] && TrySwap(i, j) && !used.Contains(j)) { Swap(i, j); swaps++; break; } else used.Add(j);//If swapping doesn't work, "blacklist" the index } if (swaps == 0) { //If a letter was ignored (no swap was found), look backward for another change to make for (int k = i; k >= 0; k--) { if (TrySwap(i, k)) Swap(i, k); } } //Clear the used indeces used.Clear(); } } //Count how many letters are still in their original places. private void DetectIgnores() { int ignores = 0; for (int i = 0; i < original.Length; i++) { if (original[i] == shuffled[i]) ignores++; } ignoredChars = ignores; } //To allow easy conversion of strings. public static implicit operator ShuffledString(string convert) { return new ShuffledString(convert); } } public class Program { public static void Main(string[] args) { ShuffledString[] words = { "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" }; foreach(ShuffledString word in words) Console.WriteLine("{0}, {1}, ({2})", word.Original, word.Shuffled, word.Ignored); Console.ReadKey(); } } }
Bin given limits
C sharp|C#
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ..'' bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] ;Task: The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will ''print the limit of each bin together with the count of items that fell in the range''. Assume the numbers to bin are too large to practically sort. ;Task examples: Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
Bitcoin/address validation
C sharp|C#
Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters: :::* 0 zero :::* O uppercase oh :::* I uppercase eye :::* l lowercase ell With this encoding, a bitcoin address encodes 25 bytes: * the first byte is the version number, which will be zero for this task ; * the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; * the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for [[SHA-256]]. ;Example of a bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
using System; using System.Linq; using System.Security.Cryptography; using NUnit.Framework; namespace BitcoinValidator { public class ValidateTest { [TestCase] public void ValidateBitcoinAddressTest() { Assert.IsTrue(ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); // VALID Assert.IsTrue(ValidateBitcoinAddress("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9")); // VALID Assert.Throws<Exception>(() => ValidateBitcoinAddress("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X")); // checksum changed, original data Assert.Throws<Exception>(() => ValidateBitcoinAddress("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); // data changed, original checksum Assert.Throws<Exception>(() => ValidateBitcoinAddress("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); // invalid chars Assert.Throws<Exception>(() => ValidateBitcoinAddress("BZbvjr")); // checksum is fine, address too short } public static bool ValidateBitcoinAddress(string address) { if (address.Length < 26 || address.Length > 35) throw new Exception("wrong length"); var decoded = DecodeBase58(address); var d1 = Hash(decoded.SubArray(0, 21)); var d2 = Hash(d1); if (!decoded.SubArray(21, 4).SequenceEqual(d2.SubArray(0, 4))) throw new Exception("bad digest"); return true; } const string Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const int Size = 25; private static byte[] DecodeBase58(string input) { var output = new byte[Size]; foreach (var t in input) { var p = Alphabet.IndexOf(t); if (p == -1) throw new Exception("invalid character found"); var j = Size; while (--j > 0) { p += 58 * output[j]; output[j] = (byte)(p % 256); p /= 256; } if (p != 0) throw new Exception("address too long"); } return output; } private static byte[] Hash(byte[] bytes) { var hasher = new SHA256Managed(); return hasher.ComputeHash(bytes); } } public static class ArrayExtensions { public static T[] SubArray<T>(this T[] data, int index, int length) { var result = new T[length]; Array.Copy(data, index, result, 0, length); return result; } } }
Bitwise IO
C sharp|C#
The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always ''quantized'' by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a '''rough''' (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words'' nine (or more) bits long. * Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. * Errors handling is not mandatory
using System; using System.IO; public class BitReader { uint readData = 0; int startPosition = 0; int endPosition = 0; public int InBuffer { get { return endPosition - startPosition; } } private Stream stream; public Stream BaseStream { get { return stream; } } public BitReader(Stream stream) { this.stream = stream; } void EnsureData(int bitCount) { int readBits = bitCount - InBuffer; while (readBits > 0) { int b = BaseStream.ReadByte(); if (b < 0) throw new InvalidOperationException("Unexpected end of stream"); readData |= checked((uint)b << endPosition); endPosition += 8; readBits -= 8; } } public bool ReadBit() { return Read(1) > 0; } public int Read(int bitCount) { EnsureData(bitCount); int result = (int)(readData >> startPosition) & ((1 << bitCount) - 1); startPosition += bitCount; if (endPosition == startPosition) { endPosition = startPosition = 0; readData = 0; } else if (startPosition >= 8) { readData >>= startPosition; endPosition -= startPosition; startPosition = 0; } return result; } public void Align() { endPosition = startPosition = 0; readData = 0; } } public class BitWriter { uint data = 0; int dataLength = 0; Stream stream; public Stream BaseStream { get { return stream; } } public int BitsToAligment { get { return (32 - dataLength) % 8; } } public BitWriter(Stream stream) { this.stream = stream; } public void WriteBit(bool value) { Write(value ? 1 : 0, 1); } public void Write(int value, int length) { uint currentData = data | checked((uint)value << dataLength); int currentLength = dataLength + length; while (currentLength >= 8) { BaseStream.WriteByte((byte)currentData); currentData >>= 8; currentLength -= 8; } data = currentData; dataLength = currentLength; } public void Align() { if (dataLength > 0) { BaseStream.WriteByte((byte)data); data = 0; dataLength = 0; } } } class Program { static void Main(string[] args) { MemoryStream ms = new MemoryStream(); BitWriter writer = new BitWriter(ms); writer.WriteBit(true); writer.Write(5, 3); writer.Write(0x0155, 11); writer.Align(); ms.Position = 0; BitReader reader = new BitReader(ms); Console.WriteLine(reader.ReadBit()); Console.WriteLine(reader.Read(3)); Console.WriteLine(reader.Read(11).ToString("x4")); reader.Align(); } }
Box the compass
C sharp|C#
Avast me hearties! There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! ;Task description: # Create a function that takes a heading in degrees and returns the correct 32-point compass heading. # Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: :[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). ;Notes; * The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 * The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
using System; using System.Collections.Generic; namespace BoxTheCompass { class Compass { string[] cp = new string[] {"North", "North by east", "North-northeast", "Northeast by north", "Northeast","Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South", "South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest", "West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west", "North"}; public void compassHeading(float a) { int h = Convert.ToInt32(Math.Floor(a / 11.25f + .5f)) % 32; Console.WriteLine( "{0,2}: {1,-22} : {2,6:N}",h + 1, cp[h], a ); } }; class Program { static void Main(string[] args) { Compass c = new Compass(); float[] degs = new float[] {0.0f, 16.87f, 16.88f, 33.75f, 50.62f, 50.63f, 67.5f, 84.37f, 84.38f, 101.25f, 118.12f, 118.13f, 135.0f, 151.87f, 151.88f, 168.75f, 185.62f, 185.63f, 202.5f, 219.37f, 219.38f, 236.25f, 253.12f, 253.13f, 270.0f, 286.87f, 286.88f, 303.75f, 320.62f, 320.63f, 337.5f, 354.37f, 354.38f}; foreach (float d in degs) c.compassHeading(d); Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(); } } }
Brazilian numbers
C sharp|C# from Go
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits. ;E.G.: :* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''. :* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same. :* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same. :* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same. :* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same. :* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same. :* ''and so on...'' All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''. More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1''' The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2 ;Task: Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; :* the first '''20''' Brazilian numbers; :* the first '''20 odd''' Brazilian numbers; :* the first '''20 prime''' Brazilian numbers; ;See also: :* '''OEIS:A125134 - Brazilian numbers''' :* '''OEIS:A257521 - Odd Brazilian numbers''' :* '''OEIS:A085104 - Prime Brazilian numbers'''
using System; class Program { static bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) if (n % b != f) return false; return true; } static bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0) return true; for (int b = 2; b < n - 1; b++) if (sameDigits(n, b)) return true; return false; } static bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d * d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false; d += 4; } return true; } static void Main(string[] args) { foreach (string kind in ",odd ,prime ".Split(',')) { bool quiet = false; int BigLim = 99999, limit = 20; Console.WriteLine("First {0} {1}Brazilian numbers:", limit, kind); int c = 0, n = 7; while (c < BigLim) { if (isBrazilian(n)) { if (!quiet) Console.Write("{0:n0} ", n); if (++c == limit) { Console.Write("\n\n"); quiet = true; } } if (quiet && kind != "") continue; switch (kind) { case "": n++; break; case "odd ": n += 2; break; case "prime ": while (true) { n += 2; if (isPrime(n)) break; } break; } } if (kind == "") Console.WriteLine("The {0:n0}th Brazilian number is: {1:n0}\n", BigLim + 1, n); } } }
Break OO privacy
C sharp|C#
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory. Note that cheating on your type system is almost universally regarded as unidiomatic at best, and poor programming practice at worst. Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
Burrows–Wheeler transform
C sharp|C# from D
{{Wikipedia|Burrows-Wheeler_transform}} The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows-Wheeler transform
using System; using System.Collections.Generic; using System.Linq; namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03; private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --i) { a[i] = a[i - 1]; } a[0] = t; } // For some reason, strings do not compare how whould be expected private static int Compare(string s1, string s2) { for (int i = 0; i < s1.Length && i < s2.Length; ++i) { if (s1[i] < s2[i]) { return -1; } if (s2[i] < s1[i]) { return 1; } } if (s1.Length < s2.Length) { return -1; } if (s2.Length < s1.Length) { return 1; } return 0; } static string Bwt(string s) { if (s.Any(a => a == STX || a == ETX)) { throw new ArgumentException("Input can't contain STX or ETX"); } char[] ss = (STX + s + ETX).ToCharArray(); List<string> table = new List<string>(); for (int i = 0; i < ss.Length; ++i) { table.Add(new string(ss)); Rotate(ref ss); } table.Sort(Compare); return new string(table.Select(a => a.Last()).ToArray()); } static string Ibwt(string r) { int len = r.Length; List<string> table = new List<string>(new string[len]); for (int i = 0; i < len; ++i) { for (int j = 0; j < len; ++j) { table[j] = r[j] + table[j]; } table.Sort(Compare); } foreach (string row in table) { if (row.Last() == ETX) { return row.Substring(1, len - 2); } } return ""; } static string MakePrintable(string s) { return s.Replace(STX, '^').Replace(ETX, '|'); } static void Main() { string[] tests = new string[] { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" }; foreach (string test in tests) { Console.WriteLine(MakePrintable(test)); Console.Write(" --> "); string t = ""; try { t = Bwt(test); Console.WriteLine(MakePrintable(t)); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } string r = Ibwt(t); Console.WriteLine(" --> {0}", r); Console.WriteLine(); } } } }
CSV data manipulation
C sharp|C#
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. ;Task: Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 Suggestions Show how to add a column, headed 'SUM', of the sums of the rows. If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
CSV to HTML translation
C sharp|C#
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be ''escaped'' when converted to HTML ;Task: Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. : Character,Speech : The multitude,The messiah! Show us the messiah! : Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! : The multitude,Who are you? : Brians mother,I'm his mother; that's who! : The multitude,Behold his mother! Behold his mother! ;Extra credit: ''Optionally'' allow special formatting for the first row of the table as if it is the tables header row (via preferably; CSS if you must).
using System; using System.Collections.Generic; using System.Linq; using System.Net; class Program { private static string ConvertCsvToHtmlTable(string csvText) { //split the CSV, assume no commas or line breaks in text List<List<string>> splitString = new List<List<string>>(); List<string> lineSplit = csvText.Split('\n').ToList(); foreach (string line in lineSplit) { splitString.Add(line.Split(',').ToList()); } //encode text safely, and create table string tableResult = "<table>"; foreach(List<string> splitLine in splitString) { tableResult += "<tr>"; foreach(string splitText in splitLine) { tableResult += "<td>" + WebUtility.HtmlEncode(splitText) + "</td>"; } tableResult += "</tr>"; } tableResult += "</table>"; return tableResult; } }
CSV to HTML translation
.NET Framework
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be ''escaped'' when converted to HTML ;Task: Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. : Character,Speech : The multitude,The messiah! Show us the messiah! : Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! : The multitude,Who are you? : Brians mother,I'm his mother; that's who! : The multitude,Behold his mother! Behold his mother! ;Extra credit: ''Optionally'' allow special formatting for the first row of the table as if it is the tables header row (via preferably; CSS if you must).
Imports Microsoft.VisualBasic.FileIO Module Program Sub Main(args As String()) Dim parser As TextFieldParser Try If args.Length > 1 Then parser = My.Computer.FileSystem.OpenTextFieldParser(args(1), ",") Else parser = New TextFieldParser(Console.In) With {.Delimiters = {","}} End If Dim getLines = Iterator Function() As IEnumerable(Of String()) Do Until parser.EndOfData Yield parser.ReadFields() Loop End Function Dim result = CSVTOHTML(getLines(), If(args.Length > 0, Boolean.Parse(args(0)), False)) Console.WriteLine(result) Finally If parser IsNot Nothing Then parser.Dispose() End Try End Sub Function CSVTOHTML(lines As IEnumerable(Of IEnumerable(Of String)), useTHead As Boolean) As XElement Dim getRow = Function(row As IEnumerable(Of String)) From field In row Select <td><%= field %></td> CSVTOHTML = <table> <%= From l In lines.Select( Function(line, i) If useTHead AndAlso i = 0 Then Return <thead><%= getRow(line) %></thead> Else Return <tr><%= getRow(line) %></tr> End If End Function) %> </table> End Function End Module
Calculating the value of e
C sharp|C#
Calculate the value of ''e''. (''e'' is also known as ''Euler's number'' and ''Napier's constant''.) See details: Calculating the value of e
using System; namespace CalculateE { class Program { public const double EPSILON = 1.0e-15; static void Main(string[] args) { ulong fact = 1; double e = 2.0; double e0; uint n = 2; do { e0 = e; fact *= n++; e += 1.0 / fact; } while (Math.Abs(e - e0) >= EPSILON); Console.WriteLine("e = {0:F15}", e); } } }
Call a function
C sharp|C#
Demonstrate the different syntax and semantics provided for calling a function. This may include: :* Calling a function that requires no arguments :* Calling a function with a fixed number of arguments :* Calling a function with optional arguments :* Calling a function with a variable number of arguments :* Calling a function with named arguments :* Using a function in statement context :* Using a function in first-class context within an expression :* Obtaining the return value of a function :* Distinguishing built-in functions and user-defined functions :* Distinguishing subroutines and functions ;* Stating whether arguments are passed by value or by reference ;* Is partial application possible and how This task is ''not'' about defining functions.
/* a function that has no argument */ public int MyFunction(); /* a function with a fixed number of arguments */ FunctionWithArguments(4, 3, 2); /* a function with optional arguments */ public void OptArg(); public static void Main() { OptArg(1); OptArg(1, 2); OptArg(1, 2, 3); } public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10) /* If you know the first and the last parameter */ ExampleMethod(3, optionalint: 4); /* If you know all the parameter */ ExampleMethod(3, "Hello World", 4); /* Variable number of arguments use array */ public static void UseVariableParameters(params int[] list) /* Obtain return value from function */ public internal MyFunction(); int returnValue = MyFunction();
Canonicalize CIDR
C sharp|C#
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. ;Example: Given '''87.70.141.1/22''', your code should output '''87.70.140.0/22''' ;Explanation: An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry. The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0. ;More examples for testing 36.18.154.103/12 - 36.16.0.0/12 62.62.197.11/29 - 62.62.197.8/29 67.137.119.181/4 - 64.0.0.0/4 161.214.74.21/24 - 161.214.74.0/24 184.232.176.184/18 - 184.232.128.0/18
using System; using System.Net; using System.Linq; public class Program { public static void Main() { string[] tests = { "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18" }; foreach (string t in tests) Console.WriteLine($"{t} => {Canonicalize(t)}"); } static string Canonicalize(string cidr) => CIDR.Parse(cidr).Canonicalize().ToString(); } readonly struct CIDR { public readonly IPAddress ip; public readonly int length; public static CIDR Parse(string cidr) { string[] parts = cidr.Split('/'); return new CIDR(IPAddress.Parse(parts[0]), int.Parse(parts[1])); } public CIDR(IPAddress ip, int length) => (this.ip, this.length) = (ip, length); public CIDR Canonicalize() => new CIDR( new IPAddress( ToBytes( ToInt( ip.GetAddressBytes() ) & ~((1 << (32 - length)) - 1) ) ), length ); private int ToInt(byte[] bytes) => bytes.Aggregate(0, (n, b) => (n << 8) | b); private byte[] ToBytes(int n) { byte[] bytes = new byte[4]; for (int i = 3; i >= 0; i--) { bytes[i] = (byte)(n & 0xFF); n >>= 8; } return bytes; } public override string ToString() => $"{ip}/{length}"; }
Cantor set
C sharp|C# from Java
Draw a Cantor set. See details at this Wikipedia webpage: Cantor set
using System; namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH]; static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } } private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i, j] = ' '; } } Cantor(start, seg, index + 1); Cantor(start + seg * 2, seg, index + 1); } static void Main(string[] args) { Cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
Cartesian product of two or more lists
C sharp|C#
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: ::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: ::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. :: {1, 2} x {} = {} :: {} x {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: :: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1} :: {1, 2, 3} x {30} x {500, 100} :: {1, 2, 3} x {} x {500, 100}
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Casting out nines
C sharp|C# from Java
Task (in three parts): ;Part 1 Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky. Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application. With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1. ;Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: : Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]). : note that 318682 has the same checksum as (101558 + 217124); : note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); : note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2. Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. ;Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: : \mathit{co9}(x) is the residual of x mod 9; : the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. ;related tasks * [[First perfect square in base N with N unique digits]] * [[Kaprekar numbers]]
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CastingOutNines { public static class Helper { public static string AsString<T>(this IEnumerable<T> e) { var it = e.GetEnumerator(); StringBuilder builder = new StringBuilder(); builder.Append("["); if (it.MoveNext()) { builder.Append(it.Current); } while (it.MoveNext()) { builder.Append(", "); builder.Append(it.Current); } builder.Append("]"); return builder.ToString(); } } class Program { static List<int> CastOut(int @base, int start, int end) { int[] ran = Enumerable .Range(0, @base - 1) .Where(a => a % (@base - 1) == (a * a) % (@base - 1)) .ToArray(); int x = start / (@base - 1); List<int> result = new List<int>(); while (true) { foreach (int n in ran) { int k = (@base - 1) * x + n; if (k < start) { continue; } if (k > end) { return result; } result.Add(k); } x++; } } static void Main() { Console.WriteLine(CastOut(16, 1, 255).AsString()); Console.WriteLine(CastOut(10, 1, 99).AsString()); Console.WriteLine(CastOut(17, 1, 288).AsString()); } } }
Catalan numbers/Pascal's triangle
C sharp|C# from C++
Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle. ;See: * Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction. * Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition. * Sequence A000108 on OEIS has a lot of information on Catalan Numbers. ;Related Tasks: [[Pascal's triangle]]
int n = 15; List<int> t = new List<int>() { 0, 1 }; for (int i = 1; i <= n; i++) { for (var j = i; j > 1; j--) t[j] += t[j - 1]; t.Add(t[i]); for (var j = i + 1; j > 1; j--) t[j] += t[j - 1]; Console.Write(((i == 1) ? "" : ", ") + (t[i + 1] - t[i])); }
Catamorphism
C sharp|C#
''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. ;Task: Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language. ;See also: * Wikipedia article: Fold * Wikipedia article: Catamorphism
var nums = Enumerable.Range(1, 10); int summation = nums.Aggregate((a, b) => a + b); int product = nums.Aggregate((a, b) => a * b); string concatenation = nums.Aggregate(String.Empty, (a, b) => a.ToString() + b.ToString()); Console.WriteLine("{0} {1} {2}", summation, product, concatenation);
Chaocipher
C sharp|C# from D
Description: The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ;Task: Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
using System; namespace Chaocipher { enum Mode { ENCRYPT, DECRYPT, } class Program { const string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; const string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; static string Exec(string text, Mode mode, bool showSteps = false) { char[] left = L_ALPHABET.ToCharArray(); char[] right = R_ALPHABET.ToCharArray(); char[] eText = new char[text.Length]; char[] temp = new char[26]; for (int i = 0; i < text.Length; ++i) { if (showSteps) Console.WriteLine("{0} {1}", string.Join("", left), string.Join("", right)); int index = 0; if (mode == Mode.ENCRYPT) { index = Array.IndexOf(right, text[i]); eText[i] = left[index]; } else { index = Array.IndexOf(left, text[i]); eText[i] = right[index]; } if (i == text.Length - 1) break; // permute left for (int j = index; j < 26; ++j) temp[j - index] = left[j]; for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j]; var store = temp[1]; for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; temp.CopyTo(left, 0); // permute right for (int j = index; j < 26; ++j) temp[j - index] = right[j]; for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j]; store = temp[0]; for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j]; temp[25] = store; store = temp[2]; for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; temp.CopyTo(right, 0); } return new string(eText); } static void Main(string[] args) { var plainText = "WELLDONEISBETTERTHANWELLSAID"; Console.WriteLine("The original plaintext is : {0}", plainText); Console.WriteLine("\nThe left and right alphabets after each permutation during encryption are :\n"); var cipherText = Exec(plainText, Mode.ENCRYPT, true); Console.WriteLine("\nThe ciphertext is : {0}", cipherText); var plainText2 = Exec(cipherText, Mode.DECRYPT); Console.WriteLine("\nThe recovered plaintext is : {0}", plainText2); } } }
Chaos game
C sharp|C#
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. ;Task Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. ;See also * The Game of Chaos
using System.Diagnostics; using System.Drawing; namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600); var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), new Point(300, 81) }; var r = new System.Random(); var p = new Point(r.Next(600), r.Next(600)); for (int count = 0; count < 10000; count++) { bm.SetPixel(p.X, p.Y, Color.Magenta); int i = r.Next(3); p.X = (p.X + referencePoints[i].X) / 2; p.Y = (p.Y + referencePoints[i].Y) / 2; } const string filename = "Chaos Game.png"; bm.Save(filename); Process.Start(filename); } } }
Check output device is a terminal
C sharp|C#
Demonstrate how to check whether the output device is a terminal or not. ;Related task: * [[Check input device is a terminal]]
using System; namespace CheckTerminal { class Program { static void Main(string[] args) { Console.WriteLine("Stdout is tty: {0}", Console.IsOutputRedirected); } } }
Cheryl's birthday
C sharp|C#
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. ;Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. ;Related task: * [[Sum and Product Puzzle]] ;References * Wikipedia article of the same name. * Tuple Relational Calculus
public static class CherylsBirthday { public static void Main() { var dates = new HashSet<(string month, int day)> { ("May", 15), ("May", 16), ("May", 19), ("June", 17), ("June", 18), ("July", 14), ("July", 16), ("August", 14), ("August", 15), ("August", 17) }; Console.WriteLine(dates.Count + " remaining."); //The month cannot have a unique day. var monthsWithUniqueDays = dates.GroupBy(d => d.day).Where(g => g.Count() == 1).Select(g => g.First().month).ToHashSet(); dates.RemoveWhere(d => monthsWithUniqueDays.Contains(d.month)); Console.WriteLine(dates.Count + " remaining."); //The day must now be unique. dates.IntersectWith(dates.GroupBy(d => d.day).Where(g => g.Count() == 1).Select(g => g.First())); Console.WriteLine(dates.Count + " remaining."); //The month must now be unique. dates.IntersectWith(dates.GroupBy(d => d.month).Where(g => g.Count() == 1).Select(g => g.First())); Console.WriteLine(dates.Single()); } }
Chinese remainder theorem
C sharp|C#
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv a_2 \pmod{n_2} \\ &{}\ \ \vdots \\ x &\equiv a_k \pmod{n_k} \end{align} Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. ;Task: Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. ''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2]. '''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: ::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows: For each i, the integers n_i and N/n_i are co-prime. Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. Then, one solution to the system of simultaneous congruences is: ::: x = \sum_{i=1}^k a_i s_i N/n_i and the minimal solution, ::: x \pmod{N}.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Chinese zodiac
C sharp|C# from Java
Determine the Chinese zodiac sign and related associations for a given year. Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades. Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit. The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang. Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin. ;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). ;Requisite information: * The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. * The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. * Each element gets two consecutive years; a yang followed by a yin. * The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from. Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. ;Information for optional task: * The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". * The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
using System; namespace ChineseZodiac { class Program { static string[] animals = { "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig" }; static string[] elements = { "Wood", "Fire", "Earth", "Metal", "Water" }; static string[] animalChars = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" }; static string[,] elementChars = { { "甲", "丙", "戊", "庚", "壬" }, { "乙", "丁", "己", "辛", "癸" } }; static string getYY(int year) { if (year % 2 == 0) { return "yang"; } return "yin"; } static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; int[] years = { 1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017 }; for (int i = 0; i < years.Length; i++) { int ei = (int)Math.Floor((years[i] - 4.0) % 10 / 2); int ai = (years[i] - 4) % 12; Console.WriteLine("{0} is the year of the {1} {2} ({3}). {4}{5}", years[i], elements[ei], animals[ai], getYY(years[i]), elementChars[years[i] % 2, ei], animalChars[(years[i] - 4) % 12]); } } } }
Church numerals
C sharp|C#
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. * '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. * '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)''' * '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))''' * and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: * Church Zero, * a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), * functions for Addition, Multiplication and Exponentiation over Church numerals, * a function to convert integers to corresponding Church numerals, * and a function to convert Church numerals to corresponding integers. You should: * Derive Church numerals three and four in terms of Church zero and a Church successor function. * use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, * similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, * convert each result back to an integer, and return it or print it to the console.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
Circles of given radius through two points
C sharp 6
2 circles with a given radius through 2 points in 2D space. Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. ;Exceptions: # r==0.0 should be treated as never describing circles (except in the case where the points are coincident). # If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. # If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language. # If the points are too far apart then no circles can be drawn. ;Task detail: * Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''. * Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 ;Related task: * [[Total circles area]]. ;See also: * Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
using System; public class CirclesOfGivenRadiusThroughTwoPoints { public static void Main() { double[][] values = new double[][] { new [] { 0.1234, 0.9876, 0.8765, 0.2345, 2 }, new [] { 0.0, 2.0, 0.0, 0.0, 1 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, 2 }, new [] { 0.1234, 0.9876, 0.8765, 0.2345, 0.5 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, 0 } }; foreach (var a in values) { var p = new Point(a[0], a[1]); var q = new Point(a[2], a[3]); Console.WriteLine($"Points {p} and {q} with radius {a[4]}:"); try { var centers = FindCircles(p, q, a[4]); Console.WriteLine("\t" + string.Join(" and ", centers)); } catch (Exception ex) { Console.WriteLine("\t" + ex.Message); } } } static Point[] FindCircles(Point p, Point q, double radius) { if(radius < 0) throw new ArgumentException("Negative radius."); if(radius == 0) { if(p == q) return new [] { p }; else throw new InvalidOperationException("No circles."); } if (p == q) throw new InvalidOperationException("Infinite number of circles."); double sqDistance = Point.SquaredDistance(p, q); double sqDiameter = 4 * radius * radius; if (sqDistance > sqDiameter) throw new InvalidOperationException("Points are too far apart."); Point midPoint = new Point((p.X + q.X) / 2, (p.Y + q.Y) / 2); if (sqDistance == sqDiameter) return new [] { midPoint }; double d = Math.Sqrt(radius * radius - sqDistance / 4); double distance = Math.Sqrt(sqDistance); double ox = d * (q.X - p.X) / distance, oy = d * (q.Y - p.Y) / distance; return new [] { new Point(midPoint.X - oy, midPoint.Y + ox), new Point(midPoint.X + oy, midPoint.Y - ox) }; } public struct Point { public Point(double x, double y) : this() { X = x; Y = y; } public double X { get; } public double Y { get; } public static bool operator ==(Point p, Point q) => p.X == q.X && p.Y == q.Y; public static bool operator !=(Point p, Point q) => p.X != q.X || p.Y != q.Y; public static double SquaredDistance(Point p, Point q) { double dx = q.X - p.X, dy = q.Y - p.Y; return dx * dx + dy * dy; } public override string ToString() => $"({X}, {Y})"; } }
Closures/Value capture
C sharp|C#
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. ;Goal: Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: [[Multiple distinct objects]]
using System; using System.Linq; class Program { static void Main() { var captor = (Func<int, Func<int>>)(number => () => number * number); var functions = Enumerable.Range(0, 10).Select(captor); foreach (var function in functions.Take(9)) { Console.WriteLine(function()); } } }
Comma quibbling
C sharp|C#
Comma quibbling is a task originally set by Eric Lippert in his blog. ;Task: Write a function to generate a string output which is the concatenation of input words from a list/sequence where: # An input of no words produces the output string of just the two brace characters "{}". # An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". # An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". # An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: * [] # (No input words). * ["ABC"] * ["ABC", "DEF"] * ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
using System; using System.Linq; namespace CommaQuibbling { internal static class Program { #region Static Members private static string Quibble(string[] input) { return String.Format("{{{0}}}", String.Join("", input.Reverse().Zip( new [] { "", " and " }.Concat(Enumerable.Repeat(", ", int.MaxValue)), (x, y) => x + y).Reverse())); } private static void Main() { Console.WriteLine( Quibble( new string[] {} ) ); Console.WriteLine( Quibble( new[] {"ABC"} ) ); Console.WriteLine( Quibble( new[] {"ABC", "DEF"} ) ); Console.WriteLine( Quibble( new[] {"ABC", "DEF", "G", "H"} ) ); Console.WriteLine( "< Press Any Key >" ); Console.ReadKey(); } #endregion } }
Command-line arguments
C sharp|C#
{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]]. See also [[Program name]]. For parsing command line arguments intelligently, see [[Parsing command-line arguments]]. Example command line: myprogram -c "alpha beta" -h "gamma"
using System; namespace RosettaCode { class Program { static void Main() { string[] args = Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Compare a list of strings
C sharp 7
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. If the input list has less than two elements, the tests should always return true. There is ''no'' need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible. Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers. If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
public static (bool lexicallyEqual, bool strictlyAscending) CompareAListOfStrings(List<string> strings) => strings.Count < 2 ? (true, true) : ( strings.Distinct().Count() < 2, Enumerable.Range(1, strings.Count - 1).All(i => string.Compare(strings[i-1], strings[i]) < 0) );
Compile-time calculation
C sharp|C#
Some programming languages allow calculation of values at compile time. ;Task: Calculate 10! (ten factorial) at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
using System; public static class Program { public const int FACTORIAL_10 = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1; static void Main() { Console.WriteLine(FACTORIAL_10); } }
Compiler/lexical analyzer
C sharp|C#
The C and Python versions can be considered reference implementations. ;Related Tasks * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task
using System; using System.IO; using System.Linq; using System.Collections.Generic; namespace Rosetta { public enum TokenType { End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract, Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal, Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Keyword_if, Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen, RightParen, LeftBrace, RightBrace, Semicolon, Comma, Identifier, Integer, String, None } /// <summary> /// Storage class for tokens /// </summary> public class Token { public TokenType Type { get; set; } public int Line { get; set; } public int Position { get; set; } public string Value { get; set; } public override string ToString() { if (Type == TokenType.Integer || Type == TokenType.Identifier) { return String.Format("{0,-5} {1,-5} {2,-14} {3}", Line, Position, Type.ToString(), Value); } else if (Type == TokenType.String) { return String.Format("{0,-5} {1,-5} {2,-14} \"{3}\"", Line, Position, Type.ToString(), Value.Replace("\n", "\\n")); } return String.Format("{0,-5} {1,-5} {2,-14}", Line, Position, Type.ToString()); } } /// <summary> /// C# Example of Lexical scanner for Rosetta Compiler /// </summary> public class LexicalScanner { // character classes private const string _letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"; private const string _numbers = "0123456789"; private const string _identifier = _letters + _numbers + "_"; private const string _whitespace = " \t\n\r"; // mappings from string keywords to token type private Dictionary<string, TokenType> _keywordTokenTypeMap = new Dictionary<string, TokenType>() { { "if", TokenType.Keyword_if }, { "else", TokenType.Keyword_else }, { "while", TokenType.Keyword_while }, { "print", TokenType.Keyword_print }, { "putc", TokenType.Keyword_putc } }; // mappings from simple operators to token type private Dictionary<string, TokenType> _operatorTokenTypeMap = new Dictionary<string, TokenType>() { { "+", TokenType.Op_add }, { "-", TokenType.Op_subtract }, { "*", TokenType.Op_multiply }, { "/", TokenType.Op_divide }, { "%", TokenType.Op_mod }, { "=", TokenType.Op_assign }, { "<", TokenType.Op_less }, { ">", TokenType.Op_greater }, { "!", TokenType.Op_not }, }; private List<string> _keywords; private string _operators = "+-*/%=<>!%"; private string _code; private List<Token> tokens = new List<Token>(); private int _line = 1; private int _position = 1; public string CurrentCharacter { get { try { return _code.Substring(0, 1); } catch (ArgumentOutOfRangeException) { return ""; } } } /// <summary> /// Lexical scanner initialiser /// </summary> /// <param name="code">Code to be tokenised</param> public LexicalScanner (string code) { _code = code; _keywords = _keywordTokenTypeMap.Keys.ToList(); } /// <summary> /// Advance the cursor forward given number of characters /// </summary> /// <param name="characters">Number of characters to advance</param> private void advance(int characters=1) { try { // reset position when there is a newline if (CurrentCharacter == "\n") { _position = 0; _line++; } _code = _code.Substring(characters, _code.Length - characters); _position += characters; } catch (ArgumentOutOfRangeException) { _code = ""; } } /// <summary> /// Outputs error message to the console and exits /// </summary> /// <param name="message">Error message to display to user</param> /// <param name="line">Line error occurred on</param> /// <param name="position">Line column that the error occurred at</param> public void error(string message, int line, int position) { // output error to the console and exit Console.WriteLine(String.Format("{0} @ {1}:{2}", message, line, position)); Environment.Exit(1); } /// <summary> /// Pattern matching using first & follow matching /// </summary> /// <param name="recogniseClass">String of characters that identifies the token type /// or the exact match the be made if exact:true</param> /// <param name="matchClass">String of characters to match against remaining target characters</param> /// <param name="tokenType">Type of token the match represents.</param> /// <param name="notNextClass">Optional class of characters that cannot follow the match</param> /// <param name="maxLen">Optional maximum length of token value</param> /// <param name="exact">Denotes whether recogniseClass represents an exact match or class match. /// Default: false</param> /// <param name="discard">Denotes whether the token is kept or discarded. Default: false</param> /// <param name="offset">Optiona line position offset to account for discarded tokens</param> /// <returns>Boolean indicating if a match was made </returns> public bool match(string recogniseClass, string matchClass, TokenType tokenType, string notNextClass=null, int maxLen=Int32.MaxValue, bool exact=false, bool discard=false, int offset=0) { // if we've hit the end of the file, there's no more matching to be done if (CurrentCharacter == "") return false; // store _current_ line and position so that our vectors point at the start // of each token int line = _line; int position = _position; // special case exact tokens to avoid needing to worry about backtracking if (exact) { if (_code.StartsWith(recogniseClass)) { if (!discard) tokens.Add(new Token() { Type = tokenType, Value = recogniseClass, Line = line, Position = position - offset}); advance(recogniseClass.Length); return true; } return false; } // first match - denotes the token type usually if (!recogniseClass.Contains(CurrentCharacter)) return false; string tokenValue = CurrentCharacter; advance(); // follow match while we haven't exceeded maxLen and there are still characters // in the code stream while ((matchClass ?? "").Contains(CurrentCharacter) && tokenValue.Length <= maxLen && CurrentCharacter != "") { tokenValue += CurrentCharacter; advance(); } // ensure that any incompatible characters are not next to the token // eg 42fred is invalid, and neither recognized as a number nor an identifier. // _letters would be the notNextClass if (notNextClass != null && notNextClass.Contains(CurrentCharacter)) error("Unrecognised character: " + CurrentCharacter, _line, _position); // only add tokens to the stack that aren't marked as discard - dont want // things like open and close quotes/comments if (!discard) { Token token = new Token() { Type = tokenType, Value = tokenValue, Line = line, Position = position - offset }; tokens.Add(token); } return true; } /// <summary> /// Tokenise the input code /// </summary> /// <returns>List of Tokens</returns> public List<Token> scan() { while (CurrentCharacter != "") { // match whitespace match(_whitespace, _whitespace, TokenType.None, discard: true); // match integers match(_numbers, _numbers, TokenType.Integer, notNextClass:_letters); // match identifiers and keywords if (match(_letters, _identifier, TokenType.Identifier)) { Token match = tokens.Last(); if (_keywords.Contains(match.Value)) match.Type = _keywordTokenTypeMap[match.Value]; } // match string similarly to comments without allowing newlines // this token doesn't get discarded though if (match("\"", null, TokenType.String, discard:true)) { string value = ""; int position = _position; while (!match("\"", null, TokenType.String, discard:true)) { // not allowed newlines in strings if (CurrentCharacter == "\n") error("End-of-line while scanning string literal. Closing string character not found before end-of-line", _line, _position); // end of file reached before finding end of string if (CurrentCharacter == "") error("End-of-file while scanning string literal. Closing string character not found", _line, _position); value += CurrentCharacter; // deal with escape sequences - we only accept newline (\n) if (value.Length >= 2) { string lastCharacters = value.Substring(value.Length - 2, 2); if (lastCharacters[0] == '\\') { if (lastCharacters[1] != 'n') { error("Unknown escape sequence. ", _line, position); } value = value.Substring(0, value.Length - 2).ToString() + "\n"; } } advance(); } tokens.Add(new Token() { Type = TokenType.String, Value = value, Line = _line, Position = position - 1}); } // match string literals if (match("'", null, TokenType.Integer, discard:true)) { int value; int position = _position; value = CurrentCharacter.ToCharArray()[0]; advance(); // deal with empty literals '' if (value == '\'') error("Empty character literal", _line, _position); // deal with escaped characters, only need to worry about \n and \\ // throw werror on any other if (value == '\\') { if (CurrentCharacter == "n") { value = '\n'; } else if (CurrentCharacter == "\\") { value = '\\'; } else { error("Unknown escape sequence. ", _line, _position - 1); } advance(); } // if we haven't hit a closing ' here, there are two many characters // in the literal if (!match("'", null, TokenType.Integer, discard: true)) error("Multi-character constant", _line, _position); tokens.Add(new Rosetta.Token() { Type = TokenType.Integer, Value = value.ToString(), Line = _line, Position = position - 1 }); } // match comments by checking for starting token, then advancing // until closing token is matched if (match("/*", null, TokenType.None, exact: true, discard: true)) { while (!match("*/", null, TokenType.None, exact: true, discard: true)) { // reached the end of the file without closing comment! if (CurrentCharacter == "") error("End-of-file in comment. Closing comment characters not found.", _line, _position); advance(); } continue; } // match complex operators match("<=", null, TokenType.Op_lessequal, exact: true); match(">=", null, TokenType.Op_greaterequal, exact: true); match("==", null, TokenType.Op_equal, exact: true); match("!=", null, TokenType.Op_notequal, exact: true); match("&&", null, TokenType.Op_and, exact: true); match("||", null, TokenType.Op_or, exact: true); // match simple operators if (match(_operators, null, TokenType.None, maxLen:1)) { Token match = tokens.Last(); match.Type = _operatorTokenTypeMap[match.Value]; } // brackets, braces and separators match("(", null, TokenType.LeftParen, exact: true); match(")", null, TokenType.RightParen, exact: true); match("{", null, TokenType.LeftBrace, exact: true); match("}", null, TokenType.RightBrace, exact: true); match(";", null, TokenType.Semicolon, exact: true); match(",", null, TokenType.Comma, exact: true); } // end of file token tokens.Add(new Rosetta.Token() { Type = TokenType.End_of_input, Line = _line, Position = _position }); return tokens; } static void Main (string[] args) { StreamReader inputFile; // if we passed in a filename, read code from that, else // read code from stdin if (args.Length > 0) { string path = args[0]; try { inputFile = new StreamReader(path); } catch (IOException) { inputFile = new StreamReader(Console.OpenStandardInput(8192)); } } else { inputFile = new StreamReader(Console.OpenStandardInput(8192)); } string code = inputFile.ReadToEnd(); // strip windows line endings out code = code.Replace("\r", ""); LexicalScanner scanner = new LexicalScanner(code); List<Token> tokens = scanner.scan(); foreach(Token token in tokens) { Console.WriteLine(token.ToString()); } } } }
Continued fraction
C sharp|C# from Java
A number may be represented as a continued fraction (see Mathworld for more information) as follows: :a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}} The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1. :\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}} For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1. :e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}} For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2. :\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}} ;See also: :* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
using System; using System.Collections.Generic; namespace ContinuedFraction { class Program { static double Calc(Func<int, int[]> f, int n) { double temp = 0.0; for (int ni = n; ni >= 1; ni--) { int[] p = f(ni); temp = p[1] / (p[0] + temp); } return f(0)[0] + temp; } static void Main(string[] args) { List<Func<int, int[]>> fList = new List<Func<int, int[]>>(); fList.Add(n => new int[] { n > 0 ? 2 : 1, 1 }); fList.Add(n => new int[] { n > 0 ? n : 2, n > 1 ? (n - 1) : 1 }); fList.Add(n => new int[] { n > 0 ? 6 : 3, (int) Math.Pow(2 * n - 1, 2) }); foreach (var f in fList) { Console.WriteLine(Calc(f, 200)); } } } }
Continued fraction/Arithmetic/Construct from rational number
C sharp|C#
To understand this task in context please see [[Continued fraction arithmetic]] The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming: :N_1 is the numerator :N_2 is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero. Demonstrate the function by outputing the continued fraction for: : 1/2 : 3 : 23/8 : 13/11 : 22/7 : -151/77 \sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you: : 14142,10000 : 141421,100000 : 1414214,1000000 : 14142136,10000000 Try : : 31,10 : 314,100 : 3142,1000 : 31428,10000 : 314285,100000 : 3142857,1000000 : 31428571,10000000 : 314285714,100000000 Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.
using System; using System.Collections.Generic; class Program { static IEnumerable<int> r2cf(int n1, int n2) { while (Math.Abs(n2) > 0) { int t1 = n1 / n2; int t2 = n2; n2 = n1 - t1 * n2; n1 = t2; yield return t1; } } static void spit(IEnumerable<int> f) { foreach (int n in f) Console.Write(" {0}", n); Console.WriteLine(); } static void Main(string[] args) { spit(r2cf(1, 2)); spit(r2cf(3, 1)); spit(r2cf(23, 8)); spit(r2cf(13, 11)); spit(r2cf(22, 7)); spit(r2cf(-151, 77)); for (int scale = 10; scale <= 10000000; scale *= 10) { spit(r2cf((int)(Math.Sqrt(2) * scale), scale)); } spit(r2cf(31, 10)); spit(r2cf(314, 100)); spit(r2cf(3142, 1000)); spit(r2cf(31428, 10000)); spit(r2cf(314285, 100000)); spit(r2cf(3142857, 1000000)); spit(r2cf(31428571, 10000000)); spit(r2cf(314285714, 100000000)); } }
Convert decimal number to rational
C sharp|C# from C
The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: * 67 / 74 = 0.9(054) = 0.9054054... * 14 / 27 = 0.(518) = 0.518518... Acceptable output: * 0.9054054 - 4527027 / 5000000 * 0.518518 - 259259 / 500000 Finite decimals are of course no problem: * 0.75 - 3 / 4
using System; using System.Text; namespace RosettaDecimalToFraction { public class Fraction { public Int64 Numerator; public Int64 Denominator; public Fraction(double f, Int64 MaximumDenominator = 4096) { /* Translated from the C version. */ /* a: continued fraction coefficients. */ Int64 a; var h = new Int64[3] { 0, 1, 0 }; var k = new Int64[3] { 1, 0, 0 }; Int64 x, d, n = 1; int i, neg = 0; if (MaximumDenominator <= 1) { Denominator = 1; Numerator = (Int64)f; return; } if (f < 0) { neg = 1; f = -f; } while (f != Math.Floor(f)) { n <<= 1; f *= 2; } d = (Int64)f; /* continued fraction and check denominator each step */ for (i = 0; i < 64; i++) { a = (n != 0) ? d / n : 0; if ((i != 0) && (a == 0)) break; x = d; d = n; n = x % n; x = a; if (k[1] * a + k[0] >= MaximumDenominator) { x = (MaximumDenominator - k[0]) / k[1]; if (x * 2 >= a || k[1] >= MaximumDenominator) i = 65; else break; } h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; } Denominator = k[1]; Numerator = neg != 0 ? -h[1] : h[1]; } public override string ToString() { return string.Format("{0} / {1}", Numerator, Denominator); } } class Program { static void Main(string[] args) { Console.OutputEncoding = UTF8Encoding.UTF8; foreach (double d in new double[] { 0.9054054, 0.518518, 0.75, 0.4285714, 0.833333, 0.90909, 3.14159265358979, 2.7182818284590451 }) { var f = new Fraction(d, d >= 2 ? 65536 : 4096); Console.WriteLine("{0,20} → {1}", d, f); } } } }
Convert seconds to compound duration
C sharp|C#
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrate that it passes the following three test-cases: '''''Test Cases''''' :::::{| class="wikitable" |- ! input number ! output string |- | 7259 | 2 hr, 59 sec |- | 86400 | 1 d |- | 6000000 | 9 wk, 6 d, 10 hr, 40 min |} '''''Details''''' The following five units should be used: :::::{| class="wikitable" |- ! unit ! suffix used in output ! conversion |- | week | wk | 1 week = 7 days |- | day | d | 1 day = 24 hours |- | hour | hr | 1 hour = 60 minutes |- | minute | min | 1 minute = 60 seconds |- | second | sec | |} However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
using System; using System.Collections.Generic; using System.Linq; namespace ConvertSecondsToCompoundDuration { class Program { static void Main( string[] args ) { foreach ( string arg in args ) { int duration ; bool isValid = int.TryParse( arg , out duration ) ; if ( !isValid ) { Console.Error.WriteLine( "ERROR: Not an integer: {0}" , arg ) ; } if ( duration < 0 ) { Console.Error.WriteLine( "ERROR: duration must be non-negative" , arg ) ; } Console.WriteLine(); Console.WriteLine( "{0:#,##0} seconds ==> {1}" , duration , FormatAsDuration(duration) ) ; } } private static string FormatAsDuration( int duration ) { if ( duration < 0 ) throw new ArgumentOutOfRangeException("duration") ; return string.Join( ", " , GetDurationParts(duration) ) ; } private static IEnumerable<string> GetDurationParts( int duration ) { var parts = new[] { new { Name="wk" , Length = 7*24*60*60*1 , } , new { Name="d" , Length = 24*60*60*1 , } , new { Name="h" , Length = 60*60*1 , } , new { Name="m" , Length = 60*1 , } , new { Name="s" , Length = 1 , } , } ; foreach ( var part in parts ) { int n = Math.DivRem( duration , part.Length , out duration ) ; if ( n > 0 ) yield return string.Format( "{0} {1}" , n , part.Name ) ; } } } }
Convert seconds to compound duration
C sharp 6
Write a function or program which: * takes a positive integer representing a duration in seconds as input (e.g., 100), and * returns a string which shows the same duration decomposed into: :::* weeks, :::* days, :::* hours, :::* minutes, and :::* seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrate that it passes the following three test-cases: '''''Test Cases''''' :::::{| class="wikitable" |- ! input number ! output string |- | 7259 | 2 hr, 59 sec |- | 86400 | 1 d |- | 6000000 | 9 wk, 6 d, 10 hr, 40 min |} '''''Details''''' The following five units should be used: :::::{| class="wikitable" |- ! unit ! suffix used in output ! conversion |- | week | wk | 1 week = 7 days |- | day | d | 1 day = 24 hours |- | hour | hr | 1 hour = 60 minutes |- | minute | min | 1 minute = 60 seconds |- | second | sec | |} However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec"). Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec) Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
private static string ConvertToCompoundDuration(int seconds) { if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (seconds == 0) return "0 sec"; TimeSpan span = TimeSpan.FromSeconds(seconds); int[] parts = {span.Days / 7, span.Days % 7, span.Hours, span.Minutes, span.Seconds}; string[] units = {" wk", " d", " hr", " min", " sec"}; return string.Join(", ", from index in Enumerable.Range(0, units.Length) where parts[index] > 0 select parts[index] + units[index]); }
Copy stdin to stdout
.NET Framework 4.0 or later
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
using System; class Program { static void Main(string[] args) { Console.OpenStandardInput().CopyTo(Console.OpenStandardOutput()); } }
Count the coins
C sharp|C#
There are four types of common coins in US currency: :::# quarters (25 cents) :::# dimes (10 cents) :::# nickels (5 cents), and :::# pennies (1 cent) There are six ways to make change for 15 cents: :::# A dime and a nickel :::# A dime and 5 pennies :::# 3 nickels :::# 2 nickels and 5 pennies :::# A nickel and 10 pennies :::# 15 pennies ;Task: How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents). ;Optional: Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? (Note: the answer is larger than 232). ;References: * an algorithm from the book ''Structure and Interpretation of Computer Programs''. * an article in the algorithmist. * Change-making problem on Wikipedia.
// Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/ class Program { static long Count(int[] C, int m, int n) { var table = new long[n + 1]; table[0] = 1; for (int i = 0; i < m; i++) for (int j = C[i]; j <= n; j++) table[j] += table[j - C[i]]; return table[n]; } static void Main(string[] args) { var C = new int[] { 1, 5, 10, 25 }; int m = C.Length; int n = 100; Console.WriteLine(Count(C, m, n)); //242 Console.ReadLine(); } }
Create an HTML table
C sharp|C#
Create an HTML table. * The table body should have at least three rows of three columns. * Each of these three columns should be labelled "X", "Y", and "Z". * An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. * The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. * The numbers should be aligned in the same fashion for all columns.
using System; using System.Text; using System.Xml; namespace N { public class T { public static void Main() { var headers = new [] { "", "X", "Y", "Z" }; var cols = headers.Select(name => new XElement( "th", name, new XAttribute("text-align", "center") ) ); var rows = Enumerable.Range(0, 4).Select(ri => new XElement( "tr", new XElement("td", ri), Enumerable.Range(0, 4).Select(ci => new XElement( "td", ci, new XAttribute("text-align", "center") ) ) ) ); var xml = new XElement( "table", new XElement( "thead", new XElement("tr", cols), new XElement("tbody", rows) ) ); Console.WriteLine(xml.ToString()); } } }
Currency
C sharp|C#
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. ;Note: The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact. For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. Use the values: ::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers) ::* 2 milkshakes at $2.86 each, and ::* a tax rate of 7.65%. (That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) Compute and output (show results on this page): ::* the total price before tax ::* the tax ::* the total with tax The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. The output must show dollars and cents with a decimal point. The three results displayed should be: ::* 22000000000000005.72 ::* 1683000000000000.44 ::* 23683000000000006.16 Dollar signs and thousands separators are optional.
using System; using System.Collections.Generic; namespace Currency { class Program { static void Main(string[] args) { MenuItem hamburger = new MenuItem() { Name = "Hamburger", Price = 5.5M }; MenuItem milkshake = new MenuItem() { Name = "Milkshake", Price = 2.86M }; IList<CartItem> cart = new List<CartItem>(); cart.Add(new CartItem() { item = hamburger, quantity = 4000000000000000 }); cart.Add(new CartItem() { item = milkshake, quantity = 2 }); decimal total = CalculateTotal(cart); Console.WriteLine(string.Format("Total before tax: {0:C}", total)); // Add Tax decimal tax = total * 0.0765M; Console.WriteLine(string.Format("Tax: {0:C}", tax)); total += tax; Console.WriteLine(string.Format("Total with tax: {0:C}", total)); } private static decimal CalculateTotal(IList<CartItem> cart) { decimal total = 0M; foreach (CartItem item in cart) { total += item.quantity * item.item.Price; } return total; } private struct MenuItem { public string Name { get; set; } public decimal Price { get; set; } } private struct CartItem { public MenuItem item { get; set; } public decimal quantity { get; set; } } } }
Currying
C sharp|C#
{{Wikipedia|Currying}} ;Task: Create a simple demonstrative example of Currying in a specific language. Add any historic details as to how the feature made its way into the language.
public delegate int Plus(int y); public delegate Plus CurriedPlus(int x); public static CurriedPlus plus = delegate(int x) {return delegate(int y) {return x + y;};}; static void Main() { int sum = plus(3)(4); // sum = 7 int sum2= plus(2)(plus(3)(4)) // sum2 = 9 }
Cyclotomic polynomial
C sharp 8
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n. ;Task: * Find and print the first 30 cyclotomic polynomials. * Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient. ;See also * Wikipedia article, Cyclotomic polynomial, showing ways to calculate them. * The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using IntMap = System.Collections.Generic.Dictionary<int, int>; public static class CyclotomicPolynomial { public static void Main2() { Console.WriteLine("Task 1: Cyclotomic polynomials for n <= 30:"); for (int i = 1; i <= 30; i++) { var p = GetCyclotomicPolynomial(i); Console.WriteLine($"CP[{i}] = {p.ToString()}"); } Console.WriteLine(); Console.WriteLine("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:"); for (int i = 1, n = 0; i <= 10; i++) { while (true) { n++; var p = GetCyclotomicPolynomial(n); if (p.Any(t => Math.Abs(t.Coefficient) == i)) { Console.WriteLine($"CP[{n}] has coefficient with magnitude = {i}"); n--; break; } } } } private const int MaxFactors = 100_000; private const int Algorithm = 2; private static readonly Term x = new Term(1, 1); private static readonly Dictionary<int, Polynomial> polyCache = new Dictionary<int, Polynomial> { [1] = x - 1 }; private static readonly Dictionary<int, IntMap> factorCache = new Dictionary<int, IntMap> { [2] = new IntMap { [2] = 1 } }; private static Polynomial GetCyclotomicPolynomial(in int n) { if (polyCache.TryGetValue(n, out var result)) return result; var factors = GetFactors(n); if (factors.ContainsKey(n)) { //n is prime result = new Polynomial(from exp in ..n select x[exp]); } else if (factors.Count == 2 && factors.Contains(2, 1) && factors.Contains(n/2, 1)) { //n = 2p result = new Polynomial(from i in ..(n/2) select (IsOdd(i) ? -x : x)[i]); } else if (factors.Count == 1 && factors.TryGetValue(2, out int h)) { //n = 2^h result = x[1<<(h-1)] + 1; } else if (factors.Count == 1 && !factors.ContainsKey(n)) { // n = p^k (int p, int k) = factors.First(); result = new Polynomial(from i in ..p select x[i * (int)Math.Pow(p, k-1)]); } else if (factors.Count == 2 && factors.ContainsKey(2)) { //n = 2^h * p^k (int p, int k) = factors.First(entry => entry.Key != 2); int twoExp = 1 << (factors[2] - 1); result = new Polynomial(from i in ..p select (IsOdd(i) ? -x : x)[i * twoExp * (int)Math.Pow(p, k-1)]); } else if (factors.ContainsKey(2) && IsOdd(n/2) && n/2 > 1) { // CP(2m)[x] = CP[-m][x], n is odd > 1 Polynomial cycloDiv2 = GetCyclotomicPolynomial(n/2); result = new Polynomial(from term in cycloDiv2 select IsOdd(term.Exponent) ? -term : term); #pragma warning disable CS0162 } else if (Algorithm == 0) { var divisors = GetDivisors(n); result = x[n] - 1; foreach (int d in divisors) result /= GetCyclotomicPolynomial(d); } else if (Algorithm == 1) { var divisors = GetDivisors(n).ToList(); int maxDivisor = divisors.Max(); result = (x[n] - 1) / (x[maxDivisor] - 1); foreach (int d in divisors.Where(div => maxDivisor % div == 0)) { result /= GetCyclotomicPolynomial(d); } } else if (Algorithm == 2) { int m = 1; result = GetCyclotomicPolynomial(m); var primes = factors.Keys.ToList(); primes.Sort(); foreach (int prime in primes) { var cycloM = result; result = new Polynomial(from term in cycloM select term.Coefficient * x[term.Exponent * prime]); result /= cycloM; m *= prime; } int s = n / m; result = new Polynomial(from term in result select term.Coefficient * x[term.Exponent * s]); #pragma warning restore CS0162 } else { throw new InvalidOperationException("Invalid algorithm"); } polyCache[n] = result; return result; } private static bool IsOdd(int i) => (i & 1) != 0; private static bool Contains(this IntMap map, int key, int value) => map.TryGetValue(key, out int v) && v == value; private static int GetOrZero(this IntMap map, int key) => map.TryGetValue(key, out int v) ? v : 0; private static IEnumerable<T> Select<T>(this Range r, Func<int, T> f) => Enumerable.Range(r.Start.Value, r.End.Value - r.Start.Value).Select(f); private static IntMap GetFactors(in int n) { if (factorCache.TryGetValue(n, out var factors)) return factors; factors = new IntMap(); if (!IsOdd(n)) { foreach (var entry in GetFactors(n/2)) factors.Add(entry.Key, entry.Value); factors[2] = factors.GetOrZero(2) + 1; return Cache(n, factors); } for (int i = 3; i * i <= n; i+=2) { if (n % i == 0) { foreach (var entry in GetFactors(n/i)) factors.Add(entry.Key, entry.Value); factors[i] = factors.GetOrZero(i) + 1; return Cache(n, factors); } } factors[n] = 1; return Cache(n, factors); } private static IntMap Cache(int n, IntMap factors) { if (n < MaxFactors) factorCache[n] = factors; return factors; } private static IEnumerable<int> GetDivisors(int n) { for (int i = 1; i * i <= n; i++) { if (n % i == 0) { yield return i; int div = n / i; if (div != i && div != n) yield return div; } } } public sealed class Polynomial : IEnumerable<Term> { public Polynomial() { } public Polynomial(params Term[] terms) : this(terms.AsEnumerable()) { } public Polynomial(IEnumerable<Term> terms) { Terms.AddRange(terms); Simplify(); } private List<Term>? terms; private List<Term> Terms => terms ??= new List<Term>(); public int Count => terms?.Count ?? 0; public int Degree => Count == 0 ? -1 : Terms[0].Exponent; public int LeadingCoefficient => Count == 0 ? 0 : Terms[0].Coefficient; public IEnumerator<Term> GetEnumerator() => Terms.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public override string ToString() => Count == 0 ? "0" : string.Join(" + ", Terms).Replace("+ -", "- "); public static Polynomial operator *(Polynomial p, Term t) => new Polynomial(from s in p select s * t); public static Polynomial operator +(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms)); public static Polynomial operator -(Polynomial p, Polynomial q) => new Polynomial(p.Terms.Concat(q.Terms.Select(t => -t))); public static Polynomial operator *(Polynomial p, Polynomial q) => new Polynomial(from s in p from t in q select s * t); public static Polynomial operator /(Polynomial p, Polynomial q) => p.Divide(q).quotient; public (Polynomial quotient, Polynomial remainder) Divide(Polynomial divisor) { if (Degree < 0) return (new Polynomial(), this); Polynomial quotient = new Polynomial(); Polynomial remainder = this; int lcv = divisor.LeadingCoefficient; int dv = divisor.Degree; while (remainder.Degree >= divisor.Degree) { int lcr = remainder.LeadingCoefficient; Term div = new Term(lcr / lcv, remainder.Degree - dv); quotient.Terms.Add(div); remainder += divisor * -div; } quotient.Simplify(); remainder.Simplify(); return (quotient, remainder); } private void Simplify() { if (Count < 2) return; Terms.Sort((a, b) => -a.CompareTo(b)); for (int i = Terms.Count - 1; i > 0; i--) { Term s = Terms[i-1]; Term t = Terms[i]; if (t.Exponent == s.Exponent) { Terms[i-1] = new Term(s.Coefficient + t.Coefficient, s.Exponent); Terms.RemoveAt(i); } } Terms.RemoveAll(t => t.IsZero); } } public readonly struct Term : IEquatable<Term>, IComparable<Term> { public Term(int coefficient, int exponent = 0) => (Coefficient, Exponent) = (coefficient, exponent); public Term this[int exponent] => new Term(Coefficient, exponent); //Using x[exp] because x^exp has low precedence public int Coefficient { get; } public int Exponent { get; } public bool IsZero => Coefficient == 0; public static Polynomial operator +(Term left, Term right) => new Polynomial(left, right); public static Polynomial operator -(Term left, Term right) => new Polynomial(left, -right); public static implicit operator Term(int coefficient) => new Term(coefficient); public static Term operator -(Term t) => new Term(-t.Coefficient, t.Exponent); public static Term operator *(Term left, Term right) => new Term(left.Coefficient * right.Coefficient, left.Exponent + right.Exponent); public static bool operator ==(Term left, Term right) => left.Equals(right); public static bool operator !=(Term left, Term right) => !left.Equals(right); public static bool operator <(Term left, Term right) => left.CompareTo(right) < 0; public static bool operator >(Term left, Term right) => left.CompareTo(right) > 0; public static bool operator <=(Term left, Term right) => left.CompareTo(right) <= 0; public static bool operator >=(Term left, Term right) => left.CompareTo(right) >= 0; public bool Equals(Term other) => Exponent == other.Exponent && Coefficient == other.Coefficient; public override bool Equals(object? obj) => obj is Term t && Equals(t); public override int GetHashCode() => Coefficient.GetHashCode() * 31 + Exponent.GetHashCode(); public int CompareTo(Term other) { int c = Exponent.CompareTo(other.Exponent); if (c != 0) return c; return Coefficient.CompareTo(other.Coefficient); } public override string ToString() => (Coefficient, Exponent) switch { (0, _) => "0", (_, 0) => $"{Coefficient}", (1, 1) => "x", (-1, 1) => "-x", (_, 1) => $"{Coefficient}x", (1, _) => $"x^{Exponent}", (-1, _) => $"-x^{Exponent}", _ => $"{Coefficient}x^{Exponent}" }; } }
Damm algorithm
C sharp|C# from Java
The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. ;Task: Verify the checksum, stored as last digit of an input.
using System; namespace DammAlgorithm { class Program { static int[,] table = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; static bool Damm(string s) { int interim = 0; foreach (char c in s) { interim = table[interim, c - '0']; } return interim == 0; } static void Main(string[] args) { int[] numbers = { 5724, 5727, 112946, 112949 }; foreach (int number in numbers) { bool isValid = Damm(number.ToString()); if (isValid) { Console.WriteLine("{0,6} is valid", number); } else { Console.WriteLine("{0,6} is invalid", number); } } } } }
De Bruijn sequences
C sharp|C# from Kotlin
{{DISPLAYTITLE:de Bruijn sequences}} The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn. A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be capitalized. In combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on a size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every possible length-''n'' string (computer science, formal theory) on ''A'' occurs exactly once as a contiguous substring. Such a sequence is denoted by ''B''(''k'', ''n'') and has length ''k''''n'', which is also the number of distinct substrings of length ''n'' on ''A''; de Bruijn sequences are therefore optimally short. There are: (k!)k(n-1) / kn distinct de Bruijn sequences ''B''(''k'', ''n''). ;Task: For this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on a PIN-like code lock that does not have an "enter" key and accepts the last ''n'' digits entered. Note: automated teller machines (ATMs) used to work like this, but their software has been updated to not allow a brute-force attack. ;Example: A digital door lock with a 4-digit code would have ''B'' (10, 4) solutions, with a length of '''10,000''' (digits). Therefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to open the lock. Trying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses. ;Task requirements: :* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code. :::* Show the length of the generated de Bruijn sequence. :::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page). :::* Show the first and last '''130''' digits of the de Bruijn sequence. :* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence. :::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros). :* Reverse the de Bruijn sequence. :* Again, perform the (above) verification test. :* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence. :::* Perform the verification test (again). There should be four PIN codes missing. (The last requirement is to ensure that the verification tests performs correctly. The verification processes should list any and all missing PIN codes.) Show all output here, on this page. ;References: :* Wikipedia entry: de Bruijn sequence. :* MathWorld entry: de Bruijn sequence. :* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
using System; using System.Collections.Generic; using System.Text; namespace DeBruijn { class Program { const string digits = "0123456789"; static string DeBruijn(int k, int n) { var alphabet = digits.Substring(0, k); var a = new byte[k * n]; var seq = new List<byte>(); void db(int t, int p) { if (t > n) { if (n % p == 0) { seq.AddRange(new ArraySegment<byte>(a, 1, p)); } } else { a[t] = a[t - p]; db(t + 1, p); var j = a[t - p] + 1; while (j < k) { a[t] = (byte)j; db(t + 1, t); j++; } } } db(1, 1); var buf = new StringBuilder(); foreach (var i in seq) { buf.Append(alphabet[i]); } var b = buf.ToString(); return b + b.Substring(0, n - 1); } static bool AllDigits(string s) { foreach (var c in s) { if (c < '0' || '9' < c) { return false; } } return true; } static void Validate(string db) { var le = db.Length; var found = new int[10_000]; var errs = new List<string>(); // Check all strings of 4 consecutive digits within 'db' // to see if all 10,000 combinations occur without duplication. for (int i = 0; i < le - 3; i++) { var s = db.Substring(i, 4); if (AllDigits(s)) { int.TryParse(s, out int n); found[n]++; } } for (int i = 0; i < 10_000; i++) { if (found[i] == 0) { errs.Add(string.Format(" PIN number {0,4} missing", i)); } else if (found[i] > 1) { errs.Add(string.Format(" PIN number {0,4} occurs {1} times", i, found[i])); } } var lerr = errs.Count; if (lerr == 0) { Console.WriteLine(" No errors found"); } else { var pl = lerr == 1 ? "" : "s"; Console.WriteLine(" {0} error{1} found:", lerr, pl); errs.ForEach(Console.WriteLine); } } static string Reverse(string s) { char[] arr = s.ToCharArray(); Array.Reverse(arr); return new string(arr); } static void Main() { var db = DeBruijn(10, 4); var le = db.Length; Console.WriteLine("The length of the de Bruijn sequence is {0}", le); Console.WriteLine("\nThe first 130 digits of the de Bruijn sequence are: {0}", db.Substring(0, 130)); Console.WriteLine("\nThe last 130 digits of the de Bruijn sequence are: {0}", db.Substring(le - 130, 130)); Console.WriteLine("\nValidating the deBruijn sequence:"); Validate(db); Console.WriteLine("\nValidating the reversed deBruijn sequence:"); Validate(Reverse(db)); var bytes = db.ToCharArray(); bytes[4443] = '.'; db = new string(bytes); Console.WriteLine("\nValidating the overlaid deBruijn sequence:"); Validate(db); } } }
Deepcopy
C sharp|C#
Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure. The task should show: * Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles. * Any limitations of the method. * That the structure and its copy are different. * Suitable links to external documentation for common libraries.
using System; namespace prog { class MainClass { class MyClass : ICloneable { public MyClass() { f = new int[3]{2,3,5}; c = '1'; } public object Clone() { MyClass cpy = (MyClass) this.MemberwiseClone(); cpy.f = (int[]) this.f.Clone(); return cpy; } public char c; public int[] f; } public static void Main( string[] args ) { MyClass c1 = new MyClass(); MyClass c2 = (MyClass) c1.Clone(); } } }
Department numbers
C sharp|C#
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
using System; public class Program { public static void Main() { for (int p = 2; p <= 7; p+=2) { for (int s = 1; s <= 7; s++) { int f = 12 - p - s; if (s >= f) break; if (f > 7) continue; if (s == p || f == p) continue; //not even necessary Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}"); Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}"); } } } }
Descending primes
C#|CSharp
Generate and show all primes with strictly descending decimal digits. ;See also ;* OEIS:A052014 - Primes with distinct digits in descending order ;Related: *[[Ascending primes]]
using System; class Program { static bool ispr(uint n) { if ((n & 1) == 0 || n < 2) return n == 2; for (uint j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } static void Main(string[] args) { uint c = 0; int nc; var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var nxt = new uint[128]; while (true) { nc = 0; foreach (var a in ps) { if (ispr(a)) Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " "); for (uint b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) { Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); } else break; } Console.WriteLine("\n{0} descending primes found", c); } }
Determine if a string has all the same characters
C sharp|C# from D
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
using System; namespace AllSame { class Program { static void Analyze(string s) { Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length); if (s.Length > 1) { var b = s[0]; for (int i = 1; i < s.Length; i++) { var c = s[i]; if (c != b) { Console.WriteLine(" Not all characters in the string are the same."); Console.WriteLine(" '{0}' (0x{1:X02}) is different at position {2}", c, (int)c, i); return; } } } Console.WriteLine(" All characters in the string are the same."); } static void Main() { var strs = new string[] { "", " ", "2", "333", ".55", "tttTTT", "4444 444k" }; foreach (var str in strs) { Analyze(str); } } } }
Determine if a string has all unique characters
C sharp|C#
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as unique ::* process the strings from left-to-right ::* if unique, display a message saying such ::* if not unique, then: ::::* display a message saying such ::::* display what character is duplicated ::::* only the 1st non-unique character need be displayed ::::* display where "both" duplicated characters are in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the duplicated character Use (at least) these five test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 1 which is a single period ('''.''') :::* a string of length 6 which contains: '''abcABC''' :::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX''' :::* a string of length 36 which ''doesn't'' contain the letter "oh": :::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ''' Show all output here on this page.
using System; using System.Linq; public class Program { static void Main { string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"}; foreach (string s in input) { Console.WriteLine($"\"{s}\" (Length {s.Length}) " + string.Join(", ", s.Select((c, i) => (c, i)) .GroupBy(t => t.c).Where(g => g.Count() > 1) .Select(g => $"'{g.Key}' (0X{(int)g.Key:X})[{string.Join(", ", g.Select(t => t.i))}]") .DefaultIfEmpty("All characters are unique.") ) ); } } }
Determine if a string is collapsible
C sharp|C#
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ''immediately repeated'' character is any character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.} ;Examples: In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated by underscores (above), even though they (those characters) appear elsewhere in the character string. So, after ''collapsing'' the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate ''repeated'' characters and ''collapse'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: string number ++ 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | 5 | --- Harry S Truman | <###### has many repeated blanks +------------------------------------------------------------------------+
using System; using static System.Linq.Enumerable; public class Program { static void Main() { string[] input = { "", "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "headmistressship", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " --- Harry S Truman " }; foreach (string s in input) { Console.WriteLine($"old: {s.Length} «««{s}»»»"); string c = Collapse(s); Console.WriteLine($"new: {c.Length} «««{c}»»»"); } } static string Collapse(string s) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Determine if a string is squeezable
C sharp|C#
Determine if a character string is ''squeezable''. And if so, squeeze the string (by removing any number of a ''specified'' ''immediately repeated'' character). This task is very similar to the task '''Determine if a character string is collapsible''' except that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''. If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). A specified ''immediately repeated'' character is any specified character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''squeeze'''.} ;Examples: In the following character string with a specified ''immediately repeated'' character of '''e''': The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''e''' is an specified repeated character, indicated by an underscore (above), even though they (the characters) appear elsewhere in the character string. So, after ''squeezing'' the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string, using a specified immediately repeated character '''s''': headmistressship The "squeezed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character and ''squeeze'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the specified repeated character (to be searched for and possibly ''squeezed''): :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: immediately string repeated number character ( | a blank, a minus, a seven, a period) ++ 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-' 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7' 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.' 5 | --- Harry S Truman | (below) <###### has many repeated blanks +------------------------------------------------------------------------+ | | | For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: * a blank * a minus * a lowercase '''r''' Note: there should be seven results shown, one each for the 1st four strings, and three results for the 5th string.
using System; using static System.Linq.Enumerable; public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'); SqueezeAndPrint("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'); string s = " --- Harry S Truman "; SqueezeAndPrint(s, ' '); SqueezeAndPrint(s, '-'); SqueezeAndPrint(s, 'r'); } static void SqueezeAndPrint(string s, char c) { Console.WriteLine($"squeeze: '{c}'"); Console.WriteLine($"old: {s.Length} «««{s}»»»"); s = Squeeze(s, c); Console.WriteLine($"new: {s.Length} «««{s}»»»"); } static string Squeeze(string s, char c) => string.IsNullOrEmpty(s) ? "" : s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != c || s[i] != s[i - 1]).Select(i => s[i]).ToArray()); }
Determine if two triangles overlap
C sharp|C#
Determining if two triangles in the same plane overlap is an important topic in collision detection. ;Task: Determine which of these pairs of triangles overlap in 2D: :::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6) :::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0) :::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6) :::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4) :::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2) :::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4) Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer): :::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
using System; using System.Collections.Generic; namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; } public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) { P1 = p1; P2 = p2; P3 = p3; } public double Det2D() { return P1.Item1 * (P2.Item2 - P3.Item2) + P2.Item1 * (P3.Item2 - P1.Item2) + P3.Item1 * (P3.Item1 - P2.Item2); } public void CheckTriWinding(bool allowReversed) { var detTri = Det2D(); if (detTri < 0.0) { if (allowReversed) { var a = P3; P3 = P2; P2 = a; } else { throw new Exception("Triangle has wrong winding direction"); } } } public bool BoundaryCollideChk(double eps) { return Det2D() < eps; } public bool BoundaryDoesntCollideChk(double eps) { return Det2D() <= eps; } public override string ToString() { return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3); } } class Program { static bool BoundaryCollideChk(Triangle t, double eps) { return t.BoundaryCollideChk(eps); } static bool BoundaryDoesntCollideChk(Triangle t, double eps) { return t.BoundaryDoesntCollideChk(eps); } static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { // Triangles must be expressed anti-clockwise t1.CheckTriWinding(allowReversed); t2.CheckTriWinding(allowReversed); // 'onBoundary' determines whether points on boundary are considered as colliding or not var chkEdge = onBoundary ? (Func<Triangle, double, bool>)BoundaryCollideChk : BoundaryDoesntCollideChk; List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 }; List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 }; // for each edge E of t1 for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; // Check all points of t2 lay on the external side of edge E. // If they do, the triangles do not overlap. if (chkEdge(new Triangle(lp1[i], lp1[j], lp2[0]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) && chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) { return false; } } // for each edge E of t2 for (int i = 0; i < 3; i++) { var j = (i + 1) % 3; // Check all points of t1 lay on the external side of edge E. // If they do, the triangles do not overlap. if (chkEdge(new Triangle(lp2[i], lp2[j], lp1[0]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) && chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) { return false; } } // The triangles overlap return true; } static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) { if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) { Console.WriteLine("overlap"); } else { Console.WriteLine("do not overlap"); } } static void Main(string[] args) { var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); // need to allow reversed for this pair to avoid exception t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0)); t2 = t1; Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2, 0.0, true); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0)); t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1.P3 = new Tuple<double, double>(2.5, 5.0); t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0)); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0)); Console.WriteLine("{0} and\n{1}", t1, t2); Overlap(t1, t2); Console.WriteLine(); t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0)); t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1)); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points collide"); Overlap(t1, t2); Console.WriteLine(); Console.WriteLine("{0} and\n{1}", t1, t2); Console.WriteLine("which have only a single corner in contact, if boundary points do not collide"); Overlap(t1, t2, 0.0, false, false); } } }
Digital root
C sharp|C#
The digital root, X, of a number, n, is calculated: : find X as the sum of the digits of n : find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: :627615 has additive persistence 2 and digital root of 9; :39390 has additive persistence 2 and digital root of 6; :588225 has additive persistence 2 and digital root of 3; :393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. ;See: * [[Casting out nines]] for this wiki's use of this procedure. * [[Digital root/Multiplicative digital root]] * [[Sum digits of an integer]] * Digital root sequence on OEIS * Additive persistence sequence on OEIS * [[Iterated digits squaring]]
using System; using System.Linq; class Program { static Tuple<int, int> DigitalRoot(long num) { int additivepersistence = 0; while (num > 9) { num = num.ToString().ToCharArray().Sum(x => x - '0'); additivepersistence++; } return new Tuple<int, int>(additivepersistence, (int)num); } static void Main(string[] args) { foreach (long num in new long[] { 627615, 39390, 588225, 393900588225 }) { var t = DigitalRoot(num); Console.WriteLine("{0} has additive persistence {1} and digital root {2}", num, t.Item1, t.Item2); } } }
Display a linear combination
C sharp|C# from D
Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots). Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is: :\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots where \alpha^{i_k}\neq 0 The output must comply to the following rules: * don't show null terms, unless the whole combination is null. ::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong. * don't show scalars when they are equal to one or minus one. ::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong. * don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. ::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
using System; using System.Collections.Generic; using System.Text; namespace DisplayLinearCombination { class Program { static string LinearCombo(List<int> c) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < c.Count; i++) { int n = c[i]; if (n < 0) { if (sb.Length == 0) { sb.Append('-'); } else { sb.Append(" - "); } } else if (n > 0) { if (sb.Length != 0) { sb.Append(" + "); } } else { continue; } int av = Math.Abs(n); if (av != 1) { sb.AppendFormat("{0}*", av); } sb.AppendFormat("e({0})", i + 1); } if (sb.Length == 0) { sb.Append('0'); } return sb.ToString(); } static void Main(string[] args) { List<List<int>> combos = new List<List<int>>{ new List<int> { 1, 2, 3}, new List<int> { 0, 1, 2, 3}, new List<int> { 1, 0, 3, 4}, new List<int> { 1, 2, 0}, new List<int> { 0, 0, 0}, new List<int> { 0}, new List<int> { 1, 1, 1}, new List<int> { -1, -1, -1}, new List<int> { -1, -2, 0, -3}, new List<int> { -1}, }; foreach (List<int> c in combos) { var arr = "[" + string.Join(", ", c) + "]"; Console.WriteLine("{0,15} -> {1}", arr, LinearCombo(c)); } } } }
Diversity prediction theorem
C sharp|C#
The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies. Scott E. Page introduced the diversity prediction theorem: : ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. Therefore, when the diversity in a group is large, the error of the crowd is small. ;Definitions: ::* Average Individual Error: Average of the individual squared errors ::* Collective Error: Squared error of the collective prediction ::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction ::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then :::::: Collective Error = Average Individual Error - Prediction Diversity ;Task: For a given true value and a number of number of estimates (from a crowd), show (here on this page): :::* the true value and the crowd estimates :::* the average error :::* the crowd error :::* the prediction diversity Use (at least) these two examples: :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51''' :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42''' ;Also see: :* Wikipedia entry: Wisdom of the crowd :* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
using System; using System.Linq; using System.Collections.Generic; public class MainClass { static double Square(double x) => x * x; static double AverageSquareDiff(double a, IEnumerable<double> predictions) => predictions.Select(x => Square(x - a)).Average(); static void DiversityTheorem(double truth, IEnumerable<double> predictions) { var average = predictions.Average(); Console.WriteLine($@"average-error: {AverageSquareDiff(truth, predictions)} crowd-error: {Square(truth - average)} diversity: {AverageSquareDiff(average, predictions)}"); } public static void Main() { DiversityTheorem(49, new []{48d,47,51}); DiversityTheorem(49, new []{48d,47,51,42}); } }
Dot product
C sharp|C#
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
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; }
Dot product
C sharp
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
public static decimal DotProduct(decimal[] a, decimal[] b) { return a.Zip(b, (x, y) => x * y).Sum(); }
Draw a clock
C sharp|C#
Draw a clock. More specific: # Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. # The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. # A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. # A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. ;Key points * animate simple object * timed event * polling system resources * code clarity
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()); } }
Draw a rotating cube
C sharp|C# from Java
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. ;Related tasks * Draw a cuboid * write language name in 3D ASCII
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Threading; namespace RotatingCube { 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}}; public Form1() { Width = Height = 640; StartPosition = FormStartPosition.CenterScreen; SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true); Scale(100, 100, 100); RotateCuboid(Math.PI / 4, Math.Atan(Math.Sqrt(2))); var timer = new DispatcherTimer(); timer.Tick += (s, e) => { RotateCuboid(Math.PI / 180, 0); Refresh(); }; timer.Interval = new TimeSpan(0, 0, 0, 0, 17); timer.Start(); } 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); } } } }
Draw a sphere
C sharp|C# from C
{{requires|Graphics}} ;Task: Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. ;Related tasks: * draw a cuboid * draw a rotating cube * write language name in 3D ASCII * draw a Deathstar
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(); } } }
Eban numbers
C sharp|C# from D
Definition: An '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English. Or more literally, spelled numbers that contain the letter '''e''' are banned. The American version of spelling numbers will be used here (as opposed to the British). '''2,000,000,000''' is two billion, ''not'' two milliard. Only numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task. This will allow optimizations to be used. ;Task: :::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count :::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count :::* show a count of all eban numbers up and including '''10,000''' :::* show a count of all eban numbers up and including '''100,000''' :::* show a count of all eban numbers up and including '''1,000,000''' :::* show a count of all eban numbers up and including '''10,000,000''' :::* show all output here. ;See also: :* The MathWorld entry: eban numbers. :* The OEIS entry: A6933, eban numbers. :* [[Number names]].
using System; namespace EbanNumbers { struct Interval { public int start, end; public bool print; public Interval(int start, int end, bool print) { this.start = start; this.end = end; this.print = print; } } class Program { static void Main() { Interval[] intervals = { new Interval(2, 1_000, true), new Interval(1_000, 4_000, true), new Interval(2, 10_000, false), new Interval(2, 100_000, false), new Interval(2, 1_000_000, false), new Interval(2, 10_000_000, false), new Interval(2, 100_000_000, false), new Interval(2, 1_000_000_000, false), }; foreach (var intv in intervals) { if (intv.start == 2) { Console.WriteLine("eban numbers up to and including {0}:", intv.end); } else { Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.end); } int count = 0; for (int i = intv.start; i <= intv.end; i += 2) { int b = i / 1_000_000_000; int r = i % 1_000_000_000; int m = r / 1_000_000; r = i % 1_000_000; int t = r / 1_000; r %= 1_000; if (m >= 30 && m <= 66) m %= 10; if (t >= 30 && t <= 66) t %= 10; if (r >= 30 && r <= 66) r %= 10; if (b == 0 || b == 2 || b == 4 || b == 6) { if (m == 0 || m == 2 || m == 4 || m == 6) { if (t == 0 || t == 2 || t == 4 || t == 6) { if (r == 0 || r == 2 || r == 4 || r == 6) { if (intv.print) Console.Write("{0} ", i); count++; } } } } } if (intv.print) { Console.WriteLine(); } Console.WriteLine("count = {0}\n", count); } } } }
Eertree
C sharp|C# from Java
An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both ''tries'' and ''suffix trees''. See links below. ;Task: Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. ;See also: * Wikipedia entry: trie. * Wikipedia entry: suffix tree * Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; // empty or this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { //new Node(0, null, ODD_ROOT), or new Node(0, new Dictionary<char, int>(), ODD_ROOT), //new Node(-1, null, ODD_ROOT) or new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
Egyptian division
C sharp|C#
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
using System; using System.Collections; namespace Egyptian_division { class Program { public static void Main(string[] args) { Console.Clear(); Console.WriteLine(); Console.WriteLine(" Egyptian division "); Console.WriteLine(); Console.Write(" Enter value of dividend : "); int dividend = int.Parse(Console.ReadLine()); Console.Write(" Enter value of divisor : "); int divisor = int.Parse(Console.ReadLine()); Divide(dividend, divisor); Console.WriteLine(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } static void Divide(int dividend, int divisor) { // // Local variable declaration and initialization // int result = 0; int reminder = 0; int powers_of_two = 0; int doublings = 0; int answer = 0; int accumulator = 0; int two = 2; int pow = 0; int row = 0; // // Tables declaration // ArrayList table_powers_of_two = new ArrayList(); ArrayList table_doublings = new ArrayList(); // // Fill and Show table values // Console.WriteLine(" "); Console.WriteLine(" powers_of_2 doublings "); Console.WriteLine(" "); // Set initial values powers_of_two = 1; doublings = divisor; while( doublings <= dividend ) { // Set table value table_powers_of_two.Add( powers_of_two ); table_doublings.Add( doublings ); // Show new table row Console.WriteLine("{0,8}{1,16}",powers_of_two, doublings); pow++; powers_of_two = (int)Math.Pow( two, pow ); doublings = powers_of_two * divisor; } Console.WriteLine(" "); // // Calculate division and Show table values // row = pow - 1; Console.WriteLine(" "); Console.WriteLine(" powers_of_2 doublings answer accumulator"); Console.WriteLine(" "); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row); pow--; while( pow >= 0 && accumulator < dividend ) { // Get values from tables doublings = int.Parse(table_doublings[pow].ToString()); powers_of_two = int.Parse(table_powers_of_two[pow].ToString()); if(accumulator + int.Parse(table_doublings[pow].ToString()) <= dividend ) { // Set new values accumulator += doublings; answer += powers_of_two; // Show accumulated row values in different collor Console.ForegroundColor = ConsoleColor.Green; Console.Write("{0,8}{1,16}",powers_of_two, doublings); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("{0,10}{1,12}", answer, accumulator); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2); } else { // Show not accumulated row walues Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write("{0,8}{1,16}",powers_of_two, doublings); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("{0,10}{1,12}", answer, accumulator); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 2); } pow--; } Console.WriteLine(); Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop + row + 2); Console.ResetColor(); // Set result and reminder result = answer; if( accumulator < dividend ) { reminder = dividend - accumulator; Console.WriteLine(" So " + dividend + " divided by " + divisor + " using the Egyptian method is \n " + result + " remainder (" + dividend + " - " + accumulator + ") or " + reminder); Console.WriteLine(); } else { reminder = 0; Console.WriteLine(" So " + dividend + " divided by " + divisor + " using the Egyptian method is \n " + result + " remainder " + reminder); Console.WriteLine(); } } } }
Elementary cellular automaton
C sharp|C#
An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. ;Task: Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of [[one-dimensional cellular automata]]. ;See also * Cellular automata (natureofcode.com)
using System; using System.Collections; namespace ElementaryCellularAutomaton { class Automata { BitArray cells, ncells; const int MAX_CELLS = 19; public void run() { cells = new BitArray(MAX_CELLS); ncells = new BitArray(MAX_CELLS); while (true) { Console.Clear(); Console.WriteLine("What Rule do you want to visualize"); doRule(int.Parse(Console.ReadLine())); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } private byte getCells(int index) { byte b; int i1 = index - 1, i2 = index, i3 = index + 1; if (i1 < 0) i1 = MAX_CELLS - 1; if (i3 >= MAX_CELLS) i3 -= MAX_CELLS; b = Convert.ToByte( 4 * Convert.ToByte(cells.Get(i1)) + 2 * Convert.ToByte(cells.Get(i2)) + Convert.ToByte(cells.Get(i3))); return b; } private string getBase2(int i) { string s = Convert.ToString(i, 2); while (s.Length < 8) { s = "0" + s; } return s; } private void doRule(int rule) { Console.Clear(); string rl = getBase2(rule); cells.SetAll(false); ncells.SetAll(false); cells.Set(MAX_CELLS / 2, true); Console.WriteLine("Rule: " + rule + "\n----------\n"); for (int gen = 0; gen < 51; gen++) { Console.Write("{0, 4}", gen + ": "); foreach (bool b in cells) Console.Write(b ? "#" : "."); Console.WriteLine(""); int i = 0; while (true) { byte b = getCells(i); ncells[i] = '1' == rl[7 - b] ? true : false; if (++i == MAX_CELLS) break; } i = 0; foreach (bool b in ncells) cells[i++] = b; } Console.WriteLine(""); } }; class Program { static void Main(string[] args) { Automata t = new Automata(); t.run(); } } }
Empty directory
C sharp|C#
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.
using System; using System.IO; class Program { static void Main( string[] args ) { foreach ( string dir in args ) { Console.WriteLine( "'{0}' {1} empty", dir, IsDirectoryEmpty( dir ) ? "is" : "is not" ); } } private static bool IsDirectoryEmpty( string dir ) { return ( Directory.GetFiles( dir ).Length == 0 && Directory.GetDirectories( dir ).Length == 0 ); } }
Empty string
C sharp|C#
Languages may have features for dealing specifically with empty strings (those containing no characters). ;Task: ::* Demonstrate how to assign an empty string to a variable. ::* Demonstrate how to check that a string is empty. ::* Demonstrate how to check that a string is not empty.
using System; using System.Collections.Generic; static class Program { // In short: public static void Foo() { string s; // Assign empty string: s = ""; // or s = string.Empty; // Check for empty string only (false if s is null): if (s != null && s.Length == 0) { } // Check for null or empty (more idiomatic in .NET): if (string.IsNullOrEmpty(s)) { } } public static void Main() { // Equality is somewhat convoluted in .NET. // The methods above are the author's recommendation for each case. // s is initialized to null. It is a variable of the System.String type that is a null reference and is not // the empty string. string s = null; // Alias Console.WriteLine(bool) with a shorter name to make the demonstration code less verbose. Action<bool> P = Console.WriteLine; // Assign the empty string literal to s. s = ""; // ' Assign String.Empty to s. s = string.Empty; // The empty string literal is the same object reference as String.Empty because of string interning, meaning the // behavior of the two is identical. // From this point on, "" will be used instead of String.Empty for brevity. //#== operator (object) // The == operator tests for reference equality when overload resolution fails to find an operator defined by // either operand type. However, which strings are interned is a CLR implementation detail and may be unreliable // when comparing non-empty strings. The equivalent in VB.NET would be s Is "". // Note that there is no such operator as Object.op_Equality(Object, Object): the use of the == operator for // types of type Object is a C# language feature. P((object)s == ""); //#Object.ReferenceEquals(Object, Object) // The previous line is semantically to the following, though it does not involve a method call. P(object.ReferenceEquals(s, "")); //#String.op_Equality(String, String) // The equality operator of System.String is implemented as a call to String.Equals(String). Operators cannot be // called with method syntax in C#. P(s == ""); //#String.Equals(String, String) // Call the static method defined on the String type, which first calls Object.ReferenceEquals and then, after // verifying that both are strings of the same length, compares the strings character-by-character. P(string.Equals(s, "")); //#Object.Equals(Object, Object) // First checks for reference equality and whether one or both of the arguments is null. It then invokes the // instance Equals method of the left parameter. P(object.Equals(s, "")); //#String.Equals(String) // The method is called with the string literal as the receiver because a NullReferenceException is thrown if s // is null. P("".Equals(s)); //#String.Length // Check the Length property. The ?. (null-conditional) operator is used to avoid NullReferenceException. The Equals // call above can also be done this way. Null propagation makes the equality operator return false if one operand // is a Nullable<T> and does not have a value, making this result in false when s is null. P(s?.Length == 0); //#String.Length // A more traditional version of the null-conditional using a guard clause. // Both the null-conditional and this are noticeably (~4 times) faster than "".Equals(s). In general, it appears that // for empty strings, using the length is faster than using an equality comparison. P(s != null && s.Length == 0); //#String.IsNullOrEmpty(String) // Note that all of the other methods give false for null. // A static method of System.String that returns true if the string is null or its length is zero. P(string.IsNullOrEmpty(s)); //#System.Collections.Generic.EqualityComparer(Of String).Default.Equals(String, String) // The EqualityComparer(Of T) class provides default implementations when an IEqualityComparer(Of T) is required. // The implementation for String calls String.Equals(String). P(EqualityComparer<string>.Default.Equals(s, "")); Console.WriteLine(); // Each of the means described above, except testing for a non-empty string. P((object)s != ""); P(!object.ReferenceEquals(s, "")); P(s != ""); P(!string.Equals(s, "")); P(!object.Equals(s, "")); P(!"".Equals(s)); P(s?.Length != 0); // Still false when s is null! P(s == null || s.Length != 0); P(!string.IsNullOrEmpty(s)); P(!EqualityComparer<string>.Default.Equals(s, "")); } }
Equilibrium index
C sharp|C#
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence A: ::::: A_0 = -7 ::::: A_1 = 1 ::::: A_2 = 5 ::::: A_3 = 2 ::::: A_4 = -4 ::::: A_5 = 3 ::::: A_6 = 0 3 is an equilibrium index, because: ::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6 6 is also an equilibrium index, because: ::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. ;Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<int> EquilibriumIndices(IEnumerable<int> sequence) { var left = 0; var right = sequence.Sum(); var index = 0; foreach (var element in sequence) { right -= element; if (left == right) { yield return index; } left += element; index++; } } static void Main() { foreach (var index in EquilibriumIndices(new[] { -7, 1, 5, 2, -4, 3, 0 })) { Console.WriteLine(index); } } }
Euler's identity
C sharp|C#
{{Wikipedia|Euler's_identity}} In mathematics, ''Euler's identity'' is the equality: ei\pi + 1 = 0 where e is Euler's number, the base of natural logarithms, ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and \pi is pi, the ratio of the circumference of a circle to its diameter. Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants: The number 0. The number 1. The number \pi (\pi = 3.14159+), The number e (e = 2.71828+), which occurs widely in mathematical analysis. The number ''i'', the imaginary unit of the complex numbers. ;Task Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. If that is the case, or there is some other limitation, show that ei\pi + 1 is ''approximately'' equal to zero and show the amount of error in the calculation. If your language is capable of symbolic calculations, show that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.
using System; using System.Numerics; public class Program { static void Main() { Complex e = Math.E; Complex i = Complex.ImaginaryOne; Complex π = Math.PI; Console.WriteLine(Complex.Pow(e, i * π) + 1); } }
Euler's sum of powers conjecture
C sharp|C# from Java
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
using System; namespace EulerSumOfPowers { class Program { const int MAX_NUMBER = 250; static void Main(string[] args) { bool found = false; long[] fifth = new long[MAX_NUMBER]; for (int i = 1; i <= MAX_NUMBER; i++) { long i2 = i * i; fifth[i - 1] = i2 * i2 * i; } for (int a = 0; a < MAX_NUMBER && !found; a++) { for (int b = a; b < MAX_NUMBER && !found; b++) { for (int c = b; c < MAX_NUMBER && !found; c++) { for (int d = c; d < MAX_NUMBER && !found; d++) { long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d]; int e = Array.BinarySearch(fifth, sum); found = e >= 0; if (found) { Console.WriteLine("{0}^5 + {1}^5 + {2}^5 + {3}^5 = {4}^5", a + 1, b + 1, c + 1, d + 1, e + 1); } } } } } } } }
Euler's sum of powers conjecture
C sharp|C# from vbnet
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Euler_cs { class Program { struct Pair { public int a, b; public Pair(int x, int y) { a = x; b = y; } } static int min = 1, max = 250; static ulong[] p5; static SortedDictionary<ulong, Pair>[] sum2 = new SortedDictionary<ulong, Pair>[30]; static string Fmt(Pair p) { return string.Format("{0}^5 + {1}^5", p.a, p.b); } public static void InitM() { for (int i = 0; i <= 29; i++) sum2[i] = new SortedDictionary<ulong, Pair>(); p5 = new ulong[max + 1]; p5[min] = Convert.ToUInt64(min) * Convert.ToUInt64(min); p5[min] *= p5[min] * Convert.ToUInt64(min); for (int i = min; i <= max - 1; i++) { for (int j = i + 1; j <= max; j++) { p5[j] = Convert.ToUInt64(j) * Convert.ToUInt64(j); p5[j] *= p5[j] * Convert.ToUInt64(j); if (j == max) continue; ulong x = p5[i] + p5[j]; sum2[x % 30].Add(x, new Pair(i, j)); } } } static List<string> CalcM(int m) { List<string> res = new List<string>(); for (int i = max; i >= min; i--) { ulong p = p5[i]; int pm = i % 30, mp = (pm - m + 30) % 30; foreach (var s in sum2[m].Keys) { if (p <= s) break; ulong t = p - s; if (sum2[mp].Keys.Contains(t) && sum2[mp][t].a > sum2[m][s].b) res.Add(string.Format(" {1} + {2} = {0}^5", i, Fmt(sum2[m][s]), Fmt(sum2[mp][t]))); } } return res; } static int Snip(string s) { int p = s.IndexOf("=") + 1; return Convert.ToInt32(s.Substring(p, s.IndexOf("^", p) - p)); } static int CompareRes(string x, string y) { int res = Snip(x).CompareTo(Snip(y)); if (res == 0) res = x.CompareTo(y); return res; } static int Validify(int def, string s) { int res = def, t = 0; int.TryParse(s, out t); if (t >= 1 && t < Math.Pow((double)(ulong.MaxValue >> 1), 0.2)) res = t; return res; } static void Switch(ref int a, ref int b) { int t = a; a = b; b = t; } static void Main(string[] args) { if (args.Count() > 1) { min = Validify(min, args[0]); max = Validify(max, args[1]); if (max < min) Switch(ref max, ref min); } else if (args.Count() == 1) max = Validify(max, args[0]); Console.WriteLine("Mod 30 shortcut with threading, checking from {0} to {1}...", min, max); List<string> res = new List<string>(); DateTime st = DateTime.Now; List<Task<List<string>>> taskList = new List<Task<List<string>>>(); InitM(); for (int j = 0; j <= 29; j++) { var jj = j; taskList.Add(Task.Run(() => CalcM(jj))); } Task.WhenAll(taskList); foreach (var item in taskList.Select(t => t.Result)) res.AddRange(item); res.Sort(CompareRes); foreach (var item in res) Console.WriteLine(item); Console.WriteLine(" Computation time to check entire space was {0} seconds", (DateTime.Now - st).TotalSeconds); if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey(); } } }
Even or odd
C sharp|C#
Test whether an integer is even or odd. There is more than one way to solve this task: * Use the even and odd predicates, if the language provides them. * Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd. * Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd. * Use modular congruences: ** ''i'' 0 (mod 2) iff ''i'' is even. ** ''i'' 1 (mod 2) iff ''i'' is odd.
namespace RosettaCode { using System; public static class EvenOrOdd { public static bool IsEvenBitwise(this int number) { return (number & 1) == 0; } public static bool IsOddBitwise(this int number) { return (number & 1) != 0; } public static bool IsEvenRemainder(this int number) { int remainder; Math.DivRem(number, 2, out remainder); return remainder == 0; } public static bool IsOddRemainder(this int number) { int remainder; Math.DivRem(number, 2, out remainder); return remainder != 0; } public static bool IsEvenModulo(this int number) { return (number % 2) == 0; } public static bool IsOddModulo(this int number) { return (number % 2) != 0; } } public class Program { public static void Main() { int num = 26; //Set this to any integer. if (num.IsEvenBitwise()) //Replace this with any even function. { Console.Write("Even"); } else { Console.Write("Odd"); } //Prints "Even". if (num.IsOddBitwise()) //Replace this with any odd function. { Console.Write("Odd"); } else { Console.Write("Even"); } //Prints "Even". } } }
Evolutionary algorithm
C sharp
Starting with: * The target string: "METHINKS IT IS LIKE A WEASEL". * An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). * A fitness function that computes the 'closeness' of its argument to the target string. * A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. :* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. :* repeat until the parent converges, (hopefully), to the target. ;See also: * Wikipedia entry: Weasel algorithm. * Wikipedia entry: Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, '''changing randomly any characters which don't already match the target''': ''NOTE:'' this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
using System; using System.Collections.Generic; using System.Linq; static class Program { static Random Rng = new Random((int)DateTime.Now.Ticks); static char NextCharacter(this Random self) { const string AllowedChars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; return AllowedChars[self.Next() % AllowedChars.Length]; } static string NextString(this Random self, int length) { return String.Join("", Enumerable.Repeat(' ', length) .Select(c => Rng.NextCharacter())); } static int Fitness(string target, string current) { return target.Zip(current, (a, b) => a == b ? 1 : 0).Sum(); } static string Mutate(string current, double rate) { return String.Join("", from c in current select Rng.NextDouble() <= rate ? Rng.NextCharacter() : c); } static void Main(string[] args) { const string target = "METHINKS IT IS LIKE A WEASEL"; const int C = 100; const double P = 0.05; // Start with a random string the same length as the target. string parent = Rng.NextString(target.Length); Console.WriteLine("START: {0,20} fitness: {1}", parent, Fitness(target, parent)); int i = 0; while (parent != target) { // Create C mutated strings + the current parent. var candidates = Enumerable.Range(0, C + 1) .Select(n => n > 0 ? Mutate(parent, P) : parent); // select the fittest parent = candidates.OrderByDescending(c => Fitness(target, c)).First(); ++i; Console.WriteLine(" #{0,6} {1,20} fitness: {2}", i, parent, Fitness(target, parent)); } Console.WriteLine("END: #{0,6} {1,20}", i, parent); } }
Execute HQ9+
C sharp|C#
Implement a ''' [[HQ9+]] ''' interpreter or compiler.
using System; using System.Collections.Generic; using System.Linq; class Program { static void RunCode(string code) { int accumulator = 0; var opcodes = new Dictionary<char, Action> { {'H', () => Console.WriteLine("Hello, World!"))}, {'Q', () => Console.WriteLine(code) }, {'9', () => Console.WriteLine(Enumerable.Range(1,100).Reverse().Select(n => string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around\n{1} bottles of beer on the wall\n", n, n-1)).Aggregate((a,b) => a + "\n" + b))}, {'+', () => accumulator++ } } foreach(var c in code) opcodes[c](); } }
Exponentiation order
C sharp|C#
This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents. (Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.) ;Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification): ::::* 5**3**2 ::::* (5**3)**2 ::::* 5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. ;See also: * MathWorld entry: exponentiation ;Related tasks: * exponentiation operator * arbitrary-precision integers (included) * [[Exponentiation with infix operators in (or operating on) the base]]
using System; namespace exponents { class Program { static void Main(string[] args) { /* * Like C, C# does not have an exponent operator. * Exponentiation is done via Math.Pow, which * only takes two arguments */ Console.WriteLine(Math.Pow(Math.Pow(5, 3), 2)); Console.WriteLine(Math.Pow(5, Math.Pow(3, 2))); Console.Read(); } } }
Extend your language
C sharp|C#
{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
using System; using System.Reflection; namespace Extend_your_language { class Program { public static void Main(string[] args) { Console.WriteLine(); Console.WriteLine("Hello World!"); Console.WriteLine(); int x = 0; int y = 0; for(x=0;x<2;x++) { for(y=0;y<2;y++) { CONDITIONS( (x==0) , (y==0) ). IF2 ("METHOD1"). ELSE1("METHOD2"). ELSE2("METHOD3"). ELSE ("METHOD4"); } } Console.WriteLine(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } public static void METHOD1() { Console.WriteLine("METHOD 1 executed - both are true"); } public static void METHOD2() { Console.WriteLine("METHOD 2 executed - first is true"); } public static void METHOD3() { Console.WriteLine("METHOD 3 executed - second is true"); } public static void METHOD4() { Console.WriteLine("METHOD 4 executed - both are false"); } static int CONDITIONS(bool condition1, bool condition2) { int c = 0; if(condition1 && condition2) c = 0; else if(condition1) c = 1; else if(condition2) c = 2; else c = 3; return c; } } public static class ExtensionMethods { public static int IF2(this int value, string method) { if(value == 0) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); } return value; } public static int ELSE1(this int value, string method) { if(value == 1) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); } return value; } public static int ELSE2(this int value, string method) { if(value == 2) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); } return value; } public static void ELSE(this int value, string method) { if(value == 3) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); } } } }
FASTA format
C sharp|C#
In FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. ;Task: Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED
using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { public class FastaEntry { public string Name { get; set; } public StringBuilder Sequence { get; set; } } static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile) { FastaEntry f = null; string line; while ((line = fastaFile.ReadLine()) != null) { // ignore comment lines if (line.StartsWith(";")) continue; if (line.StartsWith(">")) { if (f != null) yield return f; f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() }; } else if (f != null) f.Sequence.Append(line); } yield return f; } static void Main(string[] args) { try { using (var fastaFile = new StreamReader("fasta.txt")) { foreach (FastaEntry f in ParseFasta(fastaFile)) Console.WriteLine("{0}: {1}", f.Name, f.Sequence); } } catch (FileNotFoundException e) { Console.WriteLine(e); } Console.ReadLine(); } }
Farey sequence
C sharp|C# from Java
The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size. The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. Each Farey sequence: :::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1} :::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}. The Farey sequences of orders '''1''' to '''5''' are: :::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1} : :::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1} : :::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1} : :::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1} : :::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1} ;Task * Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive). * Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds. * Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). The length (the number of fractions) of a Farey sequence asymptotically approaches: ::::::::::: 3 x n2 / \pi2 ;See also: * OEIS sequence A006842 numerators of Farey series of order 1, 2, *** * OEIS sequence A006843 denominators of Farey series of order 1, 2, *** * OEIS sequence A005728 number of fractions in Farey series of order n * MathWorld entry Farey sequence * Wikipedia entry Farey sequence
using System; using System.Collections.Generic; using System.Linq; public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; i <= 1000; i+=100) { Console.WriteLine($"F{i} has {Generate(i).Count()} terms."); } } public static IEnumerable<(int num, int den)> Generate(int i) { var comparer = Comparer<(int n, int d)>.Create((a, b) => (a.n * b.d).CompareTo(a.d * b.n)); var seq = new SortedSet<(int n, int d)>(comparer); for (int d = 1; d <= i; d++) { for (int n = 0; n <= d; n++) { seq.Add((n, d)); } } return seq; } }
Fast Fourier transform
C sharp|C#
Calculate the FFT (Fast Fourier Transform) of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
using System; using System.Numerics; using System.Linq; using System.Diagnostics; // Fast Fourier Transform in C# public class Program { /* Performs a Bit Reversal Algorithm on a postive integer * for given number of bits * e.g. 011 with 3 bits is reversed to 110 */ public static int BitReverse(int n, int bits) { int reversedN = n; int count = bits - 1; n >>= 1; while (n > 0) { reversedN = (reversedN << 1) | (n & 1); count--; n >>= 1; } return ((reversedN << count) & ((1 << bits) - 1)); } /* Uses Cooley-Tukey iterative in-place algorithm with radix-2 DIT case * assumes no of points provided are a power of 2 */ public static void FFT(Complex[] buffer) { #if false int bits = (int)Math.Log(buffer.Length, 2); for (int j = 1; j < buffer.Length / 2; j++) { int swapPos = BitReverse(j, bits); var temp = buffer[j]; buffer[j] = buffer[swapPos]; buffer[swapPos] = temp; } // Said Zandian // The above section of the code is incorrect and does not work correctly and has two bugs. // BUG 1 // The bug is that when you reach and index that was swapped previously it does swap it again // Ex. binary value n = 0010 and Bits = 4 as input to BitReverse routine and returns 4. The code section above // swaps it. Cells 2 and 4 are swapped. just fine. // now binary value n = 0010 and Bits = 4 as input to BitReverse routine and returns 2. The code Section // swap it. Cells 4 and 2 are swapped. WROOOOONG // // Bug 2 // The code works on the half section of the cells. In the case of Bits = 4 it means that we are having 16 cells // The code works on half the cells for (int j = 1; j < buffer.Length / 2; j++) buffer.Length returns 16 // and divide by 2 makes 8, so j goes from 1 to 7. This covers almost everything but what happened to 1011 value // which must be swap with 1101. and this is the second bug. // // use the following corrected section of the code. I have seen this bug in other languages that uses bit // reversal routine. #else for (int j = 1; j < buffer.Length; j++) { int swapPos = BitReverse(j, bits); if (swapPos <= j) { continue; } var temp = buffer[j]; buffer[j] = buffer[swapPos]; buffer[swapPos] = temp; } // First the full length is used and 1011 value is swapped with 1101. Second if new swapPos is less than j // then it means that swap was happen when j was the swapPos. #endif for (int N = 2; N <= buffer.Length; N <<= 1) { for (int i = 0; i < buffer.Length; i += N) { for (int k = 0; k < N / 2; k++) { int evenIndex = i + k; int oddIndex = i + k + (N / 2); var even = buffer[evenIndex]; var odd = buffer[oddIndex]; double term = -2 * Math.PI * k / (double)N; Complex exp = new Complex(Math.Cos(term), Math.Sin(term)) * odd; buffer[evenIndex] = even + exp; buffer[oddIndex] = even - exp; } } } } public static void Main(string[] args) { Complex[] input = {1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0}; FFT(input); Console.WriteLine("Results:"); foreach (Complex c in input) { Console.WriteLine(c); } } }
Feigenbaum constant calculation
C sharp|C# from Kotlin
Calculate the Feigenbaum constant. ;See: :* Details in the Wikipedia article: Feigenbaum constant.
using System; namespace FeigenbaumConstant { class Program { static void Main(string[] args) { var maxIt = 13; var maxItJ = 10; var a1 = 1.0; var a2 = 0.0; var d1 = 3.2; Console.WriteLine(" i d"); for (int i = 2; i <= maxIt; i++) { var a = a1 + (a1 - a2) / d1; for (int j = 1; j <= maxItJ; j++) { var x = 0.0; var y = 0.0; for (int k = 1; k <= 1<<i; k++) { y = 1.0 - 2.0 * y * x; x = a - x * x; } a -= x / y; } var d = (a1 - a2) / (a - a1); Console.WriteLine("{0,2:d} {1:f8}", i, d); d1 = d; a2 = a1; a1 = a; } } } }
Fibonacci n-step number sequences
C sharp|C#
These number series are an expansion of the ordinary [[Fibonacci sequence]] where: # For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2 # For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3 # For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4... # For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}} For small values of n, Greek numeric prefixes are sometimes used to individually name each series. :::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2" |+ Fibonacci n-step sequences |- style="background-color: rgb(255, 204, 255);" ! n !! Series name !! Values |- | 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |- | 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |- | 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |- | 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |- | 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |- | 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |- | 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |- | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |- | 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |} Allied sequences can be generated where the initial values are changed: : '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values. ;Task: # Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. # Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. ;Related tasks: * [[Fibonacci sequence]] * Wolfram Mathworld * [[Hofstadter Q sequence]] * [[Leonardo numbers]] ;Also see: * Lucas Numbers - Numberphile (Video) * Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video) * Wikipedia, Lucas number * MathWorld, Fibonacci Number * Some identities for r-Fibonacci numbers * OEIS Fibonacci numbers * OEIS Lucas numbers
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fibonacci { class Program { static void Main(string[] args) { PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10)); PrintNumberSequence("Lucas", GetLucasNumbers(10)); PrintNumberSequence("Tribonacci", GetNnacciNumbers(3, 10)); PrintNumberSequence("Tetranacci", GetNnacciNumbers(4, 10)); Console.ReadKey(); } private static IList<ulong> GetLucasNumbers(int length) { IList<ulong> seedSequence = new List<ulong>() { 2, 1 }; return GetFibLikeSequence(seedSequence, length); } private static IList<ulong> GetNnacciNumbers(int seedLength, int length) { return GetFibLikeSequence(GetNacciSeed(seedLength), length); } private static IList<ulong> GetNacciSeed(int seedLength) { IList<ulong> seedSquence = new List<ulong>() { 1 }; for (uint i = 0; i < seedLength - 1; i++) { seedSquence.Add((ulong)Math.Pow(2, i)); } return seedSquence; } private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length) { IList<ulong> sequence = new List<ulong>(); int count = seedSequence.Count(); if (length <= count) { sequence = seedSequence.Take((int)length).ToList(); } else { sequence = seedSequence; for (int i = count; i < length; i++) { ulong num = 0; for (int j = 0; j < count; j++) { num += sequence[sequence.Count - 1 - j]; } sequence.Add(num); } } return sequence; } private static void PrintNumberSequence(string Title, IList<ulong> numbersequence) { StringBuilder output = new StringBuilder(Title).Append(" "); foreach (long item in numbersequence) { output.AppendFormat("{0}, ", item); } Console.WriteLine(output.ToString()); } } }
Fibonacci word
C sharp|C#
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here: Define F_Word1 as '''1''' Define F_Word2 as '''0''' Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01''' Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2 ;Task: Perform the above steps for n = 37. You may display the first few but not the larger values of n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for F_Words '''1''' to '''37''' which shows: ::* The number of characters in the word ::* The word's [[Entropy]] ;Related tasks: * Fibonacci word/fractal * [[Entropy]] * [[Entropy/Narcissist]]
using SYS = System; using SCG = System.Collections.Generic; // // Basically a port of the C++ solution as posted // 2017-11-12. // namespace FibonacciWord { class Program { static void Main( string[] args ) { PrintHeading(); string firstString = "1"; int n = 1; PrintLine( n, firstString ); string secondString = "0"; ++n; PrintLine( n, secondString ); while ( n < 37 ) { string resultString = firstString + secondString; firstString = secondString; secondString = resultString; ++n; PrintLine( n, resultString ); } } private static void PrintLine( int n, string result ) { SYS.Console.Write( "{0,-5}", n ); SYS.Console.Write( "{0,12}", result.Length ); SYS.Console.WriteLine( " {0,-16}", GetEntropy( result ) ); } private static double GetEntropy( string result ) { SCG.Dictionary<char, int> frequencies = new SCG.Dictionary<char, int>(); foreach ( char c in result ) { if ( frequencies.ContainsKey( c ) ) { ++frequencies[c]; } else { frequencies[c] = 1; } } int length = result.Length; double entropy = 0; foreach ( var keyValue in frequencies ) { double freq = (double)keyValue.Value / length; entropy += freq * SYS.Math.Log( freq, 2 ); } return -entropy; } private static void PrintHeading() { SYS.Console.Write( "{0,-5}", "N" ); SYS.Console.Write( "{0,12}", "Length" ); SYS.Console.WriteLine( " {0,-16}", "Entropy" ); } } }
Find limit of recursion
C sharp|C#
{{selection|Short Circuit|Console Program Basics}} ;Task: Find the limit of recursion.
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
Find palindromic numbers in both binary and ternary bases
C sharp 3
* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'': :::* base 2 :::* base 3 * Display '''0''' (zero) as the first number found, even though some other definitions ignore it. * Optionally, show the decimal number found in its binary and ternary form. * Show all output here. It's permissible to assume the first two numbers and simply list them. ;See also * Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
using System; using System.Collections.Generic; using System.Linq; public class FindPalindromicNumbers { static void Main(string[] args) { var query = PalindromicTernaries() .Where(IsPalindromicBinary) .Take(6); foreach (var x in query) { Console.WriteLine("Decimal: " + x); Console.WriteLine("Ternary: " + ToTernary(x)); Console.WriteLine("Binary: " + Convert.ToString(x, 2)); Console.WriteLine(); } } public static IEnumerable<long> PalindromicTernaries() { yield return 0; yield return 1; yield return 13; yield return 23; var f = new List<long> {0}; long fMiddle = 9; while (true) { for (long edge = 1; edge < 3; edge++) { int i; do { //construct the result long result = fMiddle; long fLeft = fMiddle * 3; long fRight = fMiddle / 3; for (int j = f.Count - 1; j >= 0; j--) { result += (fLeft + fRight) * f[j]; fLeft *= 3; fRight /= 3; } result += (fLeft + fRight) * edge; yield return result; //next permutation for (i = f.Count - 1; i >= 0; i--) { if (f[i] == 2) { f[i] = 0; } else { f[i]++; break; } } } while (i >= 0); } f.Add(0); fMiddle *= 3; } } public static bool IsPalindromicBinary(long number) { long n = number; long reverse = 0; while (n != 0) { reverse <<= 1; if ((n & 1) == 1) reverse++; n >>= 1; } return reverse == number; } public static string ToTernary(long n) { if (n == 0) return "0"; string result = ""; while (n > 0) { { result = (n % 3) + result; n /= 3; } return result; } }
Find the intersection of a line with a plane
C sharp|C#
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. ;Task: Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
using System; namespace FindIntersection { class Vector3D { private double x, y, z; public Vector3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public static Vector3D operator +(Vector3D lhs, Vector3D rhs) { return new Vector3D(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); } public static Vector3D operator -(Vector3D lhs, Vector3D rhs) { return new Vector3D(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z); } public static Vector3D operator *(Vector3D lhs, double rhs) { return new Vector3D(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs); } public double Dot(Vector3D rhs) { return x * rhs.x + y * rhs.y + z * rhs.z; } public override string ToString() { return string.Format("({0:F}, {1:F}, {2:F})", x, y, z); } } class Program { static Vector3D IntersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { var diff = rayPoint - planePoint; var prod1 = diff.Dot(planeNormal); var prod2 = rayVector.Dot(planeNormal); var prod3 = prod1 / prod2; return rayPoint - rayVector * prod3; } static void Main(string[] args) { var rv = new Vector3D(0.0, -1.0, -1.0); var rp = new Vector3D(0.0, 0.0, 10.0); var pn = new Vector3D(0.0, 0.0, 1.0); var pp = new Vector3D(0.0, 0.0, 5.0); var ip = IntersectPoint(rv, rp, pn, pp); Console.WriteLine("The ray intersects the plane at {0}", ip); } } }
Find the intersection of two lines
C sharp|C#
Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html] ;Task: Find the point of intersection of two lines in 2D. The 1st line passes though (4,0) and (6,10) . The 2nd line passes though (0,3) and (10,7) .
using System; using System.Drawing; public class Program { static PointF FindIntersection(PointF s1, PointF e1, PointF s2, PointF e2) { float a1 = e1.Y - s1.Y; float b1 = s1.X - e1.X; float c1 = a1 * s1.X + b1 * s1.Y; float a2 = e2.Y - s2.Y; float b2 = s2.X - e2.X; float c2 = a2 * s2.X + b2 * s2.Y; float delta = a1 * b2 - a2 * b1; //If lines are parallel, the result will be (NaN, NaN). return delta == 0 ? new PointF(float.NaN, float.NaN) : new PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta); } static void Main() { Func<float, float, PointF> p = (x, y) => new PointF(x, y); Console.WriteLine(FindIntersection(p(4f, 0f), p(6f, 10f), p(0f, 3f), p(10f, 7f))); Console.WriteLine(FindIntersection(p(0f, 0f), p(1f, 1f), p(1f, 2f), p(4f, 5f))); } }
Find the last Sunday of each month
C sharp|C#
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 ;Related tasks * [[Day of the week]] * [[Five weekends]] * [[Last Friday of each month]]
using System; namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: "); string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear); DateTime date; for (int i = 1; i <= 12; i++) { date = new DateTime(year, i, DateTime.DaysInMonth(year, i), System.Globalization.CultureInfo.CurrentCulture.Calendar); /* Modification by Albert Zakhia on 2021-16-02 The below code is very slow due to the loop, we will go twice as fast while (date.DayOfWeek != DayOfWeek.Sunday) { date = date.AddDays(-1); } */ // The updated code int daysOffset = date.DayOfWeek - dayOfWeek; // take the offset to subtract directly instead of looping if (daysOffset < 0) daysOffset += 7; // if the code is negative, we need to normalize them date = date.AddDays(-daysOffset ); // now just add the days offset Console.WriteLine(date.ToString("yyyy-MM-dd")); } } } }
Find the missing permutation
C sharp
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. ;Task: Find that missing permutation. ;Methods: * Obvious method: enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', and then look for the missing permutation. * alternate method: Hint: if all permutations were shown above, how many times would '''A''' appear in each position? What is the ''parity'' of this number? * another alternate method: Hint: if you add up the letter values of each column, does a missing letter '''A''', '''B''', '''C''', and '''D''' from each column cause the total value for each column to be unique? ;Related task: * [[Permutations]])
using System; using System.Linq; public class Test { public static void Main() { var input = new [] {"ABCD","CABD","ACDB","DACB","BCDA", "ACBD","ADCB","CDAB","DABC","BCAD","CADB", "CDBA","CBAD","ABDC","ADBC","BDCA","DCBA", "BACD","BADC","BDAC","CBDA","DBCA","DCAB"}; int[] values = {0,0,0,0}; foreach (string s in input) for (int i = 0; i < 4; i++) values[i] ^= s[i]; Console.WriteLine(string.Join("", values.Select(i => (char)i))); } }
First-class functions/Use numbers analogously
C# 4.0
In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. '''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
First perfect square in base n with n unique digits
C sharp|C# from Visual Basic .NET
Find the first perfect square in a given base '''N''' that has at least '''N''' digits and exactly '''N''' ''significant unique'' digits when expressed in base '''N'''. E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432'''). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. ;Task * Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated. * (optional) Do the same for bases '''13''' through '''16'''. * (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math) ;See also: ;* OEIS A260182: smallest square that is pandigital in base n. ;Related task ;* [[Casting out nines]]
using System; using System.Collections.Generic; using System.Numerics; static class Program { static byte Base, bmo, blim, ic; static DateTime st0; static BigInteger bllim, threshold; static HashSet<byte> hs = new HashSet<byte>(), o = new HashSet<byte>(); static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"; static List<BigInteger> limits; static string ms; // convert BigInteger to string using current base static string toStr(BigInteger b) { string res = ""; BigInteger re; while (b > 0) { b = BigInteger.DivRem(b, Base, out re); res = chars[(byte)re] + res; } return res; } // check for a portion of digits, bailing if uneven static bool allInQS(BigInteger b) { BigInteger re; int c = ic; hs.Clear(); hs.UnionWith(o); while (b > bllim) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); c += 1; if (c > hs.Count) return false; } return true; } // check for a portion of digits, all the way to the end static bool allInS(BigInteger b) { BigInteger re; hs.Clear(); hs.UnionWith(o); while (b > bllim) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); } return hs.Count == Base; } // check for all digits, bailing if uneven static bool allInQ(BigInteger b) { BigInteger re; int c = 0; hs.Clear(); while (b > 0) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); c += 1; if (c > hs.Count) return false; } return true; } // check for all digits, all the way to the end static bool allIn(BigInteger b) { BigInteger re; hs.Clear(); while (b > 0) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); } return hs.Count == Base; } // parse a string into a BigInteger, using current base static BigInteger to10(string s) { BigInteger res = 0; foreach (char i in s) res = res * Base + chars.IndexOf(i); return res; } // returns the minimum value string, optionally inserting extra digit static string fixup(int n) { string res = chars.Substring(0, Base); if (n > 0) res = res.Insert(n, n.ToString()); return "10" + res.Substring(2); } // checks the square against the threshold, advances various limits when needed static void check(BigInteger sq) { if (sq > threshold) { o.Remove((byte)chars.IndexOf(ms[blim])); blim -= 1; ic -= 1; threshold = limits[bmo - blim - 1]; bllim = to10(ms.Substring(0, blim + 1)); } } // performs all the caclulations for the current base static void doOne() { limits = new List<BigInteger>(); bmo = (byte)(Base - 1); byte dr = 0; if ((Base & 1) == 1) dr = (byte)(Base >> 1); o.Clear(); blim = 0; byte id = 0; int inc = 1; long i = 0; DateTime st = DateTime.Now; if (Base == 2) st0 = st; byte[] sdr = new byte[bmo]; byte rc = 0; for (i = 0; i < bmo; i++) { sdr[i] = (byte)((i * i) % bmo); rc += sdr[i] == dr ? (byte)1 : (byte)0; sdr[i] += sdr[i] == 0 ? bmo : (byte)0; } i = 0; if (dr > 0) { id = Base; for (i = 1; i <= dr; i++) if (sdr[i] >= dr) if (id > sdr[i]) id = sdr[i]; id -= dr; i = 0; } ms = fixup(id); BigInteger sq = to10(ms); BigInteger rt = new BigInteger(Math.Sqrt((double)sq) + 1); sq = rt * rt; if (Base > 9) { for (int j = 1; j < Base; j++) limits.Add(to10(ms.Substring(0, j) + new string(chars[bmo], Base - j + (rc > 0 ? 0 : 1)))); limits.Reverse(); while (sq < limits[0]) { rt++; sq = rt * rt; } } BigInteger dn = (rt << 1) + 1; BigInteger d = 1; if (Base > 3 && rc > 0) { while (sq % bmo != dr) { rt += 1; sq += dn; dn += 2; } // alligns sq to dr inc = bmo / rc; if (inc > 1) { dn += rt * (inc - 2) - 1; d = inc * inc; } dn += dn + d; } d <<= 1; if (Base > 9) { blim = 0; while (sq < limits[bmo - blim - 1]) blim++; ic = (byte)(blim + 1); threshold = limits[bmo - blim - 1]; if (blim > 0) for (byte j = 0; j <= blim; j++) o.Add((byte)chars.IndexOf(ms[j])); if (blim > 0) bllim = to10(ms.Substring(0, blim + 1)); else bllim = 0; if (Base > 5 && rc > 0) do { if (allInQS(sq)) break; sq += dn; dn += d; i += 1; check(sq); } while (true); else do { if (allInS(sq)) break; sq += dn; dn += d; i += 1; check(sq); } while (true); } else { if (Base > 5 && rc > 0) do { if (allInQ(sq)) break; sq += dn; dn += d; i += 1; } while (true); else do { if (allIn(sq)) break; sq += dn; dn += d; i += 1; } while (true); } rt += i * inc; Console.WriteLine("{0,3} {1,2} {2,2} {3,20} -> {4,-40} {5,10} {6,9:0.0000}s {7,9:0.0000}s", Base, inc, (id > 0 ? chars.Substring(id, 1) : " "), toStr(rt), toStr(sq), i, (DateTime.Now - st).TotalSeconds, (DateTime.Now - st0).TotalSeconds); } static void Main(string[] args) { Console.WriteLine("base inc id root square" + " test count time total"); for (Base = 2; Base <= 28; Base++) doOne(); Console.WriteLine("Elasped time was {0,8:0.00} minutes", (DateTime.Now - st0).TotalMinutes); } }
First power of 2 that has leading decimal digits of 12
C sharp|C# from C++
(This task is taken from a ''Project Euler'' problem.) (All numbers herein are expressed in base ten.) '''27 = 128''' and '''7''' is the first power of '''2''' whose leading decimal digits are '''12'''. The next power of '''2''' whose leading decimal digits are '''12''' is '''80''', '''280 = 1208925819614629174706176'''. Define ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest value of ''' ''j'' ''' such that the base ten representation of '''2''j''''' begins with the digits of ''' ''L'' '''. So ''p''(12, 1) = 7 and ''p''(12, 2) = 80 You are also given that: ''p''(123, 45) = 12710 ;Task: ::* find: :::::* ''' ''p''(12, 1) ''' :::::* ''' ''p''(12, 2) ''' :::::* ''' ''p''(123, 45) ''' :::::* ''' ''p''(123, 12345) ''' :::::* ''' ''p''(123, 678910) ''' ::* display the results here, on this page.
// a mini chrestomathy solution using System; class Program { // translated from java example static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; } // translated from go integer example (a.k.a. go translation of pascal alternative example) static long gi(int ld, int n) { string Ls = ld.ToString(); long res = 0, count = 0, f = 1; for (int i = 1; i <= 18 - Ls.Length; i++) f *= 10; const long ten18 = (long)1e18; long probe = 1; do { probe <<= 1; res++; if (probe >= ten18) do { if (probe >= ten18) probe /= 10; if (probe / f == ld) if (++count >= n) { count--; break; } probe <<= 1; res++; } while (true); string ps = probe.ToString(); if (ps.Substring(0, Math.Min(Ls.Length, ps.Length)) == Ls) if (++count >= n) break; } while (true); return res; } // translated from pascal alternative example static long pa(int ld, int n) { double L_float64 = Math.Pow(2, 64); ulong Log10_2_64 = (ulong)(L_float64 * Math.Log10(2)); double Log10Num; ulong LmtUpper, LmtLower, Frac64; long res = 0, dgts = 1, cnt; for (int i = ld; i >= 10; i /= 10) dgts *= 10; Log10Num = Math.Log10((ld + 1.0) / dgts); // '316' was a limit if (Log10Num >= 0.5) { LmtUpper = (ld + 1.0) / dgts < 10.0 ? (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2) : 0; Log10Num = Math.Log10((double)ld / dgts); LmtLower = (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2); } else { LmtUpper = (ulong)(Log10Num * L_float64); LmtLower = (ulong)(Math.Log10((double)ld / dgts) * L_float64); } cnt = 0; Frac64 = 0; if (LmtUpper != 0) do { res++; Frac64 += Log10_2_64; if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper)) if (++cnt >= n) break; } while (true); else // '999..' do { res++; Frac64 += Log10_2_64; if (Frac64 >= LmtLower) if (++cnt >= n) break; } while (true); return res; } static int[] values = new int[] { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 }; static void doOne(string name, Func<int, int, long> fun) { Console.WriteLine("{0} version:", name); var start = DateTime.Now; for (int i = 0; i < values.Length; i += 2) Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", values[i], values[i + 1], fun(values[i], values[i + 1])); Console.WriteLine("Took {0} seconds\n", DateTime.Now - start); } static void Main() { doOne("java simple", js); doOne("go integer", gi); doOne("pascal alternative", pa); } }
Fivenum
C sharp|C# from Java
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory. For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function. ;Task: Given an array of numbers, compute the five-number summary. ;Note: While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } } class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; } static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; } static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
Flatten a list
C sharp
Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] ;Related task: * [[Tree traversal]]
public static class Ex { public static List<object> Flatten(this List<object> list) { var result = new List<object>(); foreach (var item in list) { if (item is List<object>) { result.AddRange(Flatten(item as List<object>)); } else { result.Add(item); } } return result; } public static string Join<T>(this List<T> list, string glue) { return string.Join(glue, list.Select(i => i.ToString()).ToArray()); } } class Program { static void Main(string[] args) { var list = new List<object>{new List<object>{1}, 2, new List<object>{new List<object>{3,4}, 5}, new List<object>{new List<object>{new List<object>{}}}, new List<object>{new List<object>{new List<object>{6}}}, 7, 8, new List<object>{}}; Console.WriteLine("[" + list.Flatten().Join(", ") + "]"); Console.ReadLine(); } }