title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Floyd's triangle
C sharp|C# from Perl
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where * the first row is '''1''' (unity) * successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ;Task: :# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows). :# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
using System; using System.Text; public class FloydsTriangle { internal static void Main(string[] args) { int count; if (args.Length >= 1 && int.TryParse(args[0], out count) && count > 0) { Console.WriteLine(MakeTriangle(count)); } else { Console.WriteLine(MakeTriangle(5)); Console.WriteLine(); Console.WriteLine(MakeTriangle(14)); } } public static string MakeTriangle(int rows) { int maxValue = (rows * (rows + 1)) / 2; int digit = 0; StringBuilder output = new StringBuilder(); for (int row = 1; row <= rows; row++) { for (int column = 0; column < row; column++) { int colMaxDigit = (maxValue - rows) + column + 1; if (column > 0) { output.Append(' '); } digit++; output.Append(digit.ToString().PadLeft(colMaxDigit.ToString().Length)); } output.AppendLine(); } return output.ToString(); } }
Four bit adder
C sharp
"''Simulate''" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two gate. ; Finally a half adder can be made using an ''xor'' gate and an ''and'' gate. The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''. '''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones. {| |+Schematics of the "constructive blocks" !(Xor gate with ANDs, ORs and NOTs) ! (A half adder) ! (A full adder) ! (A 4-bit adder) |- |Xor gate done with ands, ors and nots |A half adder |A full adder |A 4-bit adder |} Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks.FourBitAdder { public struct BitAdderOutput { public bool S { get; set; } public bool C { get; set; } public override string ToString ( ) { return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" ); } } public struct Nibble { public bool _1 { get; set; } public bool _2 { get; set; } public bool _3 { get; set; } public bool _4 { get; set; } public override string ToString ( ) { return ( _4 ? "1" : "0" ) + ( _3 ? "1" : "0" ) + ( _2 ? "1" : "0" ) + ( _1 ? "1" : "0" ); } } public struct FourBitAdderOutput { public Nibble N { get; set; } public bool C { get; set; } public override string ToString ( ) { return N.ToString ( ) + "c" + ( C ? "1" : "0" ); } } public static class LogicGates { // Basic Gates public static bool Not ( bool A ) { return !A; } public static bool And ( bool A, bool B ) { return A && B; } public static bool Or ( bool A, bool B ) { return A || B; } // Composite Gates public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); } } public static class ConstructiveBlocks { public static BitAdderOutput HalfAdder ( bool A, bool B ) { return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) }; } public static BitAdderOutput FullAdder ( bool A, bool B, bool CI ) { BitAdderOutput HA1 = HalfAdder ( CI, A ); BitAdderOutput HA2 = HalfAdder ( HA1.S, B ); return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) }; } public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI ) { BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI ); BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C ); BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C ); BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C ); return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C }; } public static void Test ( ) { Console.WriteLine ( "Four Bit Adder" ); for ( int i = 0; i < 256; i++ ) { Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; if ( (i & 1) == 1) { A._1 = true; } if ( ( i & 2 ) == 2 ) { A._2 = true; } if ( ( i & 4 ) == 4 ) { A._3 = true; } if ( ( i & 8 ) == 8 ) { A._4 = true; } if ( ( i & 16 ) == 16 ) { B._1 = true; } if ( ( i & 32 ) == 32) { B._2 = true; } if ( ( i & 64 ) == 64 ) { B._3 = true; } if ( ( i & 128 ) == 128 ) { B._4 = true; } Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) ); } Console.WriteLine ( ); } } }
Function prototype
C sharp|C#
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. ;Task: Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: * An explanation of any placement restrictions for prototype declarations * A prototype declaration for a function that does not require arguments * A prototype declaration for a function that requires two arguments * A prototype declaration for a function that utilizes varargs * A prototype declaration for a function that utilizes optional arguments * A prototype declaration for a function that utilizes named parameters * Example of prototype declarations for subroutines or procedures (if these differ from functions) * An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
using System; public delegate int IntFunction(int a, int b); public class Program { public static int Add(int x, int y) { return x + y; } public static int Multiply(int x, int y) { return x * y; } public static void Main() { IntFunction func = Add; Console.WriteLine(func(2, 3)); //prints 5 func = Multiply; Console.WriteLine(func(2, 3)); //prints 6 func += Add; Console.WriteLine(func(2, 3)); //prints 5. Both functions are called, but only the last result is kept. } }
Fusc sequence
C sharp|C#
Definitions: The '''fusc''' integer sequence is defined as: ::* fusc(0) = 0 ::* fusc(1) = 1 ::* for '''n'''>1, the '''n'''th term is defined as: ::::* if '''n''' is even; fusc(n) = fusc(n/2) ::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above). ;An observation: :::::* fusc(A) = fusc(B) where '''A''' is some non-negative integer expressed in binary, and where '''B''' is the binary value of '''A''' reversed. Fusc numbers are also known as: ::* fusc function (named by Dijkstra, 1982) ::* Stern's Diatomic series (although it starts with unity, not zero) ::* Stern-Brocot sequence (although it starts with unity, not zero) ;Task: ::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format. ::* show the fusc number (and its index) whose length is greater than any previous fusc number length. ::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.) ::* show all numbers with commas (if appropriate). ::* show all output here. ;Related task: ::* RosettaCode Stern-Brocot sequence ;Also see: ::* the MathWorld entry: Stern's Diatomic Series. ::* the OEIS entry: A2487.
using System; using System.Collections.Generic; static class program { static int n = 61; static List<int> l = new List<int>() { 0, 1 }; static int fusc(int n) { if (n < l.Count) return l[n]; int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1]; l.Add(f); return f; } static void Main(string[] args) { bool lst = true; int w = -1, c = 0, t; string fs = "{0,11:n0} {1,-9:n0}", res = ""; Console.WriteLine("First {0} numbers in the fusc sequence:", n); for (int i = 0; i < int.MaxValue; i++) { int f = fusc(i); if (lst) { if (i < 61) Console.Write("{0} ", f); else { lst = false; Console.WriteLine(); Console.WriteLine("Points in the sequence where an item has more digits than any previous items:"); Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = ""; } } if ((t = f.ToString().Length) > w) { w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f); if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break; } } l.Clear(); } }
Gapful numbers
C#
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''187''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''187'''. About 7.46% of positive integers are ''gapful''. ;Task: :* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page :* Show the first '''30''' gapful numbers :* Show the first '''15''' gapful numbers >= '''1,000,000''' :* Show the first '''10''' gapful numbers >= '''1,000,000,000''' ;Related tasks: :* Harshad or Niven series. :* palindromic gapful numbers. :* largest number divisible by its digits. ;Also see: :* The OEIS entry: A108343 gapful numbers. :* numbersaplenty gapful numbers
using System; namespace GapfulNumbers { class Program { static void Main(string[] args) { Console.WriteLine("The first 30 gapful numbers are: "); /* Starting at 100, find 30 gapful numbers */ FindGap(100, 30); Console.WriteLine("The first 15 gapful numbers > 1,000,000 are: "); FindGap(1000000, 15); Console.WriteLine("The first 10 gapful numbers > 1,000,000,000 are: "); FindGap(1000000000, 10); Console.Read(); } public static int firstNum(int n) { /*Divide by ten until the leading digit remains.*/ while (n >= 10) { n /= 10; } return (n); } public static int lastNum(int n) { /*Modulo gives you the last digit. */ return (n % 10); } static void FindGap(int n, int gaps) { int count = 0; while (count < gaps) { /* We have to convert our first and last digits to strings to concatenate.*/ string concat = firstNum(n).ToString() + lastNum(n).ToString(); /* And then convert our concatenated string back to an integer. */ int i = Convert.ToInt32(concat); /* Modulo with our new integer and output the result. */ if (n % i == 0) { Console.Write(n + " "); count++; n++; } else { n++; continue; } } } } }
Gauss-Jordan matrix inversion
C sharp|C#
Invert matrix '''A''' using Gauss-Jordan method. '''A''' being an '''n''' x '''n''' matrix.
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b = (double[])initArray.Clone(); rows = b.Length; } internal Vector Clone() { Vector v = new Vector(b); return v; } internal double this[int row] { get { return b[row]; } set { b[row] = value; } } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; double tmp = b[r1]; b[r1] = b[r2]; b[r2] = tmp; } internal double norm(double[] weights) { double sum = 0; for (int i = 0; i < rows; i++) { double d = b[i] * weights[i]; sum += d*d; } return Math.Sqrt(sum); } internal void print() { for (int i = 0; i < rows; i++) Console.WriteLine(b[i]); Console.WriteLine(); } public static Vector operator-(Vector lhs, Vector rhs) { Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) v[i] = lhs[i] - rhs[i]; return v; } } class Matrix { private double[] b; internal readonly int rows, cols; internal Matrix(int rows, int cols) { this.rows = rows; this.cols = cols; b = new double[rows * cols]; } internal Matrix(int size) { this.rows = size; this.cols = size; b = new double[rows * cols]; for (int i = 0; i < size; i++) this[i, i] = 1; } internal Matrix(int rows, int cols, double[] initArray) { this.rows = rows; this.cols = cols; b = (double[])initArray.Clone(); if (b.Length != rows * cols) throw new Exception("bad init array"); } internal double this[int row, int col] { get { return b[row * cols + col]; } set { b[row * cols + col] = value; } } public static Vector operator*(Matrix lhs, Vector rhs) { if (lhs.cols != rhs.rows) throw new Exception("I can't multiply matrix by vector"); Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) { double sum = 0; for (int j = 0; j < rhs.rows; j++) sum += lhs[i,j]*rhs[j]; v[i] = sum; } return v; } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; int firstR1 = r1 * cols; int firstR2 = r2 * cols; for (int i = 0; i < cols; i++) { double tmp = b[firstR1 + i]; b[firstR1 + i] = b[firstR2 + i]; b[firstR2 + i] = tmp; } } //with partial pivot internal bool InvPartial() { const double Eps = 1e-12; if (rows != cols) throw new Exception("rows != cols for Inv"); Matrix M = new Matrix(rows); //unitary for (int diag = 0; diag < rows; diag++) { int max_row = diag; double max_val = Math.Abs(this[diag, diag]); double d; for (int row = diag + 1; row < rows; row++) if ((d = Math.Abs(this[row, diag])) > max_val) { max_row = row; max_val = d; } if (max_val <= Eps) return false; SwapRows(diag, max_row); M.SwapRows(diag, max_row); double invd = 1 / this[diag, diag]; for (int col = diag; col < cols; col++) { this[diag, col] *= invd; } for (int col = 0; col < cols; col++) { M[diag, col] *= invd; } for (int row = 0; row < rows; row++) { d = this[row, diag]; if (row != diag) { for (int col = diag; col < this.cols; col++) { this[row, col] -= d * this[diag, col]; } for (int col = 0; col < this.cols; col++) { M[row, col] -= d * M[diag, col]; } } } } b = M.b; return true; } internal void print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) Console.Write(this[i,j].ToString()+" "); Console.WriteLine(); } } } }
Gaussian elimination
C sharp|C#
Solve '''Ax=b''' using Gaussian elimination then backwards substitution. '''A''' being an '''n''' by '''n''' matrix. Also, '''x''' and '''b''' are '''n''' by '''1''' vectors. To improve accuracy, please use partial pivoting and scaling. ;See also: :* the Wikipedia entry: Gaussian elimination
using System; namespace Rosetta { internal class Vector { private double[] b; internal readonly int rows; internal Vector(int rows) { this.rows = rows; b = new double[rows]; } internal Vector(double[] initArray) { b = (double[])initArray.Clone(); rows = b.Length; } internal Vector Clone() { Vector v = new Vector(b); return v; } internal double this[int row] { get { return b[row]; } set { b[row] = value; } } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; double tmp = b[r1]; b[r1] = b[r2]; b[r2] = tmp; } internal double norm(double[] weights) { double sum = 0; for (int i = 0; i < rows; i++) { double d = b[i] * weights[i]; sum += d*d; } return Math.Sqrt(sum); } internal void print() { for (int i = 0; i < rows; i++) Console.WriteLine(b[i]); Console.WriteLine(); } public static Vector operator-(Vector lhs, Vector rhs) { Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) v[i] = lhs[i] - rhs[i]; return v; } } class Matrix { private double[] b; internal readonly int rows, cols; internal Matrix(int rows, int cols) { this.rows = rows; this.cols = cols; b = new double[rows * cols]; } internal Matrix(int size) { this.rows = size; this.cols = size; b = new double[rows * cols]; for (int i = 0; i < size; i++) this[i, i] = 1; } internal Matrix(int rows, int cols, double[] initArray) { this.rows = rows; this.cols = cols; b = (double[])initArray.Clone(); if (b.Length != rows * cols) throw new Exception("bad init array"); } internal double this[int row, int col] { get { return b[row * cols + col]; } set { b[row * cols + col] = value; } } public static Vector operator*(Matrix lhs, Vector rhs) { if (lhs.cols != rhs.rows) throw new Exception("I can't multiply matrix by vector"); Vector v = new Vector(lhs.rows); for (int i = 0; i < lhs.rows; i++) { double sum = 0; for (int j = 0; j < rhs.rows; j++) sum += lhs[i,j]*rhs[j]; v[i] = sum; } return v; } internal void SwapRows(int r1, int r2) { if (r1 == r2) return; int firstR1 = r1 * cols; int firstR2 = r2 * cols; for (int i = 0; i < cols; i++) { double tmp = b[firstR1 + i]; b[firstR1 + i] = b[firstR2 + i]; b[firstR2 + i] = tmp; } } //with partial pivot internal void ElimPartial(Vector B) { for (int diag = 0; diag < rows; diag++) { int max_row = diag; double max_val = Math.Abs(this[diag, diag]); double d; for (int row = diag + 1; row < rows; row++) if ((d = Math.Abs(this[row, diag])) > max_val) { max_row = row; max_val = d; } SwapRows(diag, max_row); B.SwapRows(diag, max_row); double invd = 1 / this[diag, diag]; for (int col = diag; col < cols; col++) this[diag, col] *= invd; B[diag] *= invd; for (int row = 0; row < rows; row++) { d = this[row, diag]; if (row != diag) { for (int col = diag; col < cols; col++) this[row, col] -= d * this[diag, col]; B[row] -= d * B[diag]; } } } } internal void print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) Console.Write(this[i,j].ToString()+" "); Console.WriteLine(); } } } }
Generator/Exponential
C sharp
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
using System; using System.Collections.Generic; using System.Linq; static class Program { static void Main() { Func<int, IEnumerable<int>> ms = m => Infinite().Select(i => (int)Math.Pow(i, m)); var squares = ms(2); var cubes = ms(3); var filtered = squares.Where(square => cubes.First(cube => cube >= square) != square); var final = filtered.Skip(20).Take(10); foreach (var i in final) Console.WriteLine(i); } static IEnumerable<int> Infinite() { var i = 0; while (true) yield return i++; } }
Get system command output
C sharp|C#
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). ;Related task * Execute a system command
using System; namespace GetSystemCommandOutput { class Program { static void Main(string[] args) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/c echo Hello World"; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; process.StartInfo = startInfo; process.Start(); string output = process.StandardOutput.ReadToEnd(); Console.WriteLine("Output is {0}", output); } } }
Globally replace text in several files
C sharp
Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
using System.Collections.Generic; using System.IO; class Program { static void Main() { var files = new List<string> { "test1.txt", "test2.txt" }; foreach (string file in files) { File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!")); } } }
Gray code
C sharp
Karnaugh maps in order from left to right or top to bottom. Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] ;Reference * Converting Between Gray and Binary Codes. It includes step-by-step animations.
using System; public class Gray { public static ulong grayEncode(ulong n) { return n^(n>>1); } public static ulong grayDecode(ulong n) { ulong i=1<<8*64-2; //long is 64-bit ulong p, b=p=n&i; while((i>>=1)>0) b|=p=n&i^p>>1; return b; } public static void Main(string[] args) { Console.WriteLine("Number\tBinary\tGray\tDecoded"); for(ulong i=0;i<32;i++) { Console.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", i, Convert.ToString((long)i, 2), Convert.ToString((long)grayEncode(i), 2), grayDecode(grayEncode(i)))); } } }
Greatest subsequential sum
C sharp|C#
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
using System; namespace Tests_With_Framework_4 { class Program { static void Main(string[] args) { int[] integers = { -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 }; int length = integers.Length; int maxsum, beginmax, endmax, sum; maxsum = beginmax = sum = 0; endmax = -1; for (int i = 0; i < length; i++) { sum = 0; for (int k = i; k < length; k++) { sum += integers[k]; if (sum > maxsum) { maxsum = sum; beginmax = i; endmax = k; } } } for (int i = beginmax; i <= endmax; i++) Console.WriteLine(integers[i]); Console.ReadKey(); } } }
Greedy algorithm for Egyptian fractions
C sharp|C# from Visual Basic .NET
An Egyptian fraction is the sum of distinct unit fractions such as: :::: \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48}) Each fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction \tfrac{x}{y} to be represented by repeatedly performing the replacement :::: \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil} (simplifying the 2nd term in this replacement as necessary, and where \lceil x \rceil is the ''ceiling'' function). For this task, Proper and improper fractions must be able to be expressed. Proper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that a < b, and improper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n'']. ;Task requirements: * show the Egyptian fractions for: \tfrac{43}{48} and \tfrac{5}{121} and \tfrac{2014}{59} * for all proper fractions, \tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has: ::* the largest number of terms, ::* the largest denominator. * for all one-, two-, and three-digit integers, find and show (as above). {extra credit} ;Also see: * Wolfram MathWorld(tm) entry: Egyptian fraction
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace EgyptianFractions { class Program { class Rational : IComparable<Rational>, IComparable<int> { public BigInteger Num { get; } public BigInteger Den { get; } public Rational(BigInteger n, BigInteger d) { var c = Gcd(n, d); Num = n / c; Den = d / c; if (Den < 0) { Num = -Num; Den = -Den; } } public Rational(BigInteger n) { Num = n; Den = 1; } public override string ToString() { if (Den == 1) { return Num.ToString(); } else { return string.Format("{0}/{1}", Num, Den); } } public Rational Add(Rational rhs) { return new Rational(Num * rhs.Den + rhs.Num * Den, Den * rhs.Den); } public Rational Sub(Rational rhs) { return new Rational(Num * rhs.Den - rhs.Num * Den, Den * rhs.Den); } public int CompareTo(Rational rhs) { var ad = Num * rhs.Den; var bc = Den * rhs.Num; return ad.CompareTo(bc); } public int CompareTo(int rhs) { var ad = Num * rhs; var bc = Den * rhs; return ad.CompareTo(bc); } } static BigInteger Gcd(BigInteger a, BigInteger b) { if (b == 0) { if (a < 0) { return -a; } else { return a; } } else { return Gcd(b, a % b); } } static List<Rational> Egyptian(Rational r) { List<Rational> result = new List<Rational>(); if (r.CompareTo(1) >= 0) { if (r.Den == 1) { result.Add(r); result.Add(new Rational(0)); return result; } result.Add(new Rational(r.Num / r.Den)); r = r.Sub(result[0]); } BigInteger modFunc(BigInteger m, BigInteger n) { return ((m % n) + n) % n; } while (r.Num != 1) { var q = (r.Den + r.Num - 1) / r.Num; result.Add(new Rational(1, q)); r = new Rational(modFunc(-r.Den, r.Num), r.Den * q); } result.Add(r); return result; } static string FormatList<T>(IEnumerable<T> col) { StringBuilder sb = new StringBuilder(); var iter = col.GetEnumerator(); sb.Append('['); if (iter.MoveNext()) { sb.Append(iter.Current); } while (iter.MoveNext()) { sb.AppendFormat(", {0}", iter.Current); } sb.Append(']'); return sb.ToString(); } static void Main() { List<Rational> rs = new List<Rational> { new Rational(43, 48), new Rational(5, 121), new Rational(2014, 59) }; foreach (var r in rs) { Console.WriteLine("{0} => {1}", r, FormatList(Egyptian(r))); } var lenMax = Tuple.Create(0UL, new Rational(0)); var denomMax = Tuple.Create(BigInteger.Zero, new Rational(0)); var query = (from i in Enumerable.Range(1, 100) from j in Enumerable.Range(1, 100) select new Rational(i, j)) .Distinct() .ToList(); foreach (var r in query) { var e = Egyptian(r); ulong eLen = (ulong) e.Count; var eDenom = e.Last().Den; if (eLen > lenMax.Item1) { lenMax = Tuple.Create(eLen, r); } if (eDenom > denomMax.Item1) { denomMax = Tuple.Create(eDenom, r); } } Console.WriteLine("Term max is {0} with {1} terms", lenMax.Item2, lenMax.Item1); var dStr = denomMax.Item1.ToString(); Console.WriteLine("Denominator max is {0} with {1} digits {2}...{3}", denomMax.Item2, dStr.Length, dStr.Substring(0, 5), dStr.Substring(dStr.Length - 5, 5)); } } }
Hailstone sequence
C sharp|C#
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hailstone { class Program { public static List<int> hs(int n,List<int> seq) { List<int> sequence = seq; sequence.Add(n); if (n == 1) { return sequence; }else{ int newn = (n % 2 == 0) ? n / 2 : (3 * n) + 1; return hs(newn, sequence); } } static void Main(string[] args) { int n = 27; List<int> sequence = hs(n,new List<int>()); Console.WriteLine(sequence.Count + " Elements"); List<int> start = sequence.GetRange(0, 4); List<int> end = sequence.GetRange(sequence.Count - 4, 4); Console.WriteLine("Starting with : " + string.Join(",", start) + " and ending with : " + string.Join(",", end)); int number = 0, longest = 0; for (int i = 1; i < 100000; i++) { int count = (hs(i, new List<int>())).Count; if (count > longest) { longest = count; number = i; } } Console.WriteLine("Number < 100000 with longest Hailstone seq.: " + number + " with length of " + longest); } } }
Harshad or Niven series
C sharp|C#
The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder. Assume that the series is defined as the numbers in increasing order. ;Task: The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: ::* list the first '''20''' members of the sequence, and ::* list the first Harshad number greater than '''1000'''. Show your output here. ;Related task :* Increasing gaps between consecutive Niven numbers ;See also * OEIS: A005349
using System; using System.Collections.Generic; namespace Harshad { class Program { public static bool IsHarshad(int n) { char[] inputChars = n.ToString().ToCharArray(); IList<byte> digits = new List<byte>(); foreach (char digit in inputChars) { digits.Add((byte)Char.GetNumericValue(digit)); } if (n < 1) { return false; } int sum = 0; foreach (byte digit in digits) { sum += digit; } return n % sum == 0; } static void Main(string[] args) { int i = 1; int count = 0; while (true) { if (IsHarshad(i)) { count++; if (count <= 20) { Console.Write(string.Format("{0} ", i)); } else if (i > 1000) { Console.Write(string.Format("{0} ", i)); break; } } i++; } Console.ReadKey(); } } }
Hash join
C sharp
{| class="wikitable" |- ! Input ! Output |- | {| style="border:none; border-collapse:collapse;" |- | style="border:none" | ''A'' = | style="border:none" | {| class="wikitable" |- ! Age !! Name |- | 27 || Jonah |- | 18 || Alan |- | 28 || Glory |- | 18 || Popeye |- | 28 || Alan |} | style="border:none; padding-left:1.5em;" rowspan="2" | | style="border:none" | ''B'' = | style="border:none" | {| class="wikitable" |- ! Character !! Nemesis |- | Jonah || Whales |- | Jonah || Spiders |- | Alan || Ghosts |- | Alan || Zombies |- | Glory || Buffy |} |- | style="border:none" | ''jA'' = | style="border:none" | Name (i.e. column 1) | style="border:none" | ''jB'' = | style="border:none" | Character (i.e. column 0) |} | {| class="wikitable" style="margin-left:1em" |- ! A.Age !! A.Name !! B.Character !! B.Nemesis |- | 27 || Jonah || Jonah || Whales |- | 27 || Jonah || Jonah || Spiders |- | 18 || Alan || Alan || Ghosts |- | 18 || Alan || Alan || Zombies |- | 28 || Glory || Glory || Buffy |- | 28 || Alan || Alan || Ghosts |- | 28 || Alan || Alan || Zombies |} |} The order of the rows in the output table is not significant. If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; private set; } } public class NameNemesis { public NameNemesis(string name, string nemesis) { Name = name; Nemesis = nemesis; } public string Name { get; private set; } public string Nemesis { get; private set; } } public class DataContext { public DataContext() { AgeName = new List<AgeName>(); NameNemesis = new List<NameNemesis>(); } public List<AgeName> AgeName { get; set; } public List<NameNemesis> NameNemesis { get; set; } } public class AgeNameNemesis { public AgeNameNemesis(byte age, string name, string nemesis) { Age = age; Name = name; Nemesis = nemesis; } public byte Age { get; private set; } public string Name { get; private set; } public string Nemesis { get; private set; } } class Program { public static void Main() { var data = GetData(); var result = ExecuteHashJoin(data); WriteResultToConsole(result); } private static void WriteResultToConsole(List<AgeNameNemesis> result) { result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); } private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data) { return (data.AgeName.Join(data.NameNemesis, ageName => ageName.Name, nameNemesis => nameNemesis.Name, (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) .ToList(); } private static DataContext GetData() { var context = new DataContext(); context.AgeName.AddRange(new [] { new AgeName(27, "Jonah"), new AgeName(18, "Alan"), new AgeName(28, "Glory"), new AgeName(18, "Popeye"), new AgeName(28, "Alan") }); context.NameNemesis.AddRange(new[] { new NameNemesis("Jonah", "Whales"), new NameNemesis("Jonah", "Spiders"), new NameNemesis("Alan", "Ghosts"), new NameNemesis("Alan", "Zombies"), new NameNemesis("Glory", "Buffy") }); return context; } } }
Haversine formula
c sharp|C# from Groovy
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
public static class Haversine { public static double calculate(double lat1, double lon1, double lat2, double lon2) { var R = 6372.8; // In kilometers var dLat = toRadians(lat2 - lat1); var dLon = toRadians(lon2 - lon1); lat1 = toRadians(lat1); lat2 = toRadians(lat2); var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2); var c = 2 * Math.Asin(Math.Sqrt(a)); return R * 2 * Math.Asin(Math.Sqrt(a)); } public static double toRadians(double angle) { return Math.PI * angle / 180.0; } } void Main() { Console.WriteLine(String.Format("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12, -86.67, 33.94, -118.40, Haversine.calculate(36.12, -86.67, 33.94, -118.40))); } // Returns: The distance between coordinates 36.12,-86.67 and 33.94,-118.4 is: 2887.25995060711
Hello world/Line printer
C sharp
Cause a line printer attached to the computer to print a line containing the message: Hello World! ;Note: A line printer is not the same as standard output. A line printer was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class DOCINFOA { [MarshalAs(UnmanagedType.LPStr)] public string pDocName; [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile; [MarshalAs(UnmanagedType.LPStr)] public string pDataType; } [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd); [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di); [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern bool StartPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern bool EndPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern bool EndDocPrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern bool ClosePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "WritePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten); public void HelloWorld() { IntPtr hPrinter; bool openSuccessful = OpenPrinter("My Printer", out hPrinter, IntPtr.Zero); if (openSuccessful) { DOCINFOA docInfo = new DOCINFOA(); docInfo.pDocName = "Hello World Example"; docInfo.pOutputFile = null; docInfo.pDataType = "RAW"; if (StartDocPrinter(hPrinter, 1, docInfo)) { StartPagePrinter(hPrinter); const string helloWorld = "Hello World!"; IntPtr buf = Marshal.StringToCoTaskMemAnsi(helloWorld); int bytesWritten; WritePrinter(hPrinter, buf, helloWorld.Length, out bytesWritten); Marshal.FreeCoTaskMem(buf); } if (EndPagePrinter(hPrinter)) if (EndDocPrinter(hPrinter)) ClosePrinter(hPrinter); } }
Hello world/Newbie
C sharp|C#
Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the [[Hello world/Text]] task. * Assume the language-newbie is a programmer in another language. * Assume the language-newbie is competent in installing software for the platform. * Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor). * Refer to, (and link to), already existing documentation as much as possible (but provide a summary here). * Remember to state where to view the output. * If particular IDE's or editors are required that are not standard, then point to/explain their installation too. ;Note: * If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated. * You may use sub-headings if giving instructions for multiple platforms.
C# is an ECMA-standardized language with open-source implementations, though development of the language is dominated by Microsoft. C# compilers and IDEs are available on most operating systems. ===C# on Windows=== Download the [https://www.visualstudio.com/vs/community/ Visual Studio Community Edition], which is free for personal use. This is a standard Windows click-through installer. Once installed (and after a restart), open Visual Studio. Click on "New Project..." or do File > New > Project. Select "Console Application." Make sure Visual C# / Windows is selected in the left pane (because Visual Studio handles multiple languages and platforms). Type a name for your application in the "Name" field. Click OK. Enter the Hello World code from the Hello World task into Program.cs. Press the "Start" button or hit F5 to compile and run. ===C# on iOS=== The [http://continuous.codes/ Continuous] App allows one to write, compile, and run C# code on an iOS device (iPad Pro recommended). ===C# on Linux=== ====Mono==== Mono is the oldest effort to bring C# to Linux. Install the mono-complete package. Installation instructions are [http://www.mono-project.com/docs/getting-started/install/linux/ here]. Use the text editor or IDE of your choice to enter the Hello World program, saving it as Hello.cs. To compile: $ mcs hello.cs To run: $ ./hello.exe ====.NET Core==== .NET Core is Microsoft's open-source implementation of C# and also part of the .NET libraries. Microsoft's [https://www.microsoft.com/net/core#linuxredhat installation instructions for Linux] walk through installing .NET Core on a Linux system and also compiling and running a simple "Hello, World!" console application. It does not come with an IDE, but consider [https://code.visualstudio.com/ Visual Studio Code.] ===C# on macOS=== ====Xamarin Studio==== Xamarin Studio is an IDE combined with Mono as well as cross-platform development tools. [https://developer.xamarin.com/guides/cross-platform/xamarin-studio/ Installation instructions are here.] ====.NET Core==== .NET Core is Microsoft's open-source implementation of C# and also part of the .NET libraries. Microsoft's [https://www.microsoft.com/net/core#macos installation instructions for macOS] walk through installing .NET Core on macOS and also compiling and running a simple "Hello, World!" console application. It does not come with an IDE, but consider [https://code.visualstudio.com/ Visual Studio Code.]
Here document
C sharp
A ''here document'' (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a ''here document'' is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block. ;Task: Demonstrate the use of ''here documents'' within the language. ;Related task: * [[Documentation]]
using System; class Program { static void Main(string[] args) { Console.Write(@" multiline strings are easy to put together in C#"); } }
Heronian triangles
C sharp|C#
Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by: :::: A = \sqrt{s(s-a)(s-b)(s-c)}, where ''s'' is half the perimeter of the triangle; that is, :::: s=\frac{a+b+c}{2}. '''Heronian triangles''' are triangles whose sides ''and area'' are all integers. : An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle. Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor of all three sides is '''1''' (unity). This will exclude, for example, triangle '''6, 8, 10.''' ;Task: # Create a named function/method/procedure/... that implements Hero's formula. # Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. # Show the count of how many triangles are found. # Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths # Show the first ten ordered triangles in a table of sides, perimeter, and area. # Show a similar ordered table for those triangles with area = 210 Show all output here. '''Note''': when generating triangles it may help to restrict a <= b <= c
using System; using System.Collections.Generic; namespace heron { class Program{ static void Main(string[] args){ List<int[]> list = new List<int[]>(); for (int c = 1; c <= 200; c++) for (int b = 1; b <= c; b++) for (int a = 1; a <= b; a++) if (gcd(a, gcd(b, c)) == 1 && isHeron(heronArea(a, b, c))) list.Add(new int[] { a, b, c, a + b + c, (int)heronArea(a, b, c)}); sort(list); Console.WriteLine("Number of primitive Heronian triangles with sides up to 200: " + list.Count + "\n\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:\nSides\t\t\tPerimeter\tArea"); for(int i = 0; i < 10; i++) Console.WriteLine(list[i][0] + "\t" + list[i][1] + "\t" + list[i][2] + "\t" + list[i][3] + "\t\t" + list[i][4]); Console.WriteLine("\nPerimeter = 210\nSides\t\t\tPerimeter\tArea"); foreach (int[] i in list) if (i[4] == 210) Console.WriteLine(i[0] + "\t" + i[1] + "\t" + i[2] + "\t" + i[3] + "\t\t" + i[4]); } static bool isHeron(double heronArea){ return heronArea % 1 == 0 && heronArea != 0; } static double heronArea(int a, int b, int c){ double s = (a + b + c) / 2d; return Math.Sqrt(s * (s - a) * (s - b) * (s - c)); } static int gcd(int a, int b){ int remainder = 1, dividend, divisor; dividend = a > b ? a : b; divisor = a > b ? b : a; while (remainder != 0){ remainder = dividend % divisor; if (remainder != 0){ dividend = divisor; divisor = remainder; } } return divisor; } static void sort(List<int[]> list){ int[] temp = new int[5]; bool changed = true; while(changed){ changed = false; for (int i = 1; i < list.Count; i++) if (list[i][4] < list[i - 1][4] || list[i][4] == list[i - 1][4] && list[i][3] < list[i - 1][3]){ temp = list[i]; list[i] = list[i - 1]; list[i - 1] = temp; changed = true; } } } } }
History variables
C sharp
''Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.'' ''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables. '' "History Variables: The Semantics, Formal Correctness, and Implementation of History Variables in an Imperative Programming Language" by Mallon and Takaoka Concept also discussed on LtU and Patents.com. ;Task: Demonstrate History variable support: * enable history variable support (if needed) * define a history variable * assign three values * non-destructively display the history * recall the three values. For extra points, if the language of choice does not support history variables, demonstrate how this might be implemented.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace History { class Program { static void Main(string[] args) { var h = new HistoryObject(); h.Value = 5; h.Value = "foo"; h.Value += "bar"; var history = h.ToArray(); for (int i = 0; i < history.Length; i++) { Console.Write("{0}{1}", history[i], ((i >= history.Length - 1) ? "\n" : " <- ")); } h.Undo(); h.Undo(); h.Undo(); Console.WriteLine(h.Value); } private class HistoryObject : IEnumerable<object> { public HistoryObject() { _history = new Stack<object>(); // Initiates the history stack. } public object Value { get // Returns the top value from the history if there is one. Otherwise null. { if (_history.Count > 0) return _history.Peek(); return null; } set { _history.Push(value); } // Adds the specified value to the history. } public void Undo() { if (_history.Count > 0) _history.Pop(); // Removes the current value from the history. } // History stack that will hold all previous values of the object. private readonly Stack<object> _history; public IEnumerator<object> GetEnumerator() { return _history.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
Hofstadter-Conway $10,000 sequence
C# 3.0
The definition of the sequence is colloquially described as: * Starting with the list [1,1], * Take the last number in the list so far: 1, I'll call it x. * Count forward x places from the beginning of the list to find the first number to add (1) * Count backward x places from the end of the list to find the second number to add (1) * Add the two indexed numbers from the list and the result becomes the next number in the list (1+1) * This would then produce [1,1,2] where 2 is the third element of the sequence. Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''. A less wordy description of the sequence is: a(1)=a(2)=1 a(n)=a(a(n-1))+a(n-a(n-1)) The sequence begins: 1, 1, 2, 2, 3, 4, 4, 4, 5, ... Interesting features of the sequence are that: * a(n)/n tends to 0.5 as n grows towards infinity. * a(n)/n where n is a power of 2 is 0.5 * For n>4 the maximal value of a(n)/n between successive powers of 2 decreases. a(n) / n for n in 1..256 The sequence is so named because John Conway offered a prize of $10,000 to the first person who could find the first position, p in the sequence where |a(n)/n| < 0.55 for all n > p It was later found that Hofstadter had also done prior work on the sequence. The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article). ;Task: # Create a routine to generate members of the Hofstadter-Conway $10,000 sequence. # Use it to show the maxima of a(n)/n between successive powers of two up to 2**20 # As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20 ;Also see: * Conways Challenge Sequence, Mallows' own account. * Mathworld Article.
using System; using System.Linq; namespace HofstadterConway { class Program { static int[] GenHofstadterConway(int max) { int[] result = new int[max]; result[0]=result[1]=1; for (int ix = 2; ix < max; ix++) result[ix] = result[result[ix - 1] - 1] + result[ix - result[ix - 1]]; return result; } static void Main(string[] args) { double[] adiv = new double[1 << 20]; { int[] a = GenHofstadterConway(1 << 20); for (int i = 0; i < 1 << 20; i++) adiv[i] = a[i] / (double)(i + 1); } for (int p = 2; p <= 20; p++) { var max = Enumerable.Range( (1 << (p - 1)) - 1, (1 << p) - (1 << (p - 1)) ) .Select(ix => new { I = ix + 1, A = adiv[ix] }) .OrderByDescending(x => x.A) .First(); Console.WriteLine("Maximum from 2^{0} to 2^{1} is {2} at {3}", p - 1, p, max.A, max.I); } Console.WriteLine("The winning number is {0}.", Enumerable.Range(0, 1 << 20) .Last(i => (adiv[i] > 0.55)) + 1 ); } } }
Hofstadter Figure-Figure sequences
C sharp|C#
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; // Take care of first two cases specially since S won't be larger than R at that point switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Hofstadter Q sequence
C sharp
The Hofstadter Q sequence is defined as: :: \begin{align} Q(1)&=Q(2)=1, \\ Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2. \end{align} It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence. ;Task: * Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 * Confirm and display that the 1000th term is: 502 ;Optional extra credit * Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term. * Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large. (This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
using System; using System.Collections.Generic; namespace HofstadterQSequence { class Program { // Initialize the dictionary with the first two indices filled. private static readonly Dictionary<int, int> QList = new Dictionary<int, int> { {1, 1}, {2, 1} }; private static void Main() { int lessThanLast = 0; /* Initialize our variable that holds the number of times * a member of the sequence was less than its preceding term. */ for (int n = 1; n <= 100000; n++) { int q = Q(n); // Get Q(n). if (n > 1 && QList[n - 1] > q) // If Q(n) is less than Q(n - 1), lessThanLast++; // then add to the counter. if (n > 10 && n != 1000) continue; /* If n is greater than 10 and not 1000, * the rest of the code in the loop does not apply, * and it will be skipped. */ if (!Confirm(n, q)) // Confirm Q(n) is correct. throw new Exception(string.Format("Invalid result: Q({0}) != {1}", n, q)); Console.WriteLine("Q({0}) = {1}", n, q); // Write Q(n) to the console. } Console.WriteLine("Number of times a member of the sequence was less than its preceding term: {0}.", lessThanLast); } private static bool Confirm(int n, int value) { if (n <= 10) return new[] {1, 1, 2, 3, 3, 4, 5, 5, 6, 6}[n - 1] == value; if (n == 1000) return 502 == value; throw new ArgumentException("Invalid index.", "n"); } private static int Q(int n) { int q; if (!QList.TryGetValue(n, out q)) // Try to get Q(n) from the dictionary. { q = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); // If it's not available, then calculate it. QList.Add(n, q); // Add it to the dictionary. } return q; } } }
Honeycombs
C sharp
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position within the arrangement. Each hexagon should be the same colour, and should display a unique randomly selected single capital letter on the front. The application should now wait for the user to select a hexagon, either by using a pointing device, or by pressing a key that carries a corresponding letter on a hexagon. For platforms that support pointing devices and keyboards, the application should support both methods of selection. A record of the chosen letters should be maintained and the code should be suitably commented, at the point where the the selected letter has been determined. The selected hexagon should now change colour on the display. The cycle repeats until the user has chosen all of the letters. Note that each letter can only be selected once and previously selected hexagons retain their colour after selection. The program terminates when all letters have been chosen. Optionally: output the list of selected letters and show the last selected letter, cater for a different number of columns or a different number of hexagons in each column, cater for two players, (turns alternate and the hexagons change a different colour depending on whether they were selected by player one or player two and records of both players selections are maintained.) [[image:honeycomb.gif]]
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; //////////////////////////////////////////////////////////////////////////////////////////////////// // namespace: Honeycombs // // summary: WPF implementation of Rosetta Code Honeycombs task. Uses Polygon shapes as hexes. //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Honeycombs { public partial class MainWindow { private const int RowCount = 4; private const int ColCount = 5; private const int LabelSize = 20; private readonly char[] _permutedChars; public MainWindow() { if (RowCount * ColCount > 26) #pragma warning disable 162 { throw new ArgumentException("Too many cells"); } #pragma warning restore 162 _permutedChars = GetPermutedChars(RowCount * ColCount); // VS Generated code not included InitializeComponent(); } private static char[] GetPermutedChars(int characterCount) { const string allChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var rnd = new Random(); var chars = new char[allChars.Length]; for (int i = 0; i < allChars.Length; i++) { chars[i] = allChars[i]; } for (int i = 0; i < characterCount; i++) { int swapIndex = rnd.Next() % (allChars.Length - i); char tmp = chars[swapIndex + i]; chars[swapIndex + i] = chars[i]; chars[i] = tmp; } return chars; } private void SetHexProperties(UIElementCollection hexes, double cellSize) { int charIndex = 0; List<Polygon> hexList = hexes.Cast<Polygon>().ToList(); foreach (Polygon element in hexList) { SetHexProperties(element, _permutedChars[charIndex++], cellSize); } } private void SetHexProperties(Polygon hex, char charToSet, double cellSize) { var tag = (Tuple<int, int, double, double>) hex.Tag; double cellX = tag.Item3; double cellY = tag.Item4; // We place the text in a grid centered on the hex. // The grid will then center the text within itself. var centeringGrid = new Grid(); centeringGrid.Width = centeringGrid.Height = 2 * cellSize; centeringGrid.SetValue(Canvas.LeftProperty, cellX - cellSize); centeringGrid.SetValue(Canvas.TopProperty, cellY - cellSize); centeringGrid.IsHitTestVisible = false; HoneycombCanvas.Children.Add(centeringGrid); var label = new TextBlock { Text = new string(charToSet, 1), FontFamily = new FontFamily("Segoe"), FontSize = LabelSize }; label.HorizontalAlignment = HorizontalAlignment.Center; label.VerticalAlignment = VerticalAlignment.Center; label.IsHitTestVisible = false; centeringGrid.Children.Add(label); // Reset the tag to keep track of the character in the hex hex.Tag = charToSet; hex.Fill = new SolidColorBrush(Colors.Yellow); hex.Stroke = new SolidColorBrush(Colors.Black); hex.StrokeThickness = cellSize / 10; // Mouse down event handler for the hex hex.MouseDown += hex_MouseDown; } private void hex_MouseDown(object sender, MouseButtonEventArgs e) { var hex = sender as Shape; if (hex == null) { throw new InvalidCastException("Non-shape in Honeycomb"); } // Get the letter for this hex var ch = (char) hex.Tag; // Add it to our Letters TextBlock Letters.Text = Letters.Text + ch; // Color the hex magenta hex.Fill = new SolidColorBrush(Colors.Magenta); // Remove the mouse down event handler so we won't hit on this hex again hex.MouseDown -= hex_MouseDown; } private static void GetCombSize(double actualHeight, double actualWidth, int columns, int rows, out double cellSize, out double combHeight, out double combWidth) { double columnFactor = (3 * columns + 1) / 2.0; double rowFactor = (Math.Sqrt(3) * (2 * rows + 1)) / 2.0; double cellFromWidth = actualWidth / columnFactor; double cellFromHeight = actualHeight / rowFactor; cellSize = Math.Min(cellFromWidth, cellFromHeight); combWidth = cellSize * columnFactor; combHeight = cellSize * rowFactor; } private static void AddCells(Canvas canvas, double cellSize, int columns, int rows) { double rowHeight = cellSize * Math.Sqrt(3) / 2; for (int row = 0; row < rows; row++) { AddRow(rowHeight, canvas, cellSize, columns, row); rowHeight += cellSize * Math.Sqrt(3); } } private static void AddRow(double rowHeight, Canvas canvas, double cellSize, int columnCount, int row) { double cellX = cellSize; double cellHeight = cellSize * Math.Sqrt(3); for (int col = 0; col < columnCount; col++) { double cellY = rowHeight + ((col & 1) == 1 ? cellHeight / 2 : 0); Polygon hex = GetCenteredHex(cellSize, cellX, cellY, cellHeight); hex.Tag = Tuple.Create(col, row, cellX, cellY); canvas.Children.Add(hex); cellX += 3 * cellSize / 2; } } private static Polygon GetCenteredHex(double cellSize, double cellX, double cellY, double cellHeight) { var hex = new Polygon(); hex.Points.Add(new Point(cellX - cellSize, cellY)); hex.Points.Add(new Point(cellX - cellSize / 2, cellY + cellHeight / 2)); hex.Points.Add(new Point(cellX + cellSize / 2, cellY + cellHeight / 2)); hex.Points.Add(new Point(cellX + cellSize, cellY)); hex.Points.Add(new Point(cellX + cellSize / 2, cellY - cellHeight / 2)); hex.Points.Add(new Point(cellX - cellSize / 2, cellY - cellHeight / 2)); return hex; } private void Window_Loaded(object sender, RoutedEventArgs e) { double combHeight, combWidth, cellSize; // Get sizes that will fit within our window GetCombSize(Main.ActualHeight, Main.ActualWidth, ColCount, RowCount, out cellSize, out combHeight, out combWidth); // Set the canvas size appropriately HoneycombCanvas.Width = combWidth; HoneycombCanvas.Height = combHeight; // Add the cells to the canvas AddCells(HoneycombCanvas, cellSize, ColCount, RowCount); // Set the cells to look like we want them SetHexProperties(HoneycombCanvas.Children, cellSize); } } }
Horner's rule for polynomial evaluation
C sharp|C#
A fast scheme for evaluating a polynomial such as: : -19+7x-4x^2+6x^3\, when : x=3\;. is to arrange the computation as follows: : ((((0) x + 6) x + (-4)) x + 7) x + (-19)\; And compute the result from the innermost brackets outwards as in this pseudocode: coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order'' x ''':=''' 3 accumulator ''':=''' 0 '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do''' ''# Assumes 1-based indexing for arrays'' accumulator ''':=''' ( accumulator * x ) + coefficients[i] '''done''' ''# accumulator now has the answer'' '''Task Description''' :Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule. Cf. [[Formal power series]]
using System; using System.Linq; class Program { static double Horner(double[] coefficients, double variable) { return coefficients.Reverse().Aggregate( (accumulator, coefficient) => accumulator * variable + coefficient); } static void Main() { Console.WriteLine(Horner(new[] { -19.0, 7.0, -4.0, 6.0 }, 3.0)); } }
ISBN13 check digit
C sharp
Validate the check digit of an ISBN-13 code: ::* Multiply every other digit by '''3'''. ::* Add these numbers and the other digits. ::* Take the remainder of this number after division by '''10'''. ::* If it is '''0''', the ISBN-13 check digit is correct. You might use the following codes for testing: ::::* 978-0596528126 (good) ::::* 978-0596528120 (bad) ::::* 978-1788399081 (good) ::::* 978-1788399083 (bad) Show output here, on this page ;See also: :* for details: 13-digit ISBN method of validation. (installs cookies.)
using System; using System.Linq; public class Program { public static void Main() { Console.WriteLine(CheckISBN13("978-1734314502")); Console.WriteLine(CheckISBN13("978-1734314509")); Console.WriteLine(CheckISBN13("978-1788399081")); Console.WriteLine(CheckISBN13("978-1788399083")); static bool CheckISBN13(string code) { code = code.Replace("-", "").Replace(" ", ""); if (code.Length != 13) return false; int sum = 0; foreach (var (index, digit) in code.Select((digit, index) => (index, digit))) { if (char.IsDigit(digit)) sum += (digit - '0') * (index % 2 == 0 ? 1 : 3); else return false; } return sum % 10 == 0; } } }
I before E except after C
C sharp|C# from Java
The phrase "I before E, except after C" is a widely known mnemonic which is supposed to help when spelling English words. ;Task: Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually: :::# ''"I before E when not preceded by C"'' :::# ''"E before I when preceded by C"'' If both sub-phrases are plausible then the original phrase can be said to be plausible. Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate). ;Stretch goal: As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account. ''Show your output here as well as your program.'' ;cf.: * Schools to rethink 'i before e' - BBC news, 20 June 2009 * I Before E Except After C - QI Series 8 Ep 14, (humorous) * Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
using System; using System.Collections.Generic; using System.IO; namespace IBeforeE { class Program { static bool IsOppPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ei")) { return true; } if (word.Contains("cie")) { return true; } return false; } static bool IsPlausibleWord(string word) { if (!word.Contains("c") && word.Contains("ie")) { return true; } if (word.Contains("cei")) { return true; } return false; } static bool IsPlausibleRule(string filename) { IEnumerable<string> wordSource = File.ReadLines(filename); int trueCount = 0; int falseCount = 0; foreach (string word in wordSource) { if (IsPlausibleWord(word)) { trueCount++; } else if (IsOppPlausibleWord(word)) { falseCount++; } } Console.WriteLine("Plausible count: {0}", trueCount); Console.WriteLine("Implausible count: {0}", falseCount); return trueCount > 2 * falseCount; } static void Main(string[] args) { if (IsPlausibleRule("unixdict.txt")) { Console.WriteLine("Rule is plausible."); } else { Console.WriteLine("Rule is not plausible."); } } } }
I before E except after C
.NET Core 2.1
The phrase "I before E, except after C" is a widely known mnemonic which is supposed to help when spelling English words. ;Task: Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually: :::# ''"I before E when not preceded by C"'' :::# ''"E before I when preceded by C"'' If both sub-phrases are plausible then the original phrase can be said to be plausible. Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate). ;Stretch goal: As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account. ''Show your output here as well as your program.'' ;cf.: * Schools to rethink 'i before e' - BBC news, 20 June 2009 * I Before E Except After C - QI Series 8 Ep 14, (humorous) * Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
Option Compare Binary Option Explicit On Option Infer On Option Strict On Imports System.Text.RegularExpressions #Const USE_REGEX = False Module Program ' Supports both local and remote files Const WORDLIST_URI = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ' The support factor of a word for EI or IE is the number of occurrences that support the rule minus the number that oppose it. ' I.e., for IE: ' - increased when not preceded by C ' - decreased when preceded by C ' and for EI: ' - increased when preceded by C ' - decreased when not preceded by C Private Function GetSupportFactor(word As String) As (IE As Integer, EI As Integer) Dim IE, EI As Integer ' Enumerate the letter pairs in the word. For i = 0 To word.Length - 2 Dim pair = word.Substring(i, 2) ' Instances at the beginning of a word count towards the factor and are treated as not preceded by C. Dim prevIsC As Boolean = i > 0 AndAlso String.Equals(word(i - 1), "c"c, StringComparison.OrdinalIgnoreCase) If pair.Equals("ie", StringComparison.OrdinalIgnoreCase) Then IE += If(Not prevIsC, 1, -1) ElseIf pair.Equals("ei", StringComparison.OrdinalIgnoreCase) Then EI += If(prevIsC, 1, -1) End If Next If Math.Abs(IE) > 1 Or Math.Abs(EI) > 1 Then Debug.WriteLine($"{word}: {GetSupportFactor}") Return (IE, EI) End Function ' Returns the number of words that support or oppose the rule. Private Function GetPlausabilities(words As IEnumerable(Of String)) As (ieSuppCount As Integer, ieOppCount As Integer, eiSuppCount As Integer, eiOppCount As Integer) Dim ieSuppCount, ieOppCount, eiSuppCount, eiOppCount As Integer For Each word In words Dim status = GetSupportFactor(word) If status.IE > 0 Then ieSuppCount += 1 ElseIf status.IE < 0 Then ieOppCount += 1 End If If status.EI > 0 Then eiSuppCount += 1 ElseIf status.EI < 0 Then eiOppCount += 1 End If Next Return (ieSuppCount, ieOppCount, eiSuppCount, eiOppCount) End Function ' Takes entire file instead of individual words. ' Returns the number of instances of IE or EI that support or oppose the rule. Private Function GetPlausabilitiesRegex(words As String) As (ieSuppCount As Integer, ieOppCount As Integer, eiSuppCount As Integer, eiOppCount As Integer) ' Gets number of occurrences of the pattern, case-insensitive. Dim count = Function(pattern As String) Regex.Matches(words, pattern, RegexOptions.IgnoreCase).Count Dim ie = count("[^c]ie") Dim ei = count("[^c]ei") Dim cie = count("cie") Dim cei = count("cei") Return (ie, cie, cei, ei) End Function Sub Main() Dim file As String Dim wc As New Net.WebClient() Try Console.WriteLine("Fetching file...") file = wc.DownloadString(WORDLIST_URI) Console.WriteLine("Success.") Console.WriteLine() Catch ex As Net.WebException Console.WriteLine(ex.Message) Exit Sub Finally wc.Dispose() End Try #If USE_REGEX Then Dim res = GetPlausabilitiesRegex(file) #Else Dim words = file.Split({vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries) Dim res = GetPlausabilities(words) #End If Dim PrintResult = Function(suppCount As Integer, oppCount As Integer, printEI As Boolean) As Boolean Dim ratio = suppCount / oppCount, plausible = ratio > 2 #If Not USE_REGEX Then Console.WriteLine($" Words with no instances of {If(printEI, "EI", "IE")} or equal numbers of supporting/opposing occurrences: {words.Length - suppCount - oppCount}") #End If Console.WriteLine($" Number supporting: {suppCount}") Console.WriteLine($" Number opposing: {oppCount}") Console.WriteLine($" {suppCount}/{oppCount}={ratio:N3}") Console.WriteLine($" Rule therefore IS {If(plausible, "", "NOT ")}plausible.") Return plausible End Function #If USE_REGEX Then Console.WriteLine($"Total occurrences of IE: {res.ieOppCount + res.ieSuppCount}") Console.WriteLine($"Total occurrences of EI: {res.eiOppCount + res.eiSuppCount}") #Else Console.WriteLine($"Total words: {words.Length}") #End If Console.WriteLine() Console.WriteLine("""IE is not preceded by C""") Dim iePlausible = PrintResult(res.ieSuppCount, res.ieOppCount, False) Console.WriteLine() Console.WriteLine("""EI is preceded by C""") Dim eiPlausible = PrintResult(res.eiSuppCount, res.eiOppCount, True) Console.WriteLine() Console.WriteLine($"Rule thus overall IS {If(iePlausible AndAlso eiPlausible, "", "NOT ")}plausible.") End Sub End Module
Identity matrix
C sharp
Build an identity matrix of a size known at run-time. An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', where the diagonal elements are all '''1'''s (ones), and all the other elements are all '''0'''s (zeroes). I_n = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ \end{bmatrix} ;Related tasks: * [[Spiral matrix]] * [[Zig-zag matrix]] * [[Ulam_spiral_(for_primes)]]
using System; using System.Linq; namespace IdentityMatrix { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Requires exactly one argument"); return; } int n; if (!int.TryParse(args[0], out n)) { Console.WriteLine("Requires integer parameter"); return; } var identity = Enumerable.Range(0, n).Select(i => Enumerable.Repeat(0, n).Select((z,j) => j == i ? 1 : 0).ToList()).ToList(); foreach (var row in identity) { foreach (var elem in row) { Console.Write(" " + elem); } Console.WriteLine(); } Console.ReadKey(); } } }
Imaginary base numbers
C sharp|C#
Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. ''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]'' Other imaginary bases are possible too but are not as widely discussed and aren't specifically named. '''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. At a minimum, support quater-imaginary (base 2i). For extra kudos, support positive or negative bases 2i through 6i (or higher). As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base. See Wikipedia: Quater-imaginary_base for more details. For reference, here are some some decimal and complex numbers converted to quater-imaginary. Base 10 Base 2i 1 1 2 2 3 3 4 10300 5 10301 6 10302 7 10303 8 10200 9 10201 10 10202 11 10203 12 10100 13 10101 14 10102 15 10103 16 10000 Base 10 Base 2i -1 103 -2 102 -3 101 -4 100 -5 203 -6 202 -7 201 -8 200 -9 303 -10 302 -11 301 -12 300 -13 1030003 -14 1030002 -15 1030001 -16 1030000 Base 10 Base 2i 1i 10.2 2i 10.0 3i 20.2 4i 20.0 5i 30.2 6i 30.0 7i 103000.2 8i 103000.0 9i 103010.2 10i 103010.0 11i 103020.2 12i 103020.0 13i 103030.2 14i 103030.0 15i 102000.2 16i 102000.0 Base 10 Base 2i -1i 0.2 -2i 1030.0 -3i 1030.2 -4i 1020.0 -5i 1020.2 -6i 1010.0 -7i 1010.2 -8i 1000.0 -9i 1000.2 -10i 2030.0 -11i 2030.2 -12i 2020.0 -13i 2020.2 -14i 2010.0 -15i 2010.2 -16i 2000.0
using System; using System.Linq; using System.Text; namespace ImaginaryBaseNumbers { class Complex { private double real, imag; public Complex(int r, int i) { real = r; imag = i; } public Complex(double r, double i) { real = r; imag = i; } public static Complex operator -(Complex self) => new Complex(-self.real, -self.imag); public static Complex operator +(Complex rhs, Complex lhs) => new Complex(rhs.real + lhs.real, rhs.imag + lhs.imag); public static Complex operator -(Complex rhs, Complex lhs) => new Complex(rhs.real - lhs.real, rhs.imag - lhs.imag); public static Complex operator *(Complex rhs, Complex lhs) => new Complex( rhs.real * lhs.real - rhs.imag * lhs.imag, rhs.real * lhs.imag + rhs.imag * lhs.real ); public static Complex operator *(Complex rhs, double lhs) => new Complex(rhs.real * lhs, rhs.imag * lhs); public static Complex operator /(Complex rhs, Complex lhs) => rhs * lhs.Inv(); public Complex Inv() { double denom = real * real + imag * imag; return new Complex(real / denom, -imag / denom); } public QuaterImaginary ToQuaterImaginary() { if (real == 0.0 && imag == 0.0) return new QuaterImaginary("0"); int re = (int)real; int im = (int)imag; int fi = -1; StringBuilder sb = new StringBuilder(); while (re != 0) { int rem = re % -4; re /= -4; if (rem < 0) { rem = 4 + rem; re++; } sb.Append(rem); sb.Append(0); } if (im != 0) { double f = (new Complex(0.0, imag) / new Complex(0.0, 2.0)).real; im = (int)Math.Ceiling(f); f = -4.0 * (f - im); int index = 1; while (im != 0) { int rem = im % -4; im /= -4; if (rem < 0) { rem = 4 + rem; im++; } if (index < sb.Length) { sb[index] = (char)(rem + 48); } else { sb.Append(0); sb.Append(rem); } index += 2; } fi = (int)f; } string reverse = new string(sb.ToString().Reverse().ToArray()); sb.Length = 0; sb.Append(reverse); if (fi != -1) sb.AppendFormat(".{0}", fi); string s = sb.ToString().TrimStart('0'); if (s[0] == '.') s = "0" + s; return new QuaterImaginary(s); } public override string ToString() { double real2 = (real == -0.0) ? 0.0 : real; // get rid of negative zero double imag2 = (imag == -0.0) ? 0.0 : imag; // ditto if (imag2 == 0.0) { return string.Format("{0}", real2); } if (real2 == 0.0) { return string.Format("{0}i", imag2); } if (imag2 > 0.0) { return string.Format("{0} + {1}i", real2, imag2); } return string.Format("{0} - {1}i", real2, -imag2); } } class QuaterImaginary { internal static Complex twoI = new Complex(0.0, 2.0); internal static Complex invTwoI = twoI.Inv(); private string b2i; public QuaterImaginary(string b2i) { if (b2i == "" || !b2i.All(c => "0123.".IndexOf(c) > -1) || b2i.Count(c => c == '.') > 1) { throw new Exception("Invalid Base 2i number"); } this.b2i = b2i; } public Complex ToComplex() { int pointPos = b2i.IndexOf("."); int posLen = (pointPos != -1) ? pointPos : b2i.Length; Complex sum = new Complex(0.0, 0.0); Complex prod = new Complex(1.0, 0.0); for (int j = 0; j < posLen; j++) { double k = (b2i[posLen - 1 - j] - '0'); if (k > 0.0) { sum += prod * k; } prod *= twoI; } if (pointPos != -1) { prod = invTwoI; for (int j = posLen + 1; j < b2i.Length; j++) { double k = (b2i[j] - '0'); if (k > 0.0) { sum += prod * k; } prod *= invTwoI; } } return sum; } public override string ToString() { return b2i; } } class Program { static void Main(string[] args) { for (int i = 1; i <= 16; i++) { Complex c1 = new Complex(i, 0); QuaterImaginary qi = c1.ToQuaterImaginary(); Complex c2 = qi.ToComplex(); Console.Write("{0,4} -> {1,8} -> {2,4} ", c1, qi, c2); c1 = -c1; qi = c1.ToQuaterImaginary(); c2 = qi.ToComplex(); Console.WriteLine("{0,4} -> {1,8} -> {2,4}", c1, qi, c2); } Console.WriteLine(); for (int i = 1; i <= 16; i++) { Complex c1 = new Complex(0, i); QuaterImaginary qi = c1.ToQuaterImaginary(); Complex c2 = qi.ToComplex(); Console.Write("{0,4} -> {1,8} -> {2,4} ", c1, qi, c2); c1 = -c1; qi = c1.ToQuaterImaginary(); c2 = qi.ToComplex(); Console.WriteLine("{0,4} -> {1,8} -> {2,4}", c1, qi, c2); } } } }
Include a file
C sharp
Demonstrate the language's ability to include source code from other files. ;See Also * [[Compiler/Simple file inclusion pre processor]]
/* The C# language specification does not give a mechanism for 'including' one source file within another, * likely because there is no need - all code compiled within one 'assembly' (individual IDE projects * are usually compiled to separate assemblies) can 'see' all other code within that assembly. */
Integer overflow
C sharp
Some languages support one or more integer types of the underlying processor. This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit. The integers supported by such a type can be ''signed'' or ''unsigned''. Arithmetic for machine level integers can often be done by single CPU instructions. This allows high performance and is the main reason to support machine level integers. ;Definition: An integer overflow happens when the result of a computation does not fit into the fixed size integer. The result can be too small or too big to be representable in the fixed size integer. ;Task: When a language has fixed size integer types, create a program that does arithmetic computations for the fixed size integers of the language. These computations must be done such that the result would overflow. The program should demonstrate what the following expressions do. For 32-bit signed integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit signed integer |- | -(-2147483647-1) | 2147483648 |- | 2000000000 + 2000000000 | 4000000000 |- | -2147483647 - 2147483647 | -4294967294 |- | 46341 * 46341 | 2147488281 |- | (-2147483647-1) / -1 | 2147483648 |} For 64-bit signed integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit signed integer |- | -(-9223372036854775807-1) | 9223372036854775808 |- | 5000000000000000000+5000000000000000000 | 10000000000000000000 |- | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |- | 3037000500 * 3037000500 | 9223372037000250000 |- | (-9223372036854775807-1) / -1 | 9223372036854775808 |} For 32-bit unsigned integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit unsigned integer |- | -4294967295 | -4294967295 |- | 3000000000 + 3000000000 | 6000000000 |- | 2147483647 - 4294967295 | -2147483648 |- | 65537 * 65537 | 4295098369 |} For 64-bit unsigned integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit unsigned integer |- | -18446744073709551615 | -18446744073709551615 |- | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |- | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |- | 4294967296 * 4294967296 | 18446744073709551616 |} ;Notes: :* When the integer overflow does trigger an exception show how the exception is caught. :* When the integer overflow produces some value, print it. :* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results. :* This should be done for signed and unsigned integers of various sizes supported by the computer programming language. :* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted. :* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
using System; public class IntegerOverflow { public static void Main() { unchecked { Console.WriteLine("For 32-bit signed integers:"); Console.WriteLine(-(-2147483647 - 1)); Console.WriteLine(2000000000 + 2000000000); Console.WriteLine(-2147483647 - 2147483647); Console.WriteLine(46341 * 46341); Console.WriteLine((-2147483647 - 1) / -1); Console.WriteLine(); Console.WriteLine("For 64-bit signed integers:"); Console.WriteLine(-(-9223372036854775807L - 1)); Console.WriteLine(5000000000000000000L + 5000000000000000000L); Console.WriteLine(-9223372036854775807L - 9223372036854775807L); Console.WriteLine(3037000500L * 3037000500L); Console.WriteLine((-9223372036854775807L - 1) / -1); Console.WriteLine(); Console.WriteLine("For 32-bit unsigned integers:"); //Negating a 32-bit unsigned integer will convert it to a signed 64-bit integer. Console.WriteLine(-4294967295U); Console.WriteLine(3000000000U + 3000000000U); Console.WriteLine(2147483647U - 4294967295U); Console.WriteLine(65537U * 65537U); Console.WriteLine(); Console.WriteLine("For 64-bit unsigned integers:"); // The - operator cannot be applied to 64-bit unsigned integers; it will always give a compile-time error. //Console.WriteLine(-18446744073709551615UL); Console.WriteLine(10000000000000000000UL + 10000000000000000000UL); Console.WriteLine(9223372036854775807UL - 18446744073709551615UL); Console.WriteLine(4294967296UL * 4294967296UL); Console.WriteLine(); } int i = 2147483647; Console.WriteLine(i + 1); try { checked { Console.WriteLine(i + 1); } } catch (OverflowException) { Console.WriteLine("Overflow!"); } } }
Integer sequence
C sharp|C#
Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library. If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
Intersecting number wheels
C sharp
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
using System; using System.Collections.Generic; using System.Linq; public static class IntersectingNumberWheels { public static void Main() { TurnWheels(('A', "123")).Take(20).Print(); TurnWheels(('A', "1B2"), ('B', "34")).Take(20).Print(); TurnWheels(('A', "1DD"), ('D', "678")).Take(20).Print(); TurnWheels(('A', "1BC"), ('B', "34"), ('C', "5B")).Take(20).Print(); } static IEnumerable<char> TurnWheels(params (char name, string values)[] wheels) { var data = wheels.ToDictionary(wheel => wheel.name, wheel => wheel.values.Loop().GetEnumerator()); var primary = data[wheels[0].name]; while (true) { yield return Turn(primary); } char Turn(IEnumerator<char> sequence) { sequence.MoveNext(); char c = sequence.Current; return char.IsDigit(c) ? c : Turn(data[c]); } } static IEnumerable<T> Loop<T>(this IEnumerable<T> seq) { while (true) { foreach (T element in seq) yield return element; } } static void Print(this IEnumerable<char> sequence) => Console.WriteLine(string.Join(" ", sequence)); }
Iterated digits squaring
C sharp
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): : Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page ;Related tasks: * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]]
using System; public static class IteratedDigitsSquaring { public static void Main() { Console.WriteLine(Count89s(1_000_000)); Console.WriteLine(Count89s(100_000_000)); } public static int Count89s(int limit) { if (limit < 1) return 0; int[] end = new int[Math.Min(limit, 9 * 9 * 9 + 2)]; int result = 0; for (int i = 1; i < end.Length; i++) { for (end[i] = i; end[i] != 1 && end[i] != 89; end[i] = SquareDigitSum(end[i])) { } if (end[i] == 89) result++; } for (int i = end.Length; i < limit; i++) { if (end[SquareDigitSum(i)] == 89) result++; } return result; int SquareDigitSum(int n) { int sum = 0; while (n > 0) { int digit = n % 10; sum += digit * digit; n /= 10; } return sum; } } }
Iterated digits squaring
C sharp from C
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): : Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page ;Related tasks: * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]]
using System; using System.Numerics; class Program { const int MaxPow = 301; static int [] sq = {1, 4, 9, 16, 25, 36, 49, 64, 81}; static BigInteger [] sums; static bool is89(int x) { while (true) { int s = 0, t; do if ((t = (x % 10) - 1) >= 0) s += sq[t]; while ((x /= 10) > 0); if (s == 89) return true; if (s == 1) return false; x = s; } } static BigInteger count89(int n) { BigInteger result = 0; for (int i = n * 81; i > 0; i--) { foreach (int s in sq) { if(s > i) break; sums[i] += sums[i - s]; } if (is89(i)) result += sums[i]; } return result; } static void Main(string[] args) { BigInteger [] t = new BigInteger[2] {1, 0}; sums = new BigInteger[MaxPow * 81]; Array.Copy(t, sums, t.Length); DateTime st = DateTime.Now; for (int n = 1; n < MaxPow; n++) { Console.Write("1->10^{0,-3}: {1}\n", n, count89(n)); if ((DateTime.Now - st).TotalSeconds > 6) break; } Console.WriteLine("{0} seconds elapsed.", (DateTime.Now - st).TotalSeconds); } }
JSON
C sharp 3.0
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
using System; using System.Collections.Generic; using System.Web.Script.Serialization; class Program { static void Main() { var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}}; var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(people); Console.WriteLine(json); var deserialized = serializer.Deserialize<Dictionary<string, object>>(json); Console.WriteLine(deserialized["2"]); var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }"); var data = jsonObject as Dictionary<string, object>; var array = data["bar"] as object[]; Console.WriteLine(array[1]); } }
Jewels and stones
C sharp
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct. The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'. Note that: :# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. :# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'. :# The parameters do not need to have exactly the same names. :# Validating the arguments is unnecessary. So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3. This task was inspired by this problem.
using System; using System.Linq; public class Program { public static void Main() { Console.WriteLine(Count("aAAbbbb", "Aa")); Console.WriteLine(Count("ZZ", "z")); } private static int Count(string stones, string jewels) { var bag = jewels.ToHashSet(); return stones.Count(bag.Contains); } }
Julia set
C sharp|C# from Python
Task Generate and draw a Julia set. ;Related tasks * Mandelbrot Set
public struct CalculatedPoint { public int x; public int y; public int i; } static void MultiThreaded() { const int w = 800; const int h = 600; const int zoom = 1; const int maxiter = 255; const int moveX = 0; const int moveY = 0; const double cX = -0.7; const double cY = 0.27015; // Precalculate a pallette of 256 colors var colors = (from c in Enumerable.Range(0, 256) select Color.FromArgb((c >> 5) * 36, (c >> 3 & 7) * 36, (c & 3) * 85)).ToArray(); // The "AsParallel" below invokes PLINQ, making evaluation parallel using as many cores as // are available. var calculatedPoints = Enumerable.Range(0, w * h).AsParallel().Select(xy => { double zx, zy, tmp; int x, y; int i = maxiter; y = xy / w; x = xy % w; zx = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX; zy = 1.0 * (y - h / 2) / (0.5 * zoom * h) + moveY; while (zx * zx + zy * zy < 4 && i > 1) { tmp = zx * zx - zy * zy + cX; zy = 2.0 * zx * zy + cY; zx = tmp; i -= 1; } return new CalculatedPoint { x = x, y = y, i = i }; }); // Bitmap is not multi-threaded, so main thread needs to read in the results as they // come in and plot the pixels. var bitmap = new Bitmap(w, h); foreach (CalculatedPoint cp in calculatedPoints) bitmap.SetPixel(cp.x, cp.y, colors[cp.i]); bitmap.Save("julia-set-multi.png"); }
Jump anywhere
C sharp|C#
Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range. This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions! * Some languages can ''go to'' any global label in a program. * Some languages can break multiple function calls, also known as ''unwinding the call stack''. * Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation). These jumps are not all alike. A simple ''goto'' never touches the call stack. A continuation saves the call stack, so you can continue a function call after it ends. ;Task: Use your language to demonstrate the various types of jumps that it supports. Because the possibilities vary by language, this task is not specific. You have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
public int M(int n) { int result = 0; switch (n) { case 1: cost += 25; break; case 2: cost += 25; goto case 1; case 3: cost += 50; goto case 1; } return result; }
Kaprekar numbers
C sharp
A positive integer is a Kaprekar number if: * It is '''1''' (unity) * The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. * The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, .... ;Example process: 10000 (1002) splitting from left to right: * The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive. * Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid. ;Task: Generate and show all Kaprekar numbers less than 10,000. ;Extra credit: Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; * Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g ;Reference: * The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version ;Related task: * [[Casting out nines]]
using System; using System.Collections.Generic; public class KaprekarNumbers { /// <summary> /// The entry point of the program, where the program control starts and ends. /// </summary> public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } /// <summary> /// Generator function which generates the Kaprekar numbers. /// </summary> /// <returns>The generator.</returns> /// <param name="max">The maximum value of the numbers generated.</param> private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; // 1 is always a Kaprekar number. yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { // Check the square against each power of 10 from 10^1 to 10^19 (highest which can be // represented by a ulong) // If the power of 10 to be checked against is greater than or equal to the square, stop checking if ( square <= check ) break; // Given a power of 10 as 10^n, the remainder when dividing the square number by that power // of 10 is equal to the last n digits of the number (starting from the right) and the // quotient gives the remaining digits. // If the last n digits are all zeroes, then the remainder will be zero, which is not // accepted. ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Kernighans large earthquake problem
C sharp
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. ;Problem: You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 ;Task: * Create a program or script invocation to find all the events with magnitude greater than 6 * Assuming an appropriate name e.g. "data.txt" for the file: :# Either: Show how your program is invoked to process a data file of that name. :# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
using System; using System.IO; using System.Linq; using System.Collections.Generic; public class Program { static void Main() { foreach (var earthquake in LargeEarthquakes("data.txt", 6)) Console.WriteLine(string.Join(" ", earthquake)); } static IEnumerable<string[]> LargeEarthquakes(string filename, double limit) => from line in File.ReadLines(filename) let parts = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries) where double.Parse(parts[2]) > limit select parts; }
Keyboard input/Obtain a Y or N response
C sharp
Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.
using System; namespace Y_or_N { class Program { static void Main() { bool response = GetYorN(); } static bool GetYorN() { ConsoleKey response; // Creates a variable to hold the user's response. do { while (Console.KeyAvailable) // Flushes the input queue. Console.ReadKey(); Console.Write("Y or N? "); // Asks the user to answer with 'Y' or 'N'. response = Console.ReadKey().Key; // Gets the user's response. Console.WriteLine(); // Breaks the line. } while (response != ConsoleKey.Y && response != ConsoleKey.N); // If the user did not respond with a 'Y' or an 'N', repeat the loop. /* * Return true if the user responded with 'Y', otherwise false. * * We know the response was either 'Y' or 'N', so we can assume * the response is 'N' if it is not 'Y'. */ return response == ConsoleKey.Y; } } }
Knight's tour
C sharp
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
using System; using System.Collections.Generic; namespace prog { class MainClass { const int N = 8; readonly static int[,] moves = { {+1,-2},{+2,-1},{+2,+1},{+1,+2}, {-1,+2},{-2,+1},{-2,-1},{-1,-2} }; struct ListMoves { public int x, y; public ListMoves( int _x, int _y ) { x = _x; y = _y; } } public static void Main (string[] args) { int[,] board = new int[N,N]; board.Initialize(); int x = 0, // starting position y = 0; List<ListMoves> list = new List<ListMoves>(N*N); list.Add( new ListMoves(x,y) ); do { if ( Move_Possible( board, x, y ) ) { int move = board[x,y]; board[x,y]++; x += moves[move,0]; y += moves[move,1]; list.Add( new ListMoves(x,y) ); } else { if ( board[x,y] >= 8 ) { board[x,y] = 0; list.RemoveAt(list.Count-1); if ( list.Count == 0 ) { Console.WriteLine( "No solution found." ); return; } x = list[list.Count-1].x; y = list[list.Count-1].y; } board[x,y]++; } } while( list.Count < N*N ); int last_x = list[0].x, last_y = list[0].y; string letters = "ABCDEFGH"; for( int i=1; i<list.Count; i++ ) { Console.WriteLine( string.Format("{0,2}: ", i) + letters[last_x] + (last_y+1) + " - " + letters[list[i].x] + (list[i].y+1) ); last_x = list[i].x; last_y = list[i].y; } } static bool Move_Possible( int[,] board, int cur_x, int cur_y ) { if ( board[cur_x,cur_y] >= 8 ) return false; int new_x = cur_x + moves[board[cur_x,cur_y],0], new_y = cur_y + moves[board[cur_x,cur_y],1]; if ( new_x >= 0 && new_x < N && new_y >= 0 && new_y < N && board[new_x,new_y] == 0 ) return true; return false; } } }
Kolakoski sequence
C sharp|C# from Java
The natural numbers, (excluding zero); with the property that: : ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''. ;Example: This is ''not'' a Kolakoski sequence: 1,1,2,2,2,1,2,2,1,2,... Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this: : Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ... The above gives the RLE of: 2, 3, 1, 2, 1, ... The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''. ;Creating a Kolakoski sequence: Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,.... # We start the sequence s with the first item from the cycle c: 1 # An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s. We started s with 1 and therefore s[k] states that it should appear only the 1 time. Increment k Get the next item from c and append it to the end of sequence s. s will then become: 1, 2 k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2 Increment k Append the next item from the cycle to the list: 1, 2,2, 1 k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1 increment k ... '''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case. ;Task: # Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle. # Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence. # Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE). # Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 20 members of the sequence generated from (2, 1) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1) # Check the sequence againt its RLE. (There are rules on generating Kolakoski sequences from this method that are broken by the last example)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KolakoskiSequence { class Crutch { public readonly int len; public int[] s; public int i; public Crutch(int len) { this.len = len; s = new int[len]; i = 0; } public void Repeat(int count) { for (int j = 0; j < count; j++) { if (++i == len) return; s[i] = s[i - 1]; } } } static class Extension { public static int NextInCycle(this int[] self, int index) { return self[index % self.Length]; } public static int[] Kolakoski(this int[] self, int len) { Crutch c = new Crutch(len); int k = 0; while (c.i < len) { c.s[c.i] = self.NextInCycle(k); if (c.s[k] > 1) { c.Repeat(c.s[k] - 1); } if (++c.i == len) return c.s; k++; } return c.s; } public static bool PossibleKolakoski(this int[] self) { int[] rle = new int[self.Length]; int prev = self[0]; int count = 1; int pos = 0; for (int i = 1; i < self.Length; i++) { if (self[i] == prev) { count++; } else { rle[pos++] = count; count = 1; prev = self[i]; } } // no point adding final 'count' to rle as we're not going to compare it anyway for (int i = 0; i < pos; i++) { if (rle[i] != self[i]) { return false; } } return true; } public static string AsString(this int[] self) { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var item in self) { if (count > 0) { sb.Append(", "); } sb.Append(item); count++; } return sb.Append("]").ToString(); } } class Program { static void Main(string[] args) { int[][] ias = { new int[]{1, 2}, new int[]{2, 1}, new int[]{1, 3, 1, 2}, new int[]{1, 3, 2, 1} }; int[] lens = { 20, 20, 30, 30 }; for (int i = 0; i < ias.Length; i++) { int len = lens[i]; int[] kol = ias[i].Kolakoski(len); Console.WriteLine("First {0} members of the sequence by {1}: ", len, ias[i].AsString()); Console.WriteLine(kol.AsString()); Console.WriteLine("Possible Kolakoski sequence? {0}", kol.PossibleKolakoski()); Console.WriteLine(); } } } }
Kosaraju
C sharp|C#
{{wikipedia|Graph}} Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph. For this task consider the directed graph with these connections: 0 -> 1 1 -> 2 2 -> 0 3 -> 1, 3 -> 2, 3 -> 4 4 -> 3, 4 -> 5 5 -> 2, 5 -> 6 6 -> 5 7 -> 4, 7 -> 6, 7 -> 7 And report the kosaraju strongly connected component for each node. ;References: * The article on Wikipedia.
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } /// <summary> /// Kosaraju's strongly connected components algorithm /// </summary> public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
Lah numbers
C sharp|C# from D
Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets. Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them. Lah numbers obey the identities and relations: L(n, 0), L(0, k) = 0 # for n, k > 0 L(n, n) = 1 L(n, 1) = n! L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers ''or'' L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers ;Task: :* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. :* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n). :* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''. ;See also: :* '''Wikipedia - Lah number''' :* '''OEIS:A105278 - Unsigned Lah numbers''' :* '''OEIS:A008297 - Signed Lah numbers''' ;Related Tasks: :* '''Stirling numbers of the first kind''' :* '''Stirling numbers of the second kind''' :* '''Bell numbers'''
using System; using System.Linq; using System.Numerics; namespace LahNumbers { class Program { static BigInteger Factorial(BigInteger n) { if (n == 0) return 1; BigInteger res = 1; while (n > 0) { res *= n--; } return res; } static BigInteger Lah(BigInteger n, BigInteger k) { if (k == 1) return Factorial(n); if (k == n) return 1; if (k > n) return 0; if (k < 1 || n < 1) return 0; return (Factorial(n) * Factorial(n - 1)) / (Factorial(k) * Factorial(k - 1)) / Factorial(n - k); } static void Main() { Console.WriteLine("Unsigned Lah numbers: L(n, k):"); Console.Write("n/k "); foreach (var i in Enumerable.Range(0, 13)) { Console.Write("{0,10} ", i); } Console.WriteLine(); foreach (var row in Enumerable.Range(0, 13)) { Console.Write("{0,-3}", row); foreach (var i in Enumerable.Range(0, row + 1)) { var l = Lah(row, i); Console.Write("{0,11}", l); } Console.WriteLine(); } Console.WriteLine("\nMaximum value from the L(100, *) row:"); var maxVal = Enumerable.Range(0, 100).Select(a => Lah(100, a)).Max(); Console.WriteLine(maxVal); } } }
Largest int from concatenated ints
C sharp|C#
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var source1 = new int[] { 1, 34, 3, 98, 9, 76, 45, 4 }; var source2 = new int[] { 54, 546, 548, 60 }; var largest1 = LargestPossibleSequence(source1); var largest2 = LargestPossibleSequence(source2); Console.WriteLine("The largest possible integer from set 1 is: {0}", largest1); Console.WriteLine("The largest possible integer from set 2 is: {0}", largest2); } static long LargestPossibleSequence(int[] ints) { return long.Parse(string.Join("", ints.OrderBy(i => i, new IntConcatenationComparer()).Reverse())); } } class IntConcatenationComparer : IComparer<int> { public int Compare(int x, int y) { var xy = int.Parse(x.ToString() + y.ToString()); var yx = int.Parse(y.ToString() + x.ToString()); return xy - yx; } }
Largest number divisible by its digits
C sharp|C#
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits. These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the (base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. ;Example: '''135''' is evenly divisible by '''1''', '''3''', and '''5'''. Note that the digit zero (0) can not be in the number as integer division by zero is undefined. The digits must all be unique so a base ten number will have at most '''9''' digits. Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.) ;Stretch goal: Do the same thing for hexadecimal. ;Related tasks: :* gapful numbers. :* palindromic gapful numbers. ;Also see: :* The OEIS sequence: A115569: Lynch-Bell numbers.
using System; class Program { static int gcd(int a, int b) { return b > 0 ? gcd(b, a % b) : a; } // returns least common multiple of digits of x in base b static int lcmd(long x, int b) { int r = (int)(x % b), a; x /= b; while (x > 0) { r = (r * (a = (int)(x % b))) / gcd(r, a); x /= b; } return r; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); long mx = 987654321; // all digits except zero mx = 98764321; // omitting 5 because even numbers are lost mx /= 10; // 7 digs because 8 digs won't divide by 3 long skip = lcmd(mx, 10), i; bool nDup; for (i = mx - mx % skip; ; i -= skip) { var s = i.ToString().ToCharArray(); Array.Sort(s); if (s[0] == '0') continue; // no zeros nDup = true; // checking for duplicate digits or digit five for (int j = 0, k = 1; k < s.Length; j = k++) if (s[j] == s[k] || s[k] == '5') { nDup = false; break; } if (nDup) break; } sw.Stop(); // found it Console.Write("base 10 = {0} in {1} μs\n", i, 1000 * sw.Elapsed.TotalMilliseconds); sw.Restart(); mx = 0xfedcba987654321; // all 15 digits used, no zero skip = lcmd(mx >> 4, 16); // digit one implied, so omit it for (i = mx - mx % skip; ; i -= skip) { var s = i.ToString("x").ToCharArray(); Array.Sort(s); if (s[0] == '0') continue; // no zeros nDup = true; // checking for duplicate digits for (int j = 0, k = 1; k < s.Length; j = k++) if (s[j] == s[k]) { nDup = false; break; } if (nDup) break; } sw.Stop(); // found it Console.Write("base 16 = {0} in {1} ms", i.ToString("x"), sw.Elapsed.TotalMilliseconds); } }
Last Friday of each month
C sharp
Write a program or a script that returns the date of the last Fridays 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_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 2012-06-29 2012-07-27 2012-08-31 2012-09-28 2012-10-26 2012-11-30 2012-12-28 ;Related tasks * [[Five weekends]] * [[Day of the week]] * [[Find the last Sunday of each month]]
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace RosettaCode.LastFridaysOfYear { internal static class Program { private static IEnumerable<DateTime> LastFridaysOfYear(int year) { for (var month = 1; month <= 12; month++) { var date = new DateTime(year, month, 1).AddMonths(1).AddDays(-1); while (date.DayOfWeek != DayOfWeek.Friday) { date = date.AddDays(-1); } yield return date; } } private static void Main(string[] arguments) { int year; var argument = arguments.FirstOrDefault(); if (string.IsNullOrEmpty(argument) || !int.TryParse(argument, out year)) { year = DateTime.Today.Year; } foreach (var date in LastFridaysOfYear(year)) { Console.WriteLine(date.ToString("d", CultureInfo.InvariantCulture)); } } } }
Last letter-first letter
C sharp
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category, Child 1: dog Child 2: goldfish Child 1: hippopotamus Child 2: snake ... ;Task: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated. audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask Extra brownie points for dealing with the full list of 646 names.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string pokemon_names = @"audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask"; string[] pokemon = pokemon_names.Split(new char[]{' ','\n'}); List<string> chain = new List<string>(pokemon.Length); for (int i = 0; i < pokemon.Length; i++) { swap(ref pokemon[0], ref pokemon[i]); Search( pokemon, chain, 1 ); swap(ref pokemon[0], ref pokemon[i]); } foreach (string s in chain) Console.WriteLine(s); Console.ReadKey(); } static void Search(string[] pokemon, List<string> longest_chain, int len ) { if (len > longest_chain.Count) { longest_chain.Clear(); for (int i = 0; i < len; i++) longest_chain.Add(pokemon[i]); } char lastchar = pokemon[len - 1][pokemon[len-1].Length - 1]; for (int i = len; i < pokemon.Length; i++) { if (pokemon[i][0] == lastchar) { swap(ref pokemon[i], ref pokemon[len]); Search(pokemon, longest_chain, len + 1); swap(ref pokemon[i], ref pokemon[len]); } } } static void swap(ref string s1, ref string s2) { string tmp = s1; s1 = s2; s2 = tmp; } } }
Latin Squares in reduced form
C sharp|C# from D
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained. For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row. Demonstrate by: * displaying the four reduced Latin Squares of order 4. * for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; // use 0 basing var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; // recursive closure permutes a[1:] matrix r = new matrix(); void recurse(int last) { if (last == first) { // bottom of recursion. you get here once for each permutation. // test if permutation is deranged. for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; //no, ignore it } } // yes, save a copy with 1 based indexing var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } // first row for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } //remaing rows recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f); } } } }
Law of cosines - triples
C sharp
The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(g) = C2 ;Specific angles: For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation": A2 + B2 = C2 For an angle of '''60o''' this becomes the less familiar equation: A2 + B2 - AB = C2 And finally for an angle of '''120o''' this becomes the equation: A2 + B2 + AB = C2 ;Task: * Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered. * Restrain all sides to the integers '''1..13''' inclusive. * Show how many results there are for each of the three angles mentioned above. * Display results on this page. Note: Triangles with the same length sides but different order are to be treated as the same. ;Optional Extra credit: * How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''. ;Related Task * [[Pythagorean triples]] ;See also: * Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class LawOfCosinesTriples { public static void Main2() { PrintTriples(60, 13); PrintTriples(90, 13); PrintTriples(120, 13); PrintTriples(60, 10_000, true, false); } private static void PrintTriples(int degrees, int maxSideLength, bool notAllTheSameLength = false, bool print = true) { string s = $"{degrees} degree triangles in range 1..{maxSideLength}"; if (notAllTheSameLength) s += " where not all sides are the same"; Console.WriteLine(s); int count = 0; var triples = FindTriples(degrees, maxSideLength); if (notAllTheSameLength) triples = triples.Where(NotAllTheSameLength); foreach (var triple in triples) { count++; if (print) Console.WriteLine(triple); } Console.WriteLine($"{count} solutions"); } private static IEnumerable<(int a, int b, int c)> FindTriples(int degrees, int maxSideLength) { double radians = degrees * Math.PI / 180; int coefficient = (int)Math.Round(Math.Cos(radians) * -2, MidpointRounding.AwayFromZero); int maxSideLengthSquared = maxSideLength * maxSideLength; return from a in Range(1, maxSideLength) from b in Range(1, a) let cc = a * a + b * b + a * b * coefficient where cc <= maxSideLengthSquared let c = (int)Math.Sqrt(cc) where c * c == cc select (a, b, c); } private static bool NotAllTheSameLength((int a, int b, int c) triple) => triple.a != triple.b || triple.a != triple.c; }
Least common multiple
C sharp|C#
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
Left factorials
C sharp|C#
'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; the same notation can be confusingly seen being used for the two different definitions. Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: :::::::* !''n''` :::::::* !''n'' :::::::* ''n''! (It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''': ::::: !n = \sum_{k=0}^{n-1} k! :::: where ::::: !0 = 0 ;Task Display the left factorials for: * zero through ten (inclusive) * 20 through 110 (inclusive) by tens Display the length (in decimal digits) of the left factorials for: * 1,000 through 10,000 (inclusive), by thousands. ;Also see: * The OEIS entry: A003422 left factorials * The MathWorld entry: left factorial * The MathWorld entry: factorial sums * The MathWorld entry: subfactorial ;Related task: * permutations/derangements (subfactorials)
using System; using System.Numerics; namespace LeftFactorial { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) { Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i))); } for (int j = 20; j <= 110; j += 10) { Console.WriteLine(string.Format("!{0} = {1}", j, LeftFactorial(j))); } for (int k = 1000; k <= 10000; k += 1000) { Console.WriteLine(string.Format("!{0} has {1} digits", k, LeftFactorial(k).ToString().Length)); } Console.ReadKey(); } private static BigInteger Factorial(int number) { BigInteger accumulator = 1; for (int factor = 1; factor <= number; factor++) { accumulator *= factor; } return accumulator; } private static BigInteger LeftFactorial(int n) { BigInteger result = 0; for (int i = 0; i < n; i++) { result += Factorial(i); } return result; } } }
Levenshtein distance
C sharp|C#
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
using System; namespace LevenshteinDistance { class Program { static int LevenshteinDistance(string s, string t) { int n = s.Length; int m = t.Length; int[,] d = new int[n + 1, m + 1]; if (n == 0) { return m; } if (m == 0) { return n; } for (int i = 0; i <= n; i++) d[i, 0] = i; for (int j = 0; j <= m; j++) d[0, j] = j; for (int j = 1; j <= m; j++) for (int i = 1; i <= n; i++) if (s[i - 1] == t[j - 1]) d[i, j] = d[i - 1, j - 1]; //no operation else d[i, j] = Math.Min(Math.Min( d[i - 1, j] + 1, //a deletion d[i, j - 1] + 1), //an insertion d[i - 1, j - 1] + 1 //a substitution ); return d[n, m]; } static void Main(string[] args) { if (args.Length == 2) Console.WriteLine("{0} -> {1} = {2}", args[0], args[1], LevenshteinDistance(args[0], args[1])); else Console.WriteLine("Usage:-\n\nLevenshteinDistance <string1> <string2>"); } } }
Long year
C sharp
Most years have 52 weeks, some have 53, according to ISO8601. ;Task: Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
using static System.Console; using System.Collections.Generic; using System.Linq; using System.Globalization; public static class Program { public static void Main() { WriteLine("Long years in the 21st century:"); WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53))); } public static IEnumerable<int> To(this int start, int end) { for (int i = start; i < end; i++) yield return i; } }
Longest common subsequence
C sharp|C#
'''Introduction''' Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string. The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings. Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n. The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''. Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly. We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''. Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly. A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable. A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j]. Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''. According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. '''Background''' Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n''). '''Note''' [Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)''). '''Legend''' A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of matches (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet S of distinct symbols in A + B '''References''' [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, ''pp.'' 275-281] '''Examples''' The sequences "1234" and "1224533324" have an LCS of "1234": '''1234''' '''12'''245'''3'''332'''4''' For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": '''t'''hi'''si'''sa'''test''' '''t'''e'''s'''t'''i'''ng123'''test'''ing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia.
using System; namespace LCS { class Program { static void Main(string[] args) { string word1 = "thisisatest"; string word2 = "testing123testing"; Console.WriteLine(lcsBack(word1, word2)); Console.ReadKey(); } public static string lcsBack(string a, string b) { string aSub = a.Substring(0, (a.Length - 1 < 0) ? 0 : a.Length - 1); string bSub = b.Substring(0, (b.Length - 1 < 0) ? 0 : b.Length - 1); if (a.Length == 0 || b.Length == 0) return ""; else if (a[a.Length - 1] == b[b.Length - 1]) return lcsBack(aSub, bSub) + a[a.Length - 1]; else { string x = lcsBack(a, bSub); string y = lcsBack(aSub, b); return (x.Length > y.Length) ? x : y; } } } }
Longest common substring
C sharp|C#
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
using System; namespace LongestCommonSubstring { class Program { static void Main(string[] args) { Console.WriteLine(lcs("thisisatest", "testing123testing")); Console.ReadKey(true); } public static string lcs(string a, string b) { var lengths = new int[a.Length, b.Length]; int greatestLength = 0; string output = ""; for (int i = 0; i < a.Length; i++) { for (int j = 0; j < b.Length; j++) { if (a[i] == b[j]) { lengths[i, j] = i == 0 || j == 0 ? 1 : lengths[i - 1, j - 1] + 1; if (lengths[i, j] > greatestLength) { greatestLength = lengths[i, j]; output = a.Substring(i - greatestLength + 1, greatestLength); } } else { lengths[i, j] = 0; } } } return output; } } }
Longest common substring
C sharp|C# from REXX
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
//C# program tests the LCSUBSTR (Longest Common Substring) subroutine. using System; namespace LongestCommonSubstring { class Program { static void Main(string[] args) { string a = args.Length >= 1 ? args[0] : ""; /*get two arguments (strings). */ string b = args.Length == 2 ? args[1] : ""; if (a == "") a = "thisisatest"; /*use this string for a default. */ if (b == "") b = "testing123testing"; /* " " " " " " */ Console.WriteLine("string A = {0}", a); /*echo string A to screen. */ Console.WriteLine("string B = {0}", b); /*echo string B to screen. */ Console.WriteLine("LCsubstr = {0}", LCsubstr(a, b)); /*tell Longest Common Substring. */ Console.ReadKey(true); } /*stick a fork in it, we're done.*/ /*─────────────────────────────────LCSUBSTR subroutine─────────────────────────────────*/ public static string LCsubstr(string x, string y) /*Longest Common Substring. */ { string output = ""; int lenx = x.Length; /*shortcut for using the X length*/ for (int j = 0; j < lenx; j++) /*step through start points in X.*/ { for (int k = lenx - j; k > -1; k--) /*step through string lengths. */ { string common = x.Substring(j, k); /*extract a common substring. */ if (y.IndexOf(common) > -1 && common.Length > output.Length) output = common; /*longest?*/ } /*k*/ } /*j*/ return output; /*$ is "" if no common string. */ } } }
Longest common substring
C sharp|C# from zkl
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
//C# program tests the LCS (Longest Common Substring) subroutine. using System; namespace LongestCommonSubstring { class Program { static void Main(string[] args) { string a = args.Length >= 1 ? args[0] : ""; /*get two arguments (strings). */ string b = args.Length == 2 ? args[1] : ""; if (a == "") a = "thisisatest"; /*use this string for a default. */ if (b == "") b = "testing123testing"; /* " " " " " " */ Console.WriteLine("string A = {0}", a); /*echo string A to screen. */ Console.WriteLine("string B = {0}", b); /*echo string B to screen. */ Console.WriteLine("LCS = {0}", lcs(a, b)); /*tell Longest Common Substring. */ Console.ReadKey(true); } /*stick a fork in it, we're done.*/ /*─────────────────────────────────LCS subroutine─────────────────────────────────*/ private static string lcs(string a, string b) { if(b.Length<a.Length){ string t=a; a=b; b=t; } for (int n = a.Length; n > 0; n--) { for (int m = a.Length-n; m <= a.Length-n; m++) { string s=a.Substring(m,n); if(b.Contains(s)) return(s); } } return ""; } }
Longest increasing subsequence
C sharp 6
Calculate and show here a longest increasing subsequence of the list: :\{3, 2, 6, 4, 5, 1\} And of the list: :\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} Note that a list may have more than one subsequence that is of the maximum length. ;Ref: # Dynamic Programming #1: Longest Increasing Subsequence on YouTube # An efficient solution can be based on Patience sorting.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse(); private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) { if (index == values.Count) return current; if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0) return FindRecImpl(values, current, index + 1, comparer); return Max( FindRecImpl(values, current, index + 1, comparer), FindRecImpl(values, current + values[index], index + 1, comparer) ); } private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a; class Sequence<T> : IEnumerable<T> { public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null); public Sequence(T value, Sequence<T> tail) { Value = value; Tail = tail; Length = tail == null ? 0 : tail.Length + 1; } public T Value { get; } public Sequence<T> Tail { get; } public int Length { get; } public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s); public IEnumerator<T> GetEnumerator() { for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
Longest increasing subsequence
C sharp 7
Calculate and show here a longest increasing subsequence of the list: :\{3, 2, 6, 4, 5, 1\} And of the list: :\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} Note that a list may have more than one subsequence that is of the maximum length. ;Ref: # Dynamic Programming #1: Longest Increasing Subsequence on YouTube # An efficient solution can be based on Patience sorting.
public static class LIS { public static T[] Find<T>(IList<T> values, IComparer<T> comparer = null) { if (values == null) throw new ArgumentNullException(); if (comparer == null) comparer = Comparer<T>.Default; var pileTops = new List<T>(); var pileAssignments = new int[values.Count]; for (int i = 0; i < values.Count; i++) { T element = values[i]; int pile = pileTops.BinarySearch(element, comparer); if (pile < 0) pile = ~pile; if (pile == pileTops.Count) pileTops.Add(element); else pileTops[pile] = element; pileAssignments[i] = pile; } T[] result = new T[pileTops.Count]; for (int i = pileAssignments.Length - 1, p = pileTops.Count - 1; p >= 0; i--) { if (pileAssignments[i] == p) result[p--] = values[i]; } return result; } public static void Main() { Console.WriteLine(string.Join(",", LIS.Find(new [] { 3, 2, 6, 4, 5, 1 }))); Console.WriteLine(string.Join(",", LIS.Find(new [] { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }))); } }
MAC vendor lookup
C sharp|C#
Every connected device around the world comes with a unique Media Access Control address, or a MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. ;Task: Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. '''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task<string> LookupMac(string MacAddress) { var uri = new Uri("http://api.macvendors.com/" + WebUtility.UrlEncode(MacAddress)); using (var wc = new HttpClient()) return await wc.GetStringAsync(uri); } static void Main(string[] args) { foreach (var mac in new string[] { "88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D" }) Console.WriteLine(mac + "\t" + LookupMac(mac).Result); Console.ReadLine(); } }
MD4
C sharp|C#
Find the MD4 message digest of a string of [[octet]]s. Use the ASCII encoded string "Rosetta Code" (without quotes). You may either call an MD4 library, or implement MD4 in your language. '''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
using System; using System.Collections.Generic; using System.Linq; using System.Text; static class Md4 { public static string Md4Hash(this string input) { // get padded uints from bytes List<byte> bytes = Encoding.ASCII.GetBytes(input).ToList(); uint bitCount = (uint)(bytes.Count) * 8; bytes.Add(128); while (bytes.Count % 64 != 56) bytes.Add(0); var uints = new List<uint>(); for (int i = 0; i + 3 < bytes.Count; i += 4) uints.Add(bytes[i] | (uint)bytes[i + 1] << 8 | (uint)bytes[i + 2] << 16 | (uint)bytes[i + 3] << 24); uints.Add(bitCount); uints.Add(0); // run rounds uint a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476; Func<uint, uint, uint> rol = (x, y) => x << (int)y | x >> 32 - (int)y; for (int q = 0; q + 15 < uints.Count; q += 16) { var chunk = uints.GetRange(q, 16); uint aa = a, bb = b, cc = c, dd = d; Action<Func<uint, uint, uint, uint>, uint[]> round = (f, y) => { foreach (uint i in new[] { y[0], y[1], y[2], y[3] }) { a = rol(a + f(b, c, d) + chunk[(int)(i + y[4])] + y[12], y[8]); d = rol(d + f(a, b, c) + chunk[(int)(i + y[5])] + y[12], y[9]); c = rol(c + f(d, a, b) + chunk[(int)(i + y[6])] + y[12], y[10]); b = rol(b + f(c, d, a) + chunk[(int)(i + y[7])] + y[12], y[11]); } }; round((x, y, z) => (x & y) | (~x & z), new uint[] { 0, 4, 8, 12, 0, 1, 2, 3, 3, 7, 11, 19, 0 }); round((x, y, z) => (x & y) | (x & z) | (y & z), new uint[] { 0, 1, 2, 3, 0, 4, 8, 12, 3, 5, 9, 13, 0x5a827999 }); round((x, y, z) => x ^ y ^ z, new uint[] { 0, 2, 1, 3, 0, 8, 4, 12, 3, 9, 11, 15, 0x6ed9eba1 }); a += aa; b += bb; c += cc; d += dd; } // return hex encoded string byte[] outBytes = new[] { a, b, c, d }.SelectMany(BitConverter.GetBytes).ToArray(); return BitConverter.ToString(outBytes).Replace("-", "").ToLower(); } static void Main() { Console.WriteLine("Rosetta Code".Md4Hash()); } }
Mad Libs
C sharp
{{wikipedia}} Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. ;Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: went for a walk in the park. found a . decided to take it home. Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace MadLibs_RosettaCode { class Program { static void Main(string[] args) { string madLibs = @"Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value)."; StringBuilder sb = new StringBuilder(); Regex pattern = new Regex(@"\<(.*?)\>"); string storyLine; string replacement; Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine); Console.WriteLine("Enter a story: "); // Continue to get input while empty line hasn't been entered. do { storyLine = Console.ReadLine(); sb.Append(storyLine + Environment.NewLine); } while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine)); // Retrieve only the unique regex matches from the user entered story. Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match; if(nameMatch != null) { do { Console.WriteLine("Enter value for: " + nameMatch.Value); replacement = Console.ReadLine(); } while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement)); sb.Replace(nameMatch.Value, replacement); } foreach (Match match in pattern.Matches(sb.ToString())) { replacement = string.Empty; // Guarantee we get a non-whitespace value for the replacement do { Console.WriteLine("Enter value for: " + match.Value); replacement = Console.ReadLine(); } while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement)); int location = sb.ToString().IndexOf(match.Value); sb.Remove(location, match.Value.Length).Insert(location, replacement); } Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--"); Console.WriteLine(sb.ToString()); } } }
Magic 8-ball
C#
Create Magic 8-Ball. See details at: Magic 8-Ball.
using System; namespace newProg { class Program { static void Main(string[] args) { string[] answers = { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes – definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful." }; while (true) { Random rnd = new Random(); int result = rnd.Next(0, 19); Console.WriteLine("Magic 8 Ball! Ask question and hit a key for the answer!"); string inp = Console.ReadLine(); Console.WriteLine(answers[result]); } } } }
Magic squares of doubly even order
C sharp|C# from Java
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). This means that the subsquares also have an even size, which plays a role in the construction. {| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%" |- |'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8''' |- |'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16''' |- |'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41''' |- |'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33''' |- |'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25''' |- |'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17''' |- |'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56''' |- |'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64''' |} ;Task Create a magic square of '''8 x 8'''. ;Related tasks * [[Magic squares of odd order]] * [[Magic squares of singly even order]] ;See also: * Doubly Even Magic Squares (1728.org)
using System; namespace MagicSquareDoublyEven { class Program { static void Main(string[] args) { int n = 8; var result = MagicSquareDoublyEven(n); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) Console.Write("{0,2} ", result[i, j]); Console.WriteLine(); } Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2); Console.ReadLine(); } private static int[,] MagicSquareDoublyEven(int n) { if (n < 4 || n % 4 != 0) throw new ArgumentException("base must be a positive " + "multiple of 4"); // pattern of count-up vs count-down zones int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; // how many multiples of 4 int[,] result = new int[n, n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } } }
Map range
C sharp
Given two ranges: :::* [a_1,a_2] and :::* [b_1,b_2]; :::* then a value s in range [a_1,a_2] :::* is linearly mapped to a value t in range [b_1,b_2] where: :::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)} ;Task: Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range [0, 10] to the range [-1, 0]. ;Extra credit: Show additional idiomatic ways of performing the mapping, using tools available to the language.
using System; using System.Linq; public class MapRange { public static void Main() { foreach (int i in Enumerable.Range(0, 11)) Console.WriteLine($"{i} maps to {Map(0, 10, -1, 0, i)}"); } static double Map(double a1, double a2, double b1, double b2, double s) => b1 + (s - a1) * (b2 - b1) / (a2 - a1); }
Maximum triangle path sum
C sharp|C#
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. ;Task: Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
using System; namespace RosetaCode { class MainClass { public static void Main (string[] args) { int[,] list = new int[18,19]; string input = @"55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"; var charArray = input.Split ('\n'); for (int i=0; i < charArray.Length; i++) { var numArr = charArray[i].Trim().Split(' '); for (int j = 0; j<numArr.Length; j++) { int number = Convert.ToInt32 (numArr[j]); list [i, j] = number; } } for (int i = 16; i >= 0; i--) { for (int j = 0; j < 18; j++) { list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]); } } Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0])); } } }
McNuggets problem
C sharp|C#
From Wikipedia: The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. ;Task: Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n'' where ''x'', ''y'' and ''z'' are natural numbers).
using System; public class McNuggets { public static void Main() { bool[] isMcNuggetNumber = new bool[101]; for (int x = 0; x <= 100/6; x++) { for (int y = 0; y <= 100/9; y++) { for (int z = 0; z <= 100/20; z++) { int mcNuggetNumber = x*6 + y*9 + z*20; if (mcNuggetNumber <= 100) { isMcNuggetNumber[mcNuggetNumber] = true; } } } } for (int mnnCheck = isMcNuggetNumber.Length-1; mnnCheck >= 0; mnnCheck--) { if (!isMcNuggetNumber[mnnCheck]) { Console.WriteLine("Largest non-McNuggett Number less than 100: " + mnnCheck.ToString()); break; } } } }
Metaprogramming
C sharp|C#
{{omit from|BBC BASIC}} Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
Metaprogramming in C# can be achieved using the [https://msdn.microsoft.com/en-us/library/bb126445.aspx Text Template Transformation Toolkit]. It is a textual preprocessor embedded in Visual Studio (it can also be executed from the command-line, e.g. in build scripts). It is language-agnostic, and therefore can generate code for C#, Visual Basic or other languages. This also means that it has no features which help manipulating the underlying language: it is purely textual, and does '''not''' include a C# parser to transform existing C# files (so you will need to roll your own or use [https://roslyn.codeplex.com/ Roslyn]), and does '''not''' include utilities which would help with combining pieces of code.
Mian-Chowla sequence
C#|CSharp from Go
The Mian-Chowla sequence is an integer sequence defined recursively. Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences. The sequence starts with: ::a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ::ai + aj is distinct, for all i and j less than or equal to n. ;The Task: :* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence. :* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence. Demonstrating working through the first few terms longhand: ::a1 = 1 ::1 + 1 = 2 Speculatively try a2 = 2 ::1 + 1 = 2 ::1 + 2 = 3 ::2 + 2 = 4 There are no repeated sums so '''2''' is the next number in the sequence. Speculatively try a3 = 3 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 3 = 4 ::2 + 2 = 4 ::2 + 3 = 5 ::3 + 3 = 6 Sum of '''4''' is repeated so '''3''' is rejected. Speculatively try a3 = 4 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 4 = 5 ::2 + 2 = 4 ::2 + 4 = 6 ::4 + 4 = 8 There are no repeated sums so '''4''' is the next number in the sequence. And so on... ;See also: :* OEIS:A005282 Mian-Chowla sequence
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; static class Program { static int[] MianChowla(int n) { int[] mc = new int[n - 1 + 1]; HashSet<int> sums = new HashSet<int>(), ts = new HashSet<int>(); int sum; mc[0] = 1; sums.Add(2); for (int i = 1; i <= n - 1; i++) { for (int j = mc[i - 1] + 1; ; j++) { mc[i] = j; for (int k = 0; k <= i; k++) { sum = mc[k] + j; if (sums.Contains(sum)) { ts.Clear(); break; } ts.Add(sum); } if (ts.Count > 0) { sums.UnionWith(ts); break; } } } return mc; } static void Main(string[] args) { const int n = 100; Stopwatch sw = new Stopwatch(); string str = " of the Mian-Chowla sequence are:\n"; sw.Start(); int[] mc = MianChowla(n); sw.Stop(); Console.Write("The first 30 terms{1}{2}{0}{0}Terms 91 to 100{1}{3}{0}{0}" + "Computation time was {4}ms.{0}", '\n', str, string.Join(" ", mc.Take(30)), string.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds); } }
Minimal steps down to 1
C sharp 7
Given: * A starting, positive integer (greater than one), N. * A selection of possible integer perfect divisors, D. * And a selection of possible subtractors, S. The goal is find the minimum number of steps necessary to reduce N down to one. At any step, the number may be: * Divided by any member of D if it is perfectly divided by D, (remainder zero). * OR have one of S subtracted from it, if N is greater than the member of S. There may be many ways to reduce the initial N down to 1. Your program needs to: * Find the ''minimum'' number of ''steps'' to reach 1. * Show '''one''' way of getting fron N to 1 in those minimum steps. ;Examples: No divisors, D. a single subtractor of 1. :Obviousely N will take N-1 subtractions of 1 to reach 1 Single divisor of 2; single subtractor of 1: :N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1 :N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1 Divisors 2 and 3; subtractor 1: :N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1 ;Task: Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1: :1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1. :2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000. Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2: :3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1. :4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000. ;Optional stretch goal: :2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000 ;Reference: * Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.
using System; using System.Collections.Generic; using System.Linq; public static class MinimalSteps { public static void Main() { var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 }); var lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); Console.WriteLine(); subtractors = new [] { 2 }; lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); } private static void PrintRange((char op, int param, int steps)[] lookup, int limit) { for (int goal = 1; goal <= limit; goal++) { var x = lookup[goal]; if (x.param == 0) { Console.WriteLine($"{goal} cannot be reached with these numbers."); continue; } Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: "); for (int n = goal; n > 1; ) { Console.Write($"{n},{x.op}{x.param}=> "); n = x.op == '/' ? n / x.param : n - x.param; x = lookup[n]; } Console.WriteLine("1"); } } private static void PrintMaxMins((char op, int param, int steps)[] lookup) { var maxSteps = lookup.Max(x => x.steps); var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList(); Console.WriteLine(items.Count == 1 ? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}" : $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}" ); } private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors) { var lookup = new (char op, int param, int steps)[goal+1]; lookup[1] = ('/', 1, 0); for (int n = 1; n < lookup.Length; n++) { var ln = lookup[n]; if (ln.param == 0) continue; for (int d = 0; d < divisors.Length; d++) { int target = n * divisors[d]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1); } for (int s = 0; s < subtractors.Length; s++) { int target = n + subtractors[s]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1); } } return lookup; } private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source); }
Minimum positive multiple in base 10 using only 0 and 1
C#|Csharp
Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''". ;Task: Write a routine to find the B10 of a given integer. E.G. '''n''' '''B10''' '''n''' x '''multiplier''' 1 1 ( 1 x 1 ) 2 10 ( 2 x 5 ) 7 1001 ( 7 x 143 ) 9 111111111 ( 9 x 12345679 ) 10 10 ( 10 x 1 ) and so on. Use the routine to find and display here, on this page, the '''B10''' value for: 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999 Optionally find '''B10''' for: 1998, 2079, 2251, 2277 Stretch goal; find '''B10''' for: 2439, 2997, 4878 There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation. ;See also: :* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's. :* How to find Minimum Positive Multiple in base 10 using only 0 and 1
using System; using System.Collections.Generic; using static System.Console; class Program { static string B10(int n) { int[] pow = new int[n + 1], val = new int[29]; for (int count = 0, ten = 1, x = 1; x <= n; x++) { val[x] = ten; for (int j = 0, t; j <= n; j++) if (pow[j] != 0 && pow[j] != x && pow[t = (j + ten) % n] == 0) pow[t] = x; if (pow[ten] == 0) pow[ten] = x; ten = (10 * ten) % n; if (pow[0] != 0) { x = n; string s = ""; while (x != 0) { int p = pow[x % n]; if (count > p) s += new string('0', count - p); count = p - 1; s += "1"; x = (n + x - val[p]) % n; } if (count > 0) s += new string('0', count); return s; } } return "1"; } static void Main(string[] args) { string fmt = "{0,4} * {1,24} = {2,-28}\n"; int[] m = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878 }; string[] r = new string[m.Length]; WriteLine(fmt + new string('-', 62), "n", "multiplier", "B10"); var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < m.Length; i++) r[i] = B10(m[i]); sw.Stop(); for (int i = 0; i < m.Length; i++) Write(fmt, m[i], decimal.Parse(r[i]) / m[i], r[i]); Write("\nTook {0}ms", sw.Elapsed.TotalMilliseconds); } }
Modular arithmetic
C sharp|C# from Java
equivalence relation called ''congruence''. For any positive integer p called the ''congruence modulus'', two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that: :a = b + k\,p The corresponding set of multiplicative inverse for this task. Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: :f(x) = x^{100} + x + 1 You will use 13 as the congruence modulus and you will compute f(10). It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
using System; namespace ModularArithmetic { interface IAddition<T> { T Add(T rhs); } interface IMultiplication<T> { T Multiply(T rhs); } interface IPower<T> { T Power(int pow); } interface IOne<T> { T One(); } class ModInt : IAddition<ModInt>, IMultiplication<ModInt>, IPower<ModInt>, IOne<ModInt> { private int modulo; public ModInt(int value, int modulo) { Value = value; this.modulo = modulo; } public int Value { get; } public ModInt One() { return new ModInt(1, modulo); } public ModInt Add(ModInt rhs) { return this + rhs; } public ModInt Multiply(ModInt rhs) { return this * rhs; } public ModInt Power(int pow) { return Pow(this, pow); } public override string ToString() { return string.Format("ModInt({0}, {1})", Value, modulo); } public static ModInt operator +(ModInt lhs, ModInt rhs) { if (lhs.modulo != rhs.modulo) { throw new ArgumentException("Cannot add rings with different modulus"); } return new ModInt((lhs.Value + rhs.Value) % lhs.modulo, lhs.modulo); } public static ModInt operator *(ModInt lhs, ModInt rhs) { if (lhs.modulo != rhs.modulo) { throw new ArgumentException("Cannot add rings with different modulus"); } return new ModInt((lhs.Value * rhs.Value) % lhs.modulo, lhs.modulo); } public static ModInt Pow(ModInt self, int p) { if (p < 0) { throw new ArgumentException("p must be zero or greater"); } int pp = p; ModInt pwr = self.One(); while (pp-- > 0) { pwr *= self; } return pwr; } } class Program { static T F<T>(T x) where T : IAddition<T>, IMultiplication<T>, IPower<T>, IOne<T> { return x.Power(100).Add(x).Add(x.One()); } static void Main(string[] args) { ModInt x = new ModInt(10, 13); ModInt y = F(x); Console.WriteLine("x ^ 100 + x + 1 for x = {0} is {1}", x, y); } } }
Modular exponentiation
C sharp
Find the last '''40''' decimal digits of a^b, where ::* a = 2988348162058574136915891421498819466320163312926952423791023078876139 ::* b = 2351399303373464486466122544523690094744975233415544072992656881240319 A computer is too slow to find the entire value of a^b. Instead, the program must use a fast algorithm for modular exponentiation: a^b \mod m. The algorithm must work for any integers a, b, m, where b \ge 0 and m > 0.
using System; using System.Numerics; class Program { static void Main() { var a = BigInteger.Parse("2988348162058574136915891421498819466320163312926952423791023078876139"); var b = BigInteger.Parse("2351399303373464486466122544523690094744975233415544072992656881240319"); var m = BigInteger.Pow(10, 40); Console.WriteLine(BigInteger.ModPow(a, b, m)); } }
Modular inverse
C sharp
From Wikipedia: In modulo ''m'' is an integer ''x'' such that ::a\,x \equiv 1 \pmod{m}. Or in other words, such that: ::\exists k \in\Z,\qquad a\, x = 1 + k\,m It can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task. ;Task: Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language, compute the modular inverse of 42 modulo 2017.
public class Program { static void Main() { System.Console.WriteLine(42.ModInverse(2017)); } } public static class IntExtensions { public static int ModInverse(this int a, int m) { if (m == 1) return 0; int m0 = m; (int x, int y) = (1, 0); while (a > 1) { int q = a / m; (a, m) = (m, a % m); (x, y) = (y, x - q * y); } return x < 0 ? x + m0 : x; } }
Monads/Maybe monad
C sharp|C#
Demonstrate in your programming language the following: #Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) #Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String #Compose the two functions with bind A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time. A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
using System; namespace RosettaMaybe { // courtesy of https://www.dotnetcurry.com/patterns-practices/1510/maybe-monad-csharp public abstract class Maybe<T> { public sealed class Some : Maybe<T> { public Some(T value) => Value = value; public T Value { get; } } public sealed class None : Maybe<T> { } } class Program { static Maybe<double> MonadicSquareRoot(double x) { if (x >= 0) { return new Maybe<double>.Some(Math.Sqrt(x)); } else { return new Maybe<double>.None(); } } static void Main(string[] args) { foreach (double x in new double[] { 4.0D, 8.0D, -15.0D, 16.23D, -42 }) { Maybe<double> maybe = MonadicSquareRoot(x); if (maybe is Maybe<double>.Some some) { Console.WriteLine($"The square root of {x} is " + some.Value); } else { Console.WriteLine($"Square root of {x} is undefined."); } } } } }
Move-to-front algorithm
C sharp|C#
Given a symbol table of a ''zero-indexed'' array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. ;Encoding algorithm: for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table ;Decoding algorithm: # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table ;Example: Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z''' :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''b'''roood | 1 | 'abcdefghijklmnopqrstuvwxyz' |- | b'''r'''oood | 1 17 | 'bacdefghijklmnopqrstuvwxyz' |- | br'''o'''ood | 1 17 15 | 'rbacdefghijklmnopqstuvwxyz' |- | bro'''o'''od | 1 17 15 0 | 'orbacdefghijklmnpqstuvwxyz' |- | broo'''o'''d | 1 17 15 0 0 | 'orbacdefghijklmnpqstuvwxyz' |- | brooo'''d''' | 1 17 15 0 0 5 | 'orbacdefghijklmnpqstuvwxyz' |} Decoding the indices back to the original symbol order: :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''1''' 17 15 0 0 5 | b | 'abcdefghijklmnopqrstuvwxyz' |- | 1 '''17''' 15 0 0 5 | br | 'bacdefghijklmnopqrstuvwxyz' |- | 1 17 '''15''' 0 0 5 | bro | 'rbacdefghijklmnopqstuvwxyz' |- | 1 17 15 '''0''' 0 5 | broo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 '''0''' 5 | brooo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 0 '''5''' | broood | 'orbacdefghijklmnpqstuvwxyz' |} ;Task: :* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. :* Show the strings and their encoding here. :* Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
using System; using System.Collections.Generic; using System.Text; namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); } private static void moveToFront(int charIndex) { char toFront = symbolTable[charIndex]; for (int j = charIndex; j > 0; j--) { symbolTable[j] = symbolTable[j - 1]; } symbolTable[0] = toFront; } public static int[] Encode(string input) { setSymbolTable(); var output = new List<int>(); foreach (char c in input) { for (int i = 0; i < 26; i++) { if (symbolTable[i] == c) { output.Add(i); moveToFront(i); break; } } } return output.ToArray(); } public static string Decode(int[] input) { setSymbolTable(); var output = new StringBuilder(input.Length); foreach (int n in input) { output.Append(symbolTable[n]); moveToFront(n); } return output.ToString(); } static void Main(string[] args) { string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" }; int[] encoding; foreach (string s in testInputs) { Console.WriteLine($"Encoding for '{s}':"); encoding = Encode(s); foreach (int i in encoding) { Console.Write($"{i} "); } Console.WriteLine($"\nDecoding for '{s}':"); Console.WriteLine($"{Decode(encoding)}\n"); } } } }
Multi-dimensional array
C sharp 3
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: # State the number and extent of each index to the array. # Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. # Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. ;Task: * State if the language supports multi-dimensional arrays in its syntax and usual implementation. * State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. * Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. :* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). * State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. * If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
var array = (int[,,,])Array.CreateInstance(typeof(int), new [] { 5, 4, 3, 2 }, new [] { 10, 10, 10, 10 }); int n = 1; //Note: GetUpperBound is inclusive for (int a = array.GetLowerBound(0); a <= array.GetUpperBound(0); a++) for (int b = array.GetLowerBound(1); b <= array.GetUpperBound(1); b++) for (int c = array.GetLowerBound(2); c <= array.GetUpperBound(2); c++) for (int d = array.GetLowerBound(3); d <= array.GetUpperBound(3); d++) array[a, b, c, d] = n++; //To set the first value, we must now use the lower bounds: array[10, 10, 10, 10] = 999; //As with all arrays, Length gives the TOTAL length. Console.WriteLine("Length: " + array.Length); Console.WriteLine("First 30 elements:"); //The multidimensional array does not implement the generic IEnumerable<int> //so we need to cast the elements. Console.WriteLine(string.Join(" ", array.Cast<int>().Take(30)) + " ...");
Multifactorial
C sharp
The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1). Multifactorials generalize factorials as follows: : n! = n(n-1)(n-2)...(2)(1) : n!! = n(n-2)(n-4)... : n!! ! = n(n-3)(n-6)... : n!! !! = n(n-4)(n-8)... : n!! !! ! = n(n-5)(n-10)... In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: # Write a function that given n and the degree, calculates the multifactorial. # Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. '''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
namespace RosettaCode.Multifactorial { using System; using System.Linq; internal static class Program { private static void Main() { Console.WriteLine(string.Join(Environment.NewLine, Enumerable.Range(1, 5) .Select( degree => string.Join(" ", Enumerable.Range(1, 10) .Select( number => Multifactorial(number, degree)))))); } private static int Multifactorial(int number, int degree) { if (degree < 1) { throw new ArgumentOutOfRangeException("degree"); } var count = 1 + (number - 1) / degree; if (count < 1) { throw new ArgumentOutOfRangeException("number"); } return Enumerable.Range(0, count) .Aggregate(1, (accumulator, index) => accumulator * (number - degree * index)); } } }
Multiple distinct objects
C sharp|C#
Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: [[Closures/Value capture]]
using System; using System.Linq; using System.Collections.Generic; List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();
Multisplit
C sharp
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=". For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. '''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Multisplit { internal static class Program { private static void Main(string[] args) { foreach (var s in "a!===b=!=c".Multisplit(true, "==", "!=", "=")) // Split the string and return the separators. { Console.Write(s); // Write the returned substrings and separators to the console. } Console.WriteLine(); } private static IEnumerable<string> Multisplit(this string s, bool returnSeparators = false, params string[] delimiters) { var currentString = new StringBuilder(); /* Initiate the StringBuilder. This will hold the current string to return * once we find a separator. */ int index = 0; // Initiate the index counter at 0. This tells us our current position in the string to read. while (index < s.Length) // Loop through the string. { // This will get the highest priority separator found at the current index, or null if there are none. string foundDelimiter = (from delimiter in delimiters where s.Length >= index + delimiter.Length && s.Substring(index, delimiter.Length) == delimiter select delimiter).FirstOrDefault(); if (foundDelimiter != null) { yield return currentString.ToString(); // Return the current string. if (returnSeparators) // Return the separator, if the user specified to do so. yield return string.Format("{{\"{0}\", ({1}, {2})}}", foundDelimiter, index, index + foundDelimiter.Length); currentString.Clear(); // Clear the current string. index += foundDelimiter.Length; // Move the index past the current separator. } else { currentString.Append(s[index++]); // Add the character at this index to the current string. } } if (currentString.Length > 0) yield return currentString.ToString(); // If we have anything left over, return it. } } }
Munchausen numbers
C sharp|C#
A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''. ('''Munchausen''' is also spelled: '''Munchhausen'''.) For instance: 3435 = 33 + 44 + 33 + 55 ;Task Find all Munchausen numbers between '''1''' and '''5000'''. ;Also see: :* The OEIS entry: A046253 :* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
Func<char, int> toInt = c => c-'0'; foreach (var i in Enumerable.Range(1,5000) .Where(n => n == n.ToString() .Sum(x => Math.Pow(toInt(x), toInt(x))))) Console.WriteLine(i);
Munchausen numbers
C sharp|C# from Kotlin
A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''. ('''Munchausen''' is also spelled: '''Munchhausen'''.) For instance: 3435 = 33 + 44 + 33 + 55 ;Task Find all Munchausen numbers between '''1''' and '''5000'''. ;Also see: :* The OEIS entry: A046253 :* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
using System; namespace Munchhausen { class Program { static readonly long[] cache = new long[10]; static void Main() { // Allow for 0 ^ 0 to be 0 for (int i = 1; i < 10; i++) { cache[i] = (long)Math.Pow(i, i); } for (long i = 0L; i <= 500_000_000L; i++) { if (IsMunchhausen(i)) { Console.WriteLine(i); } } Console.ReadLine(); } private static bool IsMunchhausen(long n) { long sum = 0, nn = n; do { sum += cache[(int)(nn % 10)]; if (sum > n) { return false; } nn /= 10; } while (nn > 0); return sum == n; } } }
Munchausen numbers
C sharp|C# from Visual Basic .NET
A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''. ('''Munchausen''' is also spelled: '''Munchhausen'''.) For instance: 3435 = 33 + 44 + 33 + 55 ;Task Find all Munchausen numbers between '''1''' and '''5000'''. ;Also see: :* The OEIS entry: A046253 :* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
using System; static class Program { public static void Main() { long sum, ten1 = 0, ten2 = 10; byte [] num; int [] pow = new int[10]; int i, j, n, n1, n2, n3, n4, n5, n6, n7, n8, n9, s2, s3, s4, s5, s6, s7, s8; for (i = 1; i <= 9; i++) { pow[i] = i; for (j = 2; j <= i; j++) pow[i] *= i; } for (n = 1; n <= 11; n++) { for (n9 = 0; n9 <= n; n9++) { for (n8 = 0; n8 <= n - n9; n8++) { for (n7 = 0; n7 <= n - (s8 = n9 + n8); n7++) { for (n6 = 0; n6 <= n - (s7 = s8 + n7); n6++) { for (n5 = 0; n5 <= n - (s6 = s7 + n6); n5++) { for (n4 = 0; n4 <= n - (s5 = s6 + n5); n4++) { for (n3 = 0; n3 <= n - (s4 = s5 + n4); n3++) { for (n2 = 0; n2 <= n - (s3 = s4 + n3); n2++) { for (n1 = 0; n1 <= n - (s2 = s3 + n2); n1++) { sum = n1 * pow[1] + n2 * pow[2] + n3 * pow[3] + n4 * pow[4] + n5 * pow[5] + n6 * pow[6] + n7 * pow[7] + n8 * pow[8] + n9 * pow[9]; if (sum < ten1 || sum >= ten2) continue; num = new byte[10]; foreach (char ch in sum.ToString()) num[Convert.ToByte(ch) - 48] += 1; if (n - (s2 + n1) == num[0] && n1 == num[1] && n2 == num[2] && n3 == num[3] && n4 == num[4] && n5 == num[5] && n6 == num[6] && n7 == num[7] && n8 == num[8] && n9 == num[9]) Console.WriteLine(sum); } } } } } } } } } ten1 = ten2; ten2 *= 10; } } }
N-queens problem
C sharp|C#
right Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''. For the number of solutions for small values of '''N''', see OEIS: A000170. ;Related tasks: * [[A* search algorithm]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[Peaceful chess queen armies]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
=== Roger Hui (1981) Algorithm === From Hui, Roger, The N Queens Problem, APL Quote-Quad, Volume 11, Number 3, 1981-03:- "In a solution, each possible row (column) index must appear exactly once: an index occurring more than once means that two queens are on the same row (column); and the absence of an index means that some other index must occur more than once. Hence, we can specify an arrangement as a permutation of ⍳n , which are the column indices, with the row indices understood to be ⍳n . With this, the number of possibilities is reduced from n!n×n to !n . It remains to eliminate arrangements having two queens on the same diagonal. If two queens occupy the same diagonal, the line connecting them has slope 1 or ¯1 . Conversely, if the line connecting two queens has slope 1 or ¯1 , the two queens share a diagonal. Therefore, we seek to eliminate all permutations specifying a pair of queens where ((change in y) ÷ (change in x)) ∊ 1 ¯1 , or (|change in y) = (|change in x)"
N-queens problem
C sharp
right Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''. For the number of solutions for small values of '''N''', see OEIS: A000170. ;Related tasks: * [[A* search algorithm]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[Peaceful chess queen armies]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
using static System.Linq.Enumerable; using static System.Console; namespace N_Queens { static class Program { static void Main(string[] args) { var n = 8; var domain = Range(0, n).ToArray(); var amb = new Amb.Amb(); var queens = domain.Select(_ => amb.Choose(domain)).ToArray(); amb.Require(() => n == queens.Select(q=> q.Value).Distinct().Count()); amb.Require(() => n == domain.Select(i=> i + queens[i].Value).Distinct().Count()); amb.Require(() => n == domain.Select(i=> i - queens[i].Value).Distinct().Count()); if (amb.Disambiguate()) { WriteLine("Position is row, value is column:-"); WriteLine(string.Join(" ", queens.AsEnumerable())); } else WriteLine("amb is angry"); Read(); } } }
Narcissist
C sharp
Quoting from the Esolangs wiki page: A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]]. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Narcisisst { class Program { public static void Main(string[] args) { const string path = @"E:\Narcisisst"; string[] thisFile = Directory.GetFiles(path , "Program.cs"); StringBuilder sb = new StringBuilder(); foreach (string readLine in File.ReadLines(thisFile[0])) { sb.Append(readLine); sb.Append("\n"); } Console.WriteLine(sb); string input =String.Empty; input = Console.ReadLine(); Console.WriteLine((Regex.IsMatch(sb.ToString(),input))?"accept":"reject"); Console.ReadKey(); } } }
Narcissistic decimal number
C sharp|C#
A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. They are also known as '''Plus Perfect''' numbers. ;An example: ::::* if n is '''153''' ::::* then m, (the number of decimal digits) is '''3''' ::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' ::::* and so '''153''' is a narcissistic decimal number ;Task: Generate and show here the first '''25''' narcissistic decimal numbers. Note: 0^1 = 0, the first in the series. ;See also: * the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers. * MathWorld entry: Narcissistic Number. * Wikipedia entry: Narcissistic number.
using System; namespace Narcissistic { class Narcissistic { public bool isNarcissistic(int z) { if (z < 0) return false; string n = z.ToString(); int t = 0, l = n.Length; foreach (char c in n) t += Convert.ToInt32(Math.Pow(Convert.ToDouble(c - 48), l)); return t == z; } } class Program { static void Main(string[] args) { Narcissistic n = new Narcissistic(); int c = 0, x = 0; while (c < 25) { if (n.isNarcissistic(x)) { if (c % 5 == 0) Console.WriteLine(); Console.Write("{0,7} ", x); c++; } x++; } Console.WriteLine("\n\nPress any key to continue..."); Console.ReadKey(); } } }
Narcissistic decimal number
C sharp|C# from FreeBASIC
A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. They are also known as '''Plus Perfect''' numbers. ;An example: ::::* if n is '''153''' ::::* then m, (the number of decimal digits) is '''3''' ::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' ::::* and so '''153''' is a narcissistic decimal number ;Task: Generate and show here the first '''25''' narcissistic decimal numbers. Note: 0^1 = 0, the first in the series. ;See also: * the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers. * MathWorld entry: Narcissistic Number. * Wikipedia entry: Narcissistic number.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Numerics; static class Program { public static void nar(int max, bool only1 = false) { int n, n1, n2, n3, n4, n5, n6, n7, n8, n9; int[] d; // digits tally char [] bs; // BigInteger String List<BigInteger> res = new List<BigInteger>(); // per n digits results BigInteger[,] p = new BigInteger[10, max + 1]; // powers array // BigIntegers for intermediate results BigInteger x2, x3, x4, x5, x6, x7, x8, x9; for (n = only1 ? max : 1; n <= max; n++) // main loop { for (int i = 1; i <= 9; i++) // init powers array for this n { p[i, 1] = BigInteger.Pow(i, n); for (int j = 2; j <= n; j++) p[i, j] = p[i, 1] * j; } for (n9 = n; n9 >= 0; n9--) // nested loops... { x9 = p[9, n9]; for (n8 = n - n9; n8 >= 0; n8--) { x8 = x9 + p[8, n8]; for (n7 = n - n9 - n8; n7 >= 0; n7--) { x7 = x8 + p[7, n7]; for (n6 = n - n9 - n8 - n7; n6 >= 0; n6--) { x6 = x7 + p[6, n6]; for (n5 = n - n9 - n8 - n7 - n6; n5 >= 0; n5--) { x5 = x6 + p[5, n5]; for (n4 = n - n9 - n8 - n7 - n6 - n5; n4 >= 0; n4--) { x4 = x5 + p[4, n4]; for (n3 = n - n9 - n8 - n7 - n6 - n5 - n4; n3 >= 0; n3--) { x3 = x4 + p[3, n3]; for (n2 = n - n9 - n8 - n7 - n6 - n5 - n4 - n3; n2 >= 0; n2--) { x2 = x3 + p[2, n2]; for (n1 = n - n9 - n8 - n7 - n6 - n5 - n4 - n3 - n2; n1 >= 0; n1--) { bs = (x2 + n1).ToString().ToCharArray(); switch (bs.Length.CompareTo(n)) { // Since all the for/next loops step down, when the digit count // becomes smaller than n, it's time to try the next n value. case -1: { goto Next_n; } case 0: { d = new int[10]; foreach (char c in bs) d[c - 48] += 1; if (n9 == d[9] && n8 == d[8] && n7 == d[7] && n6 == d[6] && n5 == d[5] && n4 == d[4] && n3 == d[3] && n2 == d[2] && n1 == d[1] && n - n9 - n8 - n7 - n6 - n5 - n4 - n3 - n2 - n1 == d[0]) res.Add(BigInteger.Parse(new string(bs))); break; } } } } } } } } } } } Next_n: if (only1) { Console.Write("{0} ", n); lock (resu) resu.AddRange(res); return; } else { res.Sort(); Console.WriteLine("{2,3} {0,3}: {1}", Math.Ceiling((DateTime.Now - st).TotalSeconds), string.Join(" ", res), n); res.Clear(); } } } private static DateTime st = default(DateTime); private static List<BigInteger> resu = new List<BigInteger>(); private static bool para = true; // parallel (default) or sequential calcualtion private static int lim = 7; // this is the number of digits to calcualate, not the nth entry. // for up to the 25th item, use lim = 7 digits. // for all 89 items, use lim = 39 digits. public static void Main(string[] args) { if (args.Count() > 0) { int t = lim; int.TryParse(args[0], out t); if (t < 1) t = 1; // number of digits must be > 0 if (t > 61) t = 61; // no point when lim * math.pow(9, lim) < math.pow(10, lim - 1) lim = t; // default is parallel, will do sequential when any 2nd command line parameter is present. para = !(args.Count() > 1); } st = DateTime.Now; if (para) { Console.Write("Calculations in parallel... "); // starts the bigger ones first Parallel.ForEach(Enumerable.Range(1, lim).Reverse().ToArray(), n => { nar(n, true); } ); resu.Sort(); int[] g = Enumerable.Range(1, resu.Count).ToArray(); var both = g.Zip(resu, (a, b) => a.ToString() + " " + b.ToString()); Console.WriteLine("\n{0}", string.Join("\n", both)); } else { Console.WriteLine("Sequential calculations:"); nar(lim); } Console.WriteLine("Total elasped: {0} seconds", (DateTime.Now - st).TotalSeconds); if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey(); } }
Negative base numbers
C sharp|C# from Java
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia ;Task: *Encode the decimal number 10 as negabinary (expect 11110) *Encode the decimal number 146 as negaternary (expect 21102) *Encode the decimal number 15 as negadecimal (expect 195) *In each of the above cases, convert the encoded number back to decimal. ;extra credit: * supply an integer, that when encoded to base -62 (or something "higher"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NegativeBaseNumbers { class Program { const string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string EncodeNegativeBase(long n, int b) { if (b < -62 || b > -1) { throw new ArgumentOutOfRangeException("b"); } if (n == 0) { return "0"; } StringBuilder output = new StringBuilder(); long nn = n; while (nn != 0) { int rem = (int)(nn % b); nn /= b; if (rem < 0) { nn++; rem -= b; } output.Append(DIGITS[rem]); } return new string(output.ToString().Reverse().ToArray()); } static long DecodeNegativeBase(string ns, int b) { if (b < -62 || b > -1) { throw new ArgumentOutOfRangeException("b"); } if (ns == "0") { return 0; } long total = 0; long bb = 1; for (int i = ns.Length - 1; i >= 0; i--) { char c = ns[i]; total += DIGITS.IndexOf(c) * bb; bb *= b; } return total; } static void Main(string[] args) { List<Tuple<long, int>> nbl = new List<Tuple<long, int>>() { new Tuple<long, int>(10,-2), new Tuple<long, int>(146,-3), new Tuple<long, int>(15,-10), new Tuple<long, int>(-34025238427,-62), }; foreach (var p in nbl) { string ns = EncodeNegativeBase(p.Item1, p.Item2); Console.WriteLine("{0,12} encoded in base {1,-3} = {2}", p.Item1, p.Item2, ns); long n = DecodeNegativeBase(ns, p.Item2); Console.WriteLine("{0,12} decoded in base {1,-3} = {2}", ns, p.Item2, n); Console.WriteLine(); } } } }
Nested function
C sharp|C#
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. ;Task: Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. ;References: :* Nested function
string MakeList(string separator) { int counter = 1; Func<string, string> makeItem = item => counter++ + separator + item + "\n"; return makeItem("first") + makeItem("second") + makeItem("third"); } Console.WriteLine(MakeList(". "));
Nim game
C#
Nim is a simple game where the second player-if they know the trick-will always win. The game has only 3 rules: ::* start with '''12''' tokens ::* each player takes '''1, 2, or 3''' tokens in turn ::* the player who takes the last token wins. To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. ;Task: Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
using System; namespace nimGame { class Program { static void Main(string[] args) { Console.WriteLine("There are twelve tokens.\n" + "You can take 1, 2, or 3 on your turn.\n" + "Whoever takes the last token wins.\n"); int tokens = 12; while (tokens > 0) { Console.WriteLine("There are " + tokens + " remaining."); Console.WriteLine("How many do you take?"); int playertake = Convert.ToInt32(Console.ReadLine()); if (playertake < 1 | playertake > 3) { Console.WriteLine("1, 2, or 3 only."); } else { tokens -= playertake; Console.WriteLine("I take " + (4 - playertake) + "."); tokens -= (4 - playertake); } } Console.WriteLine("I win again."); Console.ReadLine(); } } }
Nonoblock
C sharp
Nonogram puzzle. ;Given: * The number of cells in a row. * The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. ;Task: * show all possible positions. * show the number of positions of the blocks for the following cases within the row. * show all output on this page. * use a "neat" diagram of the block positions. ;Enumerate the following configurations: # '''5''' cells and '''[2, 1]''' blocks # '''5''' cells and '''[]''' blocks (no blocks) # '''10''' cells and '''[8]''' blocks # '''15''' cells and '''[2, 3, 2, 3]''' blocks # '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible) ;Example: Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# ;An algorithm: * Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). * The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. * for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block. (This is the algorithm used in the [[Nonoblock#Python]] solution). ;Reference: * The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.
using System; using System.Linq; using System.Text; public static class Nonoblock { public static void Main() { Positions(5, 2,1); Positions(5); Positions(10, 8); Positions(15, 2,3,2,3); Positions(5, 2,3); } public static void Positions(int cells, params int[] blocks) { if (cells < 0 || blocks == null || blocks.Any(b => b < 1)) throw new ArgumentOutOfRangeException(); Console.WriteLine($"{cells} cells with [{string.Join(", ", blocks)}]"); if (blocks.Sum() + blocks.Length - 1 > cells) { Console.WriteLine("No solution"); return; } var spaces = new int[blocks.Length + 1]; int total = -1; for (int i = 0; i < blocks.Length; i++) { total += blocks[i] + 1; spaces[i+1] = total; } spaces[spaces.Length - 1] = cells - 1; var sb = new StringBuilder(string.Join(".", blocks.Select(b => new string('#', b))).PadRight(cells, '.')); Iterate(sb, spaces, spaces.Length - 1, 0); Console.WriteLine(); } private static void Iterate(StringBuilder output, int[] spaces, int index, int offset) { Console.WriteLine(output.ToString()); if (index <= 0) return; int count = 0; while (output[spaces[index] - offset] != '#') { count++; output.Remove(spaces[index], 1); output.Insert(spaces[index-1], '.'); spaces[index-1]++; Iterate(output, spaces, index - 1, 1); } if (offset == 0) return; spaces[index-1] -= count; output.Remove(spaces[index-1], count); output.Insert(spaces[index] - count, ".", count); } }
Nonogram solver
C sharp
nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. ;Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" ;Task For this task, try to solve the 4 problems below, read from a "nonogram_problems.txt" file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM '''Extra credit''': generate nonograms with unique solutions, of desired height and width. This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples). ; Related tasks * [[Nonoblock]]. ;See also * Arc Consistency Algorithm * http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) * http://twanvl.nl/blog/haskell/Nonograms (Haskell) * http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet //Unused functionality elided. { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
Numbers which are not the sum of distinct squares
C#|CSharp
Integer squares are the set of integers multiplied by themselves: 1 x 1 = '''1''', 2 x 2 = '''4''', 3 x 3 = '''9''', etc. ( 1, 4, 9, 16 ... ) Most positive integers can be generated as the sum of 1 or more distinct integer squares. '''1''' == 1 '''5''' == 4 + 1 '''25''' == 16 + 9 '''77''' == 36 + 25 + 16 '''103''' == 49 + 25 + 16 + 9 + 4 Many can be generated in multiple ways: '''90''' == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9 '''130''' == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9 The number of positive integers that '''cannot''' be generated by any combination of distinct squares is in fact finite: 2, 3, 6, 7, etc. ;Task Find and show here, on this page, '''every''' positive integer than cannot be generated as the sum of distinct squares. Do not use magic numbers or pre-determined limits. Justify your answer mathematically. ;See also * OEIS: A001422 Numbers which are not the sum of distinct squares
using System; using System.Collections.Generic; using System.Linq; class Program { // recursively permutates the list of squares to seek a matching sum static bool soms(int n, IEnumerable<int> f) { if (n <= 0) return false; if (f.Contains(n)) return true; switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true; case -1: var rf = f.Reverse().Skip(1).ToList(); return soms(n - f.Last(), rf) || soms(n, rf); } return false; } static void Main() { var sw = System.Diagnostics.Stopwatch.StartNew(); int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>(); var sf = "stopped checking after finding {0} sequential non-gaps after the final gap of {1}"; for (i = 1, g = 1; g >= (i >> 1); i++) { if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i); if (!soms(i, s)) a.Add(g = i); } sw.Stop(); Console.WriteLine("Numbers which are not the sum of distinct squares:"); Console.WriteLine(string.Join(", ", a)); Console.WriteLine(sf, i - g, g); Console.Write("found {0} total in {1} ms", a.Count, sw.Elapsed.TotalMilliseconds); } }