title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Numbers which are the cube roots of the product of their proper divisors | C#|CSharp | Example
Consider the number 24. Its proper divisors are: 1, 2, 3, 4, 6, 8 and 12. Their product is 13,824 and the cube root of this is 24. So 24 satisfies the definition in the task title.
;Task
Compute and show here the first '''50''' positive integers which are the cube roots of the product of their proper divisors.
Also show the '''500th''' and '''5,000th''' such numbers.
;Stretch
Compute and show the '''50,000th''' such number.
;Reference
* OEIS:A111398 - Numbers which are the cube roots of the product of their proper divisors.
;Note
OEIS considers 1 to be the first number in this sequence even though, strictly speaking, it has no proper divisors. Please therefore do likewise.
| using System;
class Program {
static bool dc8(uint n) {
uint res = 1, count, p, d;
for ( ; (n & 1) == 0; n >>= 1) res++;
for (count = 1; n % 3 == 0; n /= 3) count++;
for (p = 5, d = 4; p * p <= n; p += d = 6 - d)
for (res *= count, count = 1; n % p == 0; n /= p) count++;
return n > 1 ? res * count == 4 : res * count == 8;
}
static void Main(string[] args) {
Console.WriteLine("First 50 numbers which are the cube roots of the products of "
+ "their proper divisors:");
for (uint n = 1, count = 0, lmt = 500; count < 5e6; ++n) if (n == 1 || dc8(n))
if (++count <= 50) Console.Write("{0,3}{1}",n, count % 10 == 0 ? '\n' : ' ');
else if (count == lmt) Console.Write("{0,16:n0}th: {1:n0}\n", count, n, lmt *= 10);
}
} |
Old lady swallowed a fly | C sharp|C# | Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
| using System;
namespace OldLady
{
internal class Program
{
private const string reason = "She swallowed the {0} to catch the {1}";
private static readonly string[] creatures = {"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"};
private static readonly string[] comments =
{
"I don't know why she swallowed that fly.\nPerhaps she'll die\n",
"That wiggled and jiggled and tickled inside her",
"How absurd, to swallow a bird",
"Imagine that. She swallowed a cat",
"What a hog to swallow a dog",
"She just opened her throat and swallowed that goat",
"I don't know how she swallowed that cow",
"She's dead of course"
};
private static void Main()
{
int max = creatures.Length;
for (int i = 0; i < max; i++)
{
Console.WriteLine("There was an old lady who swallowed a {0}", creatures[i]);
Console.WriteLine(comments[i]);
for (int j = i; j > 0 && i < max - 1; j--)
{
Console.WriteLine(reason, creatures[j], creatures[j - 1]);
if (j == 1)
{
Console.WriteLine(comments[j - 1]);
}
}
}
Console.Read();
}
}
} |
One of n lines in a file | C sharp|C# | A method of choosing a line randomly from a file:
::* Without reading the file more than once
::* When substantial parts of the file cannot be held in memory
::* Without knowing how many lines are in the file
Is to:
::* keep the first line of the file as a possible choice, then
::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
::* ...
::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
::* Return the computed possible choice when no further lines exist in the file.
;Task:
# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.
# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.
# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| class Program
{
private static Random rnd = new Random();
public static int one_of_n(int n)
{
int currentChoice = 1;
for (int i = 2; i <= n; i++)
{
double outerLimit = 1D / (double)i;
if (rnd.NextDouble() < outerLimit)
currentChoice = i;
}
return currentChoice;
}
static void Main(string[] args)
{
Dictionary<int, int> results = new Dictionary<int, int>();
for (int i = 1; i < 11; i++)
results.Add(i, 0);
for (int i = 0; i < 1000000; i++)
{
int result = one_of_n(10);
results[result] = results[result] + 1;
}
for (int i = 1; i < 11; i++)
Console.WriteLine("{0}\t{1}", i, results[i]);
Console.ReadLine();
}
}
|
Operator precedence | C sharp|C# | Operators in C and C++}}
;Task:
Provide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| [http://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/ MSDN documentation]
|
Palindrome dates | C sharp | Today ('''2020-02-02''', at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the '''yyyy-mm-dd''' format but, unusually, also for countries which use the '''dd-mm-yyyy''' format.
;Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.
| using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
static void Main()
{
foreach (var date in PalindromicDates(2021).Take(15)) WriteLine(date.ToString("yyyy-MM-dd"));
}
public static IEnumerable<DateTime> PalindromicDates(int startYear) {
for (int y = startYear; ; y++) {
int m = Reverse(y % 100);
int d = Reverse(y / 100);
if (IsValidDate(y, m, d, out var date)) yield return date;
}
int Reverse(int x) => x % 10 * 10 + x / 10;
bool IsValidDate(int y, int m, int d, out DateTime date) => DateTime.TryParse($"{y}-{m}-{d}", out date);
}
} |
Pangram checker | C sharp|C# | A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: ''The quick brown fox jumps over the lazy dog''.
;Task:
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
;Related tasks:
:* determine if a string has all the same characters
:* determine if a string has all unique characters
| using System;
namespace PangrammChecker
{
public class PangrammChecker
{
public static bool IsPangram(string str)
{
bool[] isUsed = new bool[26];
int ai = (int)'a';
int total = 0;
for (CharEnumerator en = str.ToLower().GetEnumerator(); en.MoveNext(); )
{
int d = (int)en.Current - ai;
if (d >= 0 && d < 26)
if (!isUsed[d])
{
isUsed[d] = true;
total++;
}
}
return (total == 26);
}
}
class Program
{
static void Main(string[] args)
{
string str1 = "The quick brown fox jumps over the lazy dog.";
string str2 = "The qu1ck brown fox jumps over the lazy d0g.";
Console.WriteLine("{0} is {1}a pangram", str1,
PangrammChecker.IsPangram(str1)?"":"not ");
Console.WriteLine("{0} is {1}a pangram", str2,
PangrammChecker.IsPangram(str2)?"":"not ");
Console.WriteLine("Press Return to exit");
Console.ReadLine();
}
}
} |
Parsing/RPN calculator algorithm | C sharp|C# | Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.
* Assume an input of a correct, space separated, string of tokens of an RPN expression
* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
* Print or display the output here
;Notes:
* '''^''' means exponentiation in the expression above.
* '''/''' means division.
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).
* [[Parsing/RPN to infix conversion]].
* [[Arithmetic evaluation]].
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Threading;
namespace RPNEvaluator
{
class RPNEvaluator
{
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
string rpn = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
Console.WriteLine("{0}\n", rpn);
decimal result = CalculateRPN(rpn);
Console.WriteLine("\nResult is {0}", result);
}
static decimal CalculateRPN(string rpn)
{
string[] rpnTokens = rpn.Split(' ');
Stack<decimal> stack = new Stack<decimal>();
decimal number = decimal.Zero;
foreach (string token in rpnTokens)
{
if (decimal.TryParse(token, out number))
{
stack.Push(number);
}
else
{
switch (token)
{
case "^":
case "pow":
{
number = stack.Pop();
stack.Push((decimal)Math.Pow((double)stack.Pop(), (double)number));
break;
}
case "ln":
{
stack.Push((decimal)Math.Log((double)stack.Pop(), Math.E));
break;
}
case "sqrt":
{
stack.Push((decimal)Math.Sqrt((double)stack.Pop()));
break;
}
case "*":
{
stack.Push(stack.Pop() * stack.Pop());
break;
}
case "/":
{
number = stack.Pop();
stack.Push(stack.Pop() / number);
break;
}
case "+":
{
stack.Push(stack.Pop() + stack.Pop());
break;
}
case "-":
{
number = stack.Pop();
stack.Push(stack.Pop() - number);
break;
}
default:
Console.WriteLine("Error in CalculateRPN(string) Method!");
break;
}
}
PrintState(stack);
}
return stack.Pop();
}
static void PrintState(Stack<decimal> stack)
{
decimal[] arr = stack.ToArray();
for (int i = arr.Length - 1; i >= 0; i--)
{
Console.Write("{0,-8:F3}", arr[i]);
}
Console.WriteLine();
}
}
} |
Parsing/RPN to infix conversion | C sharp|C# from Java | Create a program that takes an infix notation.
* Assume an input of a correct, space separated, string of tokens
* Generate a space separated output string representing the same expression in infix notation
* Show how the major datastructure of your algorithm changes with each new token parsed.
* Test with the following input RPN strings then print and display the output here.
:::::{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}
* Operator precedence and operator associativity is given in this table:
::::::::{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* Postfix to infix from the RubyQuiz site.
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace PostfixToInfix
{
class Program
{
class Operator
{
public Operator(char t, int p, bool i = false)
{
Token = t;
Precedence = p;
IsRightAssociative = i;
}
public char Token { get; private set; }
public int Precedence { get; private set; }
public bool IsRightAssociative { get; private set; }
}
static IReadOnlyDictionary<char, Operator> operators = new Dictionary<char, Operator>
{
{ '+', new Operator('+', 2) },
{ '-', new Operator('-', 2) },
{ '/', new Operator('/', 3) },
{ '*', new Operator('*', 3) },
{ '^', new Operator('^', 4, true) }
};
class Expression
{
public String ex;
public Operator op;
public Expression(String e)
{
ex = e;
}
public Expression(String e1, String e2, Operator o)
{
ex = String.Format("{0} {1} {2}", e1, o.Token, e2);
op = o;
}
}
static String PostfixToInfix(String postfix)
{
var stack = new Stack<Expression>();
foreach (var token in Regex.Split(postfix, @"\s+"))
{
char c = token[0];
var op = operators.FirstOrDefault(kv => kv.Key == c).Value;
if (op != null && token.Length == 1)
{
Expression rhs = stack.Pop();
Expression lhs = stack.Pop();
int opPrec = op.Precedence;
int lhsPrec = lhs.op != null ? lhs.op.Precedence : int.MaxValue;
int rhsPrec = rhs.op != null ? rhs.op.Precedence : int.MaxValue;
if ((lhsPrec < opPrec || (lhsPrec == opPrec && c == '^')))
lhs.ex = '(' + lhs.ex + ')';
if ((rhsPrec < opPrec || (rhsPrec == opPrec && c != '^')))
rhs.ex = '(' + rhs.ex + ')';
stack.Push(new Expression(lhs.ex, rhs.ex, op));
}
else
{
stack.Push(new Expression(token));
}
// print intermediate result
Console.WriteLine("{0} -> [{1}]", token,
string.Join(", ", stack.Reverse().Select(e => e.ex)));
}
return stack.Peek().ex;
}
static void Main(string[] args)
{
string[] inputs = { "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^" };
foreach (var e in inputs)
{
Console.WriteLine("Postfix : {0}", e);
Console.WriteLine("Infix : {0}", PostfixToInfix(e));
Console.WriteLine(); ;
}
Console.ReadLine();
}
}
} |
Parsing/Shunting-yard algorithm | C sharp 7.0 | Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
* Assume an input of a correct, space separated, string of tokens representing an infix expression
* Generate a space separated output string representing the RPN
* Test with the input string:
:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
* print and display the output here.
* Operator precedence is given in this table:
:{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
;Note
The handling of functions and arguments is not required.
;See also:
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* [[Parsing/RPN to infix conversion]].
| using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
Console.WriteLine(infix.ToPostfix());
}
}
public static class ShuntingYard
{
private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators
= new (string symbol, int precedence, bool rightAssociative) [] {
("^", 4, true),
("*", 3, false),
("/", 3, false),
("+", 2, false),
("-", 2, false)
}.ToDictionary(op => op.symbol);
public static string ToPostfix(this string infix) {
string[] tokens = infix.Split(' ');
var stack = new Stack<string>();
var output = new List<string>();
foreach (string token in tokens) {
if (int.TryParse(token, out _)) {
output.Add(token);
Print(token);
} else if (operators.TryGetValue(token, out var op1)) {
while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {
int c = op1.precedence.CompareTo(op2.precedence);
if (c < 0 || !op1.rightAssociative && c <= 0) {
output.Add(stack.Pop());
} else {
break;
}
}
stack.Push(token);
Print(token);
} else if (token == "(") {
stack.Push(token);
Print(token);
} else if (token == ")") {
string top = "";
while (stack.Count > 0 && (top = stack.Pop()) != "(") {
output.Add(top);
}
if (top != "(") throw new ArgumentException("No matching left parenthesis.");
Print(token);
}
}
while (stack.Count > 0) {
var top = stack.Pop();
if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis.");
output.Add(top);
}
Print("pop");
return string.Join(" ", output);
//Yikes!
void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}");
//A little more readable?
void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]");
}
} |
Pascal's triangle/Puzzle | C sharp|C# | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).
;Task:
Write a program to find a solution to this puzzle.
| using System;
namespace Pyramid_of_Numbers
{
class Program
{
public static void Main(string[] args)
{
// Set console properties
Console.Title = " Pyramid of Numbers / Pascal's triangle Puzzle";
Console.SetBufferSize(80,1000);
Console.SetWindowSize(80,60);
Console.ForegroundColor = ConsoleColor.Green;
// Main Program Loop
ConsoleKeyInfo k = new ConsoleKeyInfo('Y', ConsoleKey.Y,true,true,true);
while (k.Key == ConsoleKey.Y)
{
Console.Clear();
Console.WriteLine("----------------------------------------------");
Console.WriteLine(" Pyramid of Numbers / Pascal's triangle Puzzle");
Console.WriteLine("----------------------------------------------");
Console.WriteLine();
//
// Declare new Pyramid array
//
int r = 5;// Number of rows
int [,] Pyramid = new int[r,r];
// Set initial Pyramid values
for (int i = 0; i < r; i++)
{
for(int j = 0; j < r; j++)
{
Pyramid[i,j] = 0;
}
}
// Show info on created array
Console.WriteLine(" Pyramid has " + r + " rows");
Console.WriteLine("--------------------------------------------");
// Enter Pyramid values
for(int i = 0; i <= r-1; i++)
{
Console.WriteLine(" Enter " + (i+1).ToString() + ". row values:");
Console.WriteLine("--------------------------------------------");
for(int j = 0; j < i+1; j++)
{
Console.Write(" " + (j+1).ToString() + ". value = ");
int v = int.Parse(Console.ReadLine());
Pyramid[i,j] = v;
}
Console.WriteLine("--------------------------------------------");
}
//
// Show initial Pyramid values
//
Console.WriteLine();
Console.WriteLine(" Initial Pyramid Values ");
Console.WriteLine();
// Show Pyramid values
for(int i = 0; i <= r-1; i++)
{
for(int j = 0; j < i+1; j++)
{
Console.Write("{0,4}",Pyramid[i,j]);
}
Console.WriteLine();
}
Console.WriteLine("--------------------------------------------");
// Find solution
Solve_Pyramid(Pyramid);
Console.WriteLine();
Console.Write(" Start new calculation <Y/N> . . . ");
k = Console.ReadKey(true);
}
}
//
// Solve Function
//
public static void Solve_Pyramid(int [,] Pyramid)
{
int r = 5; // Number of rows
// Calculate Y
int a = Pyramid[r-1,1];
int b = Pyramid[r-1,3];
int c = Pyramid[0,0];
int y = (c - (4*a) - (4*b))/7;
Pyramid[r-1,2] = y;
// Create copy of Pyramid
int [,] Pyramid_Copy = new int[r,r];
Array.Copy(Pyramid,Pyramid_Copy,r*r);
int n = 0; // solution counter
for(int x = 0; x < y + 1; x++)
{
for(int z = 0; z < y + 1; z++)
{
if( (x+z) == y)
{
Pyramid[r-1,0] = x;
Pyramid[r-1,r-1] = z;
// Recalculate Pyramid values
for(int i = r-1; i > 0; i--)
{
for(int j = 0; j < i; j++)
{
Pyramid[i-1,j] = Pyramid[i,j]+Pyramid[i,j+1];
}
}
// Compare Pyramid values
bool solved = true;
for(int i = 0; i < r-1; i++)
{
for(int j = 0; j < i+1; j++)
{
if(Pyramid_Copy[i,j]>0)
{
if(Pyramid[i,j] != Pyramid_Copy[i,j])
{
solved = false;
i = r;
break;
}
}
}
}
if(solved)
{
n++;
Console.WriteLine();
Console.WriteLine(" Solved Pyramid Values no." + n);
Console.WriteLine();
// Show Pyramid values
for(int i = 0; i <= r-1; i++)
{
for(int j = 0; j < i+1; j++)
{
Console.Write("{0,4}",Pyramid[i,j]);
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine(" X = " + Pyramid[r-1,0] + " " +
" Y = " + Pyramid[r-1,2] + " " +
" Z = " + Pyramid[r-1,4]);
Console.WriteLine();
Console.WriteLine("--------------------------------------------");
}
Array.Copy(Pyramid_Copy,Pyramid,r*r);
}
}
}
if(n == 0)
{
Console.WriteLine();
Console.WriteLine(" Pyramid has no solution ");
Console.WriteLine();
}
}
}
}
|
Pascal matrix generation | C sharp | A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
;Task:
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
;Note:
The [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| using System;
public static class PascalMatrixGeneration
{
public static void Main() {
Print(GenerateUpper(5));
Console.WriteLine();
Print(GenerateLower(5));
Console.WriteLine();
Print(GenerateSymmetric(5));
}
static int[,] GenerateUpper(int size) {
int[,] m = new int[size, size];
for (int c = 0; c < size; c++) m[0, c] = 1;
for (int r = 1; r < size; r++) {
for (int c = r; c < size; c++) {
m[r, c] = m[r-1, c-1] + m[r, c-1];
}
}
return m;
}
static int[,] GenerateLower(int size) {
int[,] m = new int[size, size];
for (int r = 0; r < size; r++) m[r, 0] = 1;
for (int c = 1; c < size; c++) {
for (int r = c; r < size; r++) {
m[r, c] = m[r-1, c-1] + m[r-1, c];
}
}
return m;
}
static int[,] GenerateSymmetric(int size) {
int[,] m = new int[size, size];
for (int i = 0; i < size; i++) m[0, i] = m[i, 0] = 1;
for (int r = 1; r < size; r++) {
for (int c = 1; c < size; c++) {
m[r, c] = m[r-1, c] + m[r, c-1];
}
}
return m;
}
static void Print(int[,] matrix) {
string[,] m = ToString(matrix);
int width = m.Cast<string>().Select(s => s.Length).Max();
int rows = matrix.GetLength(0), columns = matrix.GetLength(1);
for (int row = 0; row < rows; row++) {
Console.WriteLine("|" + string.Join(" ", Range(0, columns).Select(column => m[row, column].PadLeft(width, ' '))) + "|");
}
}
static string[,] ToString(int[,] matrix) {
int rows = matrix.GetLength(0), columns = matrix.GetLength(1);
string[,] m = new string[rows, columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
m[r, c] = matrix[r, c].ToString();
}
}
return m;
}
} |
Password generator | C sharp|C# | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a --> z
upper-case letters: A --> Z
digits: 0 --> 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include ''at least one'' (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
::::* capital eye, lowercase ell, the digit one
::::* capital oh, the digit zero
::::* the digit five, capital ess
::::* the digit two, capital zee
| using System;
using System.Linq;
class Program
{
const string Lower = "abcdefghijklmnopqrstuvwxyz";
const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string Digits = "0123456789";
const string Symbols = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
static readonly string[] Full = {Lower, Upper, Digits, Symbols, Lower + Upper + Digits + Symbols};
const string Similar = "Il1O05S2Z";
static readonly string[] Excluded = Full.Select(x => new string(x.Except(Similar).ToArray())).ToArray();
static Random _rng = new Random();
static string[] _symbolSet = Full;
static void Main(string[] args)
{
int length = 12, count = 1;
try
{
foreach (var x in args.Select(arg => arg.Split(':')))
{
switch (x[0])
{
case "-l": length = int.Parse(x[1]); break;
case "-c": count = int.Parse(x[1]); break;
case "-s": _rng = new Random(x[1].GetHashCode()); break;
case "-x": _symbolSet = bool.Parse(x[1]) ? Excluded : Full; break;
default: throw new FormatException("Could not parse arguments");
}
}
}
catch { ShowUsage(); return; }
try
{
for (int i = 0; i < count; i++)
Console.WriteLine(GeneratePass(length));
}
catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); }
}
static void ShowUsage()
{
Console.WriteLine("Usage: PASSGEN [-l:length] [-c:count] [-s:seed] [-x:(true|false)]");
Console.WriteLine("\t-l: the length of the generated passwords");
Console.WriteLine("\t-c: the number of passwords to generate");
Console.WriteLine("\t-s: seed for the random number generator");
Console.WriteLine("\t-x: exclude similar characters: " + Similar);
Console.WriteLine("Example: PASSGEN -l:10 -c:5 -s:\"Sample Seed\" -x:true");
}
static string GeneratePass(int length)
{
var minLength = _symbolSet.Length - 1;
if(length < minLength)
throw new Exception("password length must be " + minLength + " or greater");
int[] usesRemaining = Enumerable.Repeat(1, _symbolSet.Length).ToArray();
usesRemaining[minLength] = length - minLength;
var password = new char[length];
for (int ii = 0; ii < length; ii++)
{
int set = _rng.Next(0, _symbolSet.Length);
if (usesRemaining[set] > 0)
{
usesRemaining[set]--;
password[ii] = _symbolSet[set][_rng.Next(0, _symbolSet[set].Length)];
}
else ii--;
}
return new string(password);
}
} |
Peaceful chess queen armies | C sharp|C# from D | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.
\
|
/
=
=
=
=
/
|
\
/
|
\
|
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.
;Task:
# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
# Display here results for the m=4, n=5 case.
;References:
* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
* A250000 OEIS
| using System;
using System.Collections.Generic;
namespace PeacefulChessQueenArmies {
using Position = Tuple<int, int>;
enum Piece {
Empty,
Black,
White
}
class Program {
static bool IsAttacking(Position queen, Position pos) {
return queen.Item1 == pos.Item1
|| queen.Item2 == pos.Item2
|| Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2);
}
static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) {
if (m == 0) {
return true;
}
bool placingBlack = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
var pos = new Position(i, j);
foreach (var queen in pBlackQueens) {
if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) {
goto inner;
}
}
foreach (var queen in pWhiteQueens) {
if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) {
goto inner;
}
}
if (placingBlack) {
pBlackQueens.Add(pos);
placingBlack = false;
} else {
pWhiteQueens.Add(pos);
if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.RemoveAt(pBlackQueens.Count - 1);
pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1);
placingBlack = true;
}
inner: { }
}
}
if (!placingBlack) {
pBlackQueens.RemoveAt(pBlackQueens.Count - 1);
}
return false;
}
static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) {
var board = new Piece[n * n];
foreach (var queen in blackQueens) {
board[queen.Item1 * n + queen.Item2] = Piece.Black;
}
foreach (var queen in whiteQueens) {
board[queen.Item1 * n + queen.Item2] = Piece.White;
}
for (int i = 0; i < board.Length; i++) {
if (i != 0 && i % n == 0) {
Console.WriteLine();
}
switch (board[i]) {
case Piece.Black:
Console.Write("B ");
break;
case Piece.White:
Console.Write("W ");
break;
case Piece.Empty:
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
Console.Write(" ");
} else {
Console.Write("# ");
}
break;
}
}
Console.WriteLine("\n");
}
static void Main() {
var nms = new int[,] {
{2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
{5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
{6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
{7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
};
for (int i = 0; i < nms.GetLength(0); i++) {
Console.WriteLine("{0} black and {0} white queens on a {1} x {1} board:", nms[i, 1], nms[i, 0]);
List<Position> blackQueens = new List<Position>();
List<Position> whiteQueens = new List<Position>();
if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) {
PrintBoard(nms[i, 0], blackQueens, whiteQueens);
} else {
Console.WriteLine("No solution exists.\n");
}
}
}
}
} |
Pentomino tiling | C sharp|C# from Java | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I
I L N Y
FF I L NN PP TTT V W X YY ZZ
FF I L N PP T U U V WW XXX Y Z
F I LL N P T UUU VVV WW X Y ZZ
A Pentomino tiling is an example of an exact cover problem and can take on many forms.
A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered
by the 12 pentomino shapes, without overlaps, with every shape only used once.
The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.
;Task
Create an 8 by 8 tiling and print the result.
;Example
F I I I I I L N
F F F L L L L N
W F - X Z Z N N
W W X X X Z N V
T W W X - Z Z V
T T T P P V V V
T Y - P P U U U
Y Y Y Y P U - U
;Related tasks
* Free polyominoes enumeration
| using System;
using System.Linq;
namespace PentominoTiling
{
class Program
{
static readonly char[] symbols = "FILNPTUVWXYZ-".ToCharArray();
static readonly int nRows = 8;
static readonly int nCols = 8;
static readonly int target = 12;
static readonly int blank = 12;
static int[][] grid = new int[nRows][];
static bool[] placed = new bool[target];
static void Main(string[] args)
{
var rand = new Random();
for (int r = 0; r < nRows; r++)
grid[r] = Enumerable.Repeat(-1, nCols).ToArray();
for (int i = 0; i < 4; i++)
{
int randRow, randCol;
do
{
randRow = rand.Next(nRows);
randCol = rand.Next(nCols);
}
while (grid[randRow][randCol] == blank);
grid[randRow][randCol] = blank;
}
if (Solve(0, 0))
{
PrintResult();
}
else
{
Console.WriteLine("no solution");
}
Console.ReadKey();
}
private static void PrintResult()
{
foreach (int[] r in grid)
{
foreach (int i in r)
Console.Write("{0} ", symbols[i]);
Console.WriteLine();
}
}
private static bool Solve(int pos, int numPlaced)
{
if (numPlaced == target)
return true;
int row = pos / nCols;
int col = pos % nCols;
if (grid[row][col] != -1)
return Solve(pos + 1, numPlaced);
for (int i = 0; i < shapes.Length; i++)
{
if (!placed[i])
{
foreach (int[] orientation in shapes[i])
{
if (!TryPlaceOrientation(orientation, row, col, i))
continue;
placed[i] = true;
if (Solve(pos + 1, numPlaced + 1))
return true;
RemoveOrientation(orientation, row, col);
placed[i] = false;
}
}
}
return false;
}
private static void RemoveOrientation(int[] orientation, int row, int col)
{
grid[row][col] = -1;
for (int i = 0; i < orientation.Length; i += 2)
grid[row + orientation[i]][col + orientation[i + 1]] = -1;
}
private static bool TryPlaceOrientation(int[] orientation, int row, int col, int shapeIndex)
{
for (int i = 0; i < orientation.Length; i += 2)
{
int x = col + orientation[i + 1];
int y = row + orientation[i];
if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)
return false;
}
grid[row][col] = shapeIndex;
for (int i = 0; i < orientation.Length; i += 2)
grid[row + orientation[i]][col + orientation[i + 1]] = shapeIndex;
return true;
}
// four (x, y) pairs are listed, (0,0) not included
static readonly int[][] F = {
new int[] {1, -1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 2, 0},
new int[] {1, 0, 1, 1, 1, 2, 2, 1}, new int[] {1, 0, 1, 1, 2, -1, 2, 0},
new int[] {1, -2, 1, -1, 1, 0, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 1},
new int[] {1, -1, 1, 0, 1, 1, 2, -1}, new int[] {1, -1, 1, 0, 2, 0, 2, 1}};
static readonly int[][] I = {
new int[] { 0, 1, 0, 2, 0, 3, 0, 4 }, new int[] { 1, 0, 2, 0, 3, 0, 4, 0 } };
static readonly int[][] L = {
new int[] {1, 0, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, 0, 3, -1, 3, 0},
new int[] {0, 1, 0, 2, 0, 3, 1, 3}, new int[] {0, 1, 1, 0, 2, 0, 3, 0},
new int[] {0, 1, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 0, 3, 1, 0},
new int[] {1, 0, 2, 0, 3, 0, 3, 1}, new int[] {1, -3, 1, -2, 1, -1, 1, 0}};
static readonly int[][] N = {
new int[] {0, 1, 1, -2, 1, -1, 1, 0}, new int[] {1, 0, 1, 1, 2, 1, 3, 1},
new int[] {0, 1, 0, 2, 1, -1, 1, 0}, new int[] {1, 0, 2, 0, 2, 1, 3, 1},
new int[] {0, 1, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, -1, 2, 0, 3, -1},
new int[] {0, 1, 0, 2, 1, 2, 1, 3}, new int[] {1, -1, 1, 0, 2, -1, 3, -1}};
static readonly int[][] P = {
new int[] {0, 1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 0, 2, 1, 0, 1, 1},
new int[] {1, 0, 1, 1, 2, 0, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 1, 1},
new int[] {0, 1, 1, 0, 1, 1, 1, 2}, new int[] {1, -1, 1, 0, 2, -1, 2, 0},
new int[] {0, 1, 0, 2, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 1, 1, 2, 0}};
static readonly int[][] T = {
new int[] {0, 1, 0, 2, 1, 1, 2, 1}, new int[] {1, -2, 1, -1, 1, 0, 2, 0},
new int[] {1, 0, 2, -1, 2, 0, 2, 1}, new int[] {1, 0, 1, 1, 1, 2, 2, 0}};
static readonly int[][] U = {
new int[] {0, 1, 0, 2, 1, 0, 1, 2}, new int[] {0, 1, 1, 1, 2, 0, 2, 1},
new int[] {0, 2, 1, 0, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 2, 0, 2, 1}};
static readonly int[][] V = {
new int[] {1, 0, 2, 0, 2, 1, 2, 2}, new int[] {0, 1, 0, 2, 1, 0, 2, 0},
new int[] {1, 0, 2, -2, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 2, 2, 2}};
static readonly int[][] W = {
new int[] {1, 0, 1, 1, 2, 1, 2, 2}, new int[] {1, -1, 1, 0, 2, -2, 2, -1},
new int[] {0, 1, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, -1, 1, 0, 2, -1}};
static readonly int[][] X = { new int[] { 1, -1, 1, 0, 1, 1, 2, 0 } };
static readonly int[][] Y = {
new int[] {1, -2, 1, -1, 1, 0, 1, 1}, new int[] {1, -1, 1, 0, 2, 0, 3, 0},
new int[] {0, 1, 0, 2, 0, 3, 1, 1}, new int[] {1, 0, 2, 0, 2, 1, 3, 0},
new int[] {0, 1, 0, 2, 0, 3, 1, 2}, new int[] {1, 0, 1, 1, 2, 0, 3, 0},
new int[] {1, -1, 1, 0, 1, 1, 1, 2}, new int[] {1, 0, 2, -1, 2, 0, 3, 0}};
static readonly int[][] Z = {
new int[] {0, 1, 1, 0, 2, -1, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 2},
new int[] {0, 1, 1, 1, 2, 1, 2, 2}, new int[] {1, -2, 1, -1, 1, 0, 2, -2}};
static readonly int[][][] shapes = { F, I, L, N, P, T, U, V, W, X, Y, Z };
}
} |
Perfect shuffle | C sharp 6 | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right"
|-
| ''original:'' ||
1
2
3
4
5
6
7
8
|-
| ''after 1st shuffle:'' ||
1
5
2
6
3
7
4
8
|-
| ''after 2nd shuffle:'' ||
1
3
5
7
2
4
6
8
|-
| ''after 3rd shuffle:'' ||
1
2
3
4
5
6
7
8
|}
'''''The Task'''''
# Write a function that can perform a perfect shuffle on an even-sized list of values.
# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
'''''Test Cases'''''
::::: {| class="wikitable"
|-
! input ''(deck size)'' !! output ''(number of shuffles required)''
|-
| 8 || 3
|-
| 24 || 11
|-
| 52 || 8
|-
| 100 || 30
|-
| 1020 || 1018
|-
| 1024 || 10
|-
| 10000 || 300
|}
| using System;
using System.Collections.Generic;
using System.Linq;
public static class PerfectShuffle
{
static void Main()
{
foreach (int input in new [] {8, 24, 52, 100, 1020, 1024, 10000}) {
int[] numbers = Enumerable.Range(1, input).ToArray();
Console.WriteLine($"{input} cards: {ShuffleThrough(numbers).Count()}");
}
IEnumerable<T[]> ShuffleThrough<T>(T[] original) {
T[] copy = (T[])original.Clone();
do {
yield return copy = Shuffle(copy);
} while (!Enumerable.SequenceEqual(original, copy));
}
}
public static T[] Shuffle<T>(T[] array) {
if (array.Length % 2 != 0) throw new ArgumentException("Length must be even.");
int half = array.Length / 2;
T[] result = new T[array.Length];
for (int t = 0, l = 0, r = half; l < half; t+=2, l++, r++) {
result[t] = array[l];
result[t+1] = array[r];
}
return result;
}
} |
Permutations/Derangements | C sharp|C# | A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''.
There are various ways to calculate !''n''.
;Task:
# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer).
# Generate ''and show'' all the derangements of 4 integers using the above routine.
# Create a function that calculates the subfactorial of ''n'', !''n''.
# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.
;Optional stretch goal:
* Calculate !''20''
;Related tasks:
* [[Anagrams/Deranged anagrams]]
* [[Best shuffle]]
* [[Left_factorials]]
| using System;
class Derangements
{
static int n = 4;
static int [] buf = new int [n];
static bool [] used = new bool [n];
static void Main()
{
for (int i = 0; i < n; i++) used [i] = false;
rec(0);
}
static void rec(int ind)
{
for (int i = 0; i < n; i++)
{
if (!used [i] && i != ind)
{
used [i] = true;
buf [ind] = i;
if (ind + 1 < n) rec(ind + 1);
else Console.WriteLine(string.Join(",", buf));
used [i] = false;
}
}
}
}
|
Phrase reversals | C sharp | Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
:# Reverse the characters of the string.
:# Reverse the characters of each individual word in the string, maintaining original word order within the string.
:# Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
| using System;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//Reverse() is an extension method on IEnumerable<char>.
//The constructor takes a char[], so we have to call ToArray()
Func<string, string> reverse = s => new string(s.Reverse().ToArray());
string phrase = "rosetta code phrase reversal";
//Reverse the string
Console.WriteLine(reverse(phrase));
//Reverse each individual word in the string, maintaining original string order.
Console.WriteLine(string.Join(" ", phrase.Split(' ').Select(word => reverse(word))));
//Reverse the order of each word of the phrase, maintaining the order of characters in each word.
Console.WriteLine(string.Join(" ", phrase.Split(' ').Reverse()));
}
}
} |
Pig the dice game | C sharp | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach '''100''' points or more.
Play is taken in turns. On each person's turn that person has the option of either:
:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.
:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.
;Task:
Create a program to score for, and simulate dice throws for, a two-person game.
;Related task:
* [[Pig the dice game/Player]]
| using System;
using System.IO;
namespace Pig {
class Roll {
public int TotalScore{get;set;}
public int RollScore{get;set;}
public bool Continue{get;set;}
}
class Player {
public String Name{get;set;}
public int Score {get;set;}
Random rand;
public Player() {
Score = 0;
rand = new Random();
}
public Roll Roll(int LastScore){
Roll roll = new Roll();
roll.RollScore = rand.Next(6) + 1;
if(roll.RollScore == 1){
roll.TotalScore = 0;
roll.Continue = false;
return roll;
}
roll.TotalScore = LastScore + roll.RollScore;
roll.Continue = true;
return roll;
}
public void FinalizeTurn(Roll roll){
Score = Score + roll.TotalScore;
}
}
public class Game {
public static void Main(String[] argv){
String input = null;
Player[] players = new Player[2];
// Game loop
while(true){
Console.Write("Greetings! Would you like to play a game (y/n)?");
while(input == null){
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
players[0] = new Player();
players[1] = new Player();
Console.Write("Player One, what's your name?");
input = Console.ReadLine();
players[0].Name = input;
Console.Write("Player Two, what's your name?");
input = Console.ReadLine();
players[1].Name = input;
Console.WriteLine(players[0].Name + " and " + players[1].Name + ", prepare to do battle!");
} else if (input.ToLowerInvariant() == "n"){
goto Goodbye; /* Not considered harmful */
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
// Play the game
int currentPlayer = 0;
Roll roll = null;
bool runTurn = true;
while(runTurn){
Player p = players[currentPlayer];
roll = p.Roll( (roll !=null) ? roll.TotalScore : 0 );
if(roll.Continue){
if(roll.TotalScore + p.Score > 99){
Console.WriteLine("Congratulations, " + p.Name + "! You rolled a " + roll.RollScore + " for a final score of " + (roll.TotalScore + p.Score) + "!");
runTurn = false;
} else {
Console.Write(p.Name + ": Roll " + roll.RollScore + "/Turn " + roll.TotalScore + "/Total " + (roll.TotalScore + p.Score) + ". Roll again (y/n)?");
input = Console.ReadLine();
if(input.ToLowerInvariant() == "y"){
// Do nothing
} else if (input.ToLowerInvariant() == "n"){
p.FinalizeTurn(roll);
currentPlayer = Math.Abs(currentPlayer - 1);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
Console.WriteLine(players[currentPlayer].Name + ", your turn begins.");
roll = null;
} else {
input = null;
Console.Write("I'm sorry, I don't understand. Play a game (y/n)?");
}
}
} else {
Console.WriteLine(p.Name + @", you rolled a 1 and lost your points for this turn.
Your current score: " + p.Score);
Console.WriteLine();
Console.WriteLine(players[0].Name + ": " + players[0].Score + " " + players[1].Name + ": " + players[1].Score);
currentPlayer = Math.Abs(currentPlayer - 1);
}
}
input = null;
}
Goodbye:
Console.WriteLine("Thanks for playing, and remember: the house ALWAYS wins!");
System.Environment.Exit(0);
}
}
}
|
Poker hand analyser | C sharp 8 | Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
;Example:
::::'''2d''' (two of diamonds).
Faces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''
Suits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or
alternatively, the unicode card-suit characters:
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
;Examples:
2 2 2 k q: three-of-a-kind
2 5 7 8 9: high-card
a 2 3 4 5: straight
2 3 2 3 3: full-house
2 7 2 3 3: two-pair
2 7 7 7 7: four-of-a-kind
10 j q k a: straight-flush
4 4 k 5 10: one-pair
q 10 7 6 q: invalid
The programs output for the above examples should be displayed here on this page.
;Extra credit:
# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
# allow two jokers
::* use the symbol '''joker'''
::* duplicates would be allowed (for jokers only)
::* five-of-a-kind would then be the highest hand
;More extra credit examples:
joker 2 2 k q: three-of-a-kind
joker 5 7 8 9: straight
joker 2 3 4 5: straight
joker 3 2 3 3: four-of-a-kind
joker 7 2 3 3: three-of-a-kind
joker 7 7 7 7: five-of-a-kind
joker j q k A: straight-flush
joker 4 k 5 10: one-pair
joker k 7 6 4: flush
joker 2 joker 4 5: straight
joker Q joker A 10: straight
joker Q joker A 10: straight-flush
joker 2 2 joker q: four-of-a-kind
;Related tasks:
* [[Playing cards]]
* [[Card shuffles]]
* [[Deal cards_for_FreeCell]]
* [[War Card_Game]]
* [[Go Fish]]
| using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class PokerHandAnalyzer
{
private enum Hand {
Invalid, High_Card, One_Pair, Two_Pair, Three_Of_A_Kind, Straight,
Flush, Full_House, Four_Of_A_Kind, Straight_Flush, Five_Of_A_Kind
}
private const bool Y = true;
private const char C = '♣', D = '♦', H = '♥', S = '♠';
private const int rankMask = 0b11_1111_1111_1111;
private const int suitMask = 0b1111 << 14;
private static readonly string[] ranks = { "a", "2", "3", "4", "5", "6", "7", "8", "9", "10", "j", "q", "k" };
private static readonly string[] suits = { C + "", D + "", H + "", S + "" };
private static readonly Card[] deck = (from suit in Range(1, 4) from rank in Range(1, 13) select new Card(rank, suit)).ToArray();
public static void Main() {
string[] hands = {
"2♥ 2♦ 2♣ k♣ q♦",
"2♥ 5♥ 7♦ 8♣ 9♠",
"a♥ 2♦ 3♣ 4♣ 5♦",
"2♥ 3♥ 2♦ 3♣ 3♦",
"2♥ 7♥ 2♦ 3♣ 3♦",
"2♥ 7♥ 7♦ 7♣ 7♠",
"10♥ j♥ q♥ k♥ a♥",
"4♥ 4♠ k♠ 5♦ 10♠",
"q♣ 10♣ 7♣ 6♣ 4♣",
"4♥ 4♣ 4♥ 4♠ 4♦", //duplicate card
"joker 2♦ 2♠ k♠ q♦",
"joker 5♥ 7♦ 8♠ 9♦",
"joker 2♦ 3♠ 4♠ 5♠",
"joker 3♥ 2♦ 3♠ 3♦",
"joker 7♥ 2♦ 3♠ 3♦",
"joker 7♥ 7♦ 7♠ 7♣",
"joker j♥ q♥ k♥ A♥",
"joker 4♣ k♣ 5♦ 10♠",
"joker k♣ 7♣ 6♣ 4♣",
"joker 2♦ joker 4♠ 5♠",
"joker Q♦ joker A♠ 10♠",
"joker Q♦ joker A♦ 10♦",
"joker 2♦ 2♠ joker q♦"
};
foreach (var h in hands) {
Console.WriteLine($"{h}: {Analyze(h).Name()}");
}
}
static string Name(this Hand hand) => string.Join('-', hand.ToString().Split('_')).ToLower();
static List<T> With<T>(this List<T> list, int index, T item) {
list[index] = item;
return list;
}
struct Card : IEquatable<Card>, IComparable<Card>
{
public static readonly Card Invalid = new Card(-1, -1);
public static readonly Card Joker = new Card(0, 0);
public Card(int rank, int suit) {
(Rank, Suit, Code) = (rank, suit) switch {
(_, -1) => (-1, -1, -1),
(-1, _) => (-1, -1, -1),
(0, _) => (0, 0, 0),
(1, _) => (rank, suit, (1 << (13 + suit)) | ((1 << 13) | 1)),
(_, _) => (rank, suit, (1 << (13 + suit)) | (1 << (rank - 1)))
};
}
public static implicit operator Card((int rank, int suit) tuple) => new Card(tuple.rank, tuple.suit);
public int Rank { get; }
public int Suit { get; }
public int Code { get; }
public override string ToString() => Rank switch {
-1 => "invalid",
0 => "joker",
_ => $"{ranks[Rank-1]}{suits[Suit-1]}"
};
public override int GetHashCode() => Rank << 16 | Suit;
public bool Equals(Card other) => Rank == other.Rank && Suit == other.Suit;
public int CompareTo(Card other) {
int c = Rank.CompareTo(other.Rank);
if (c != 0) return c;
return Suit.CompareTo(other.Suit);
}
}
static Hand Analyze(string hand) {
var cards = ParseHand(hand);
if (cards.Count != 5) return Hand.Invalid; //hand must consist of 5 cards
cards.Sort();
if (cards[0].Equals(Card.Invalid)) return Hand.Invalid;
int jokers = cards.LastIndexOf(Card.Joker) + 1;
if (jokers > 2) return Hand.Invalid; //more than 2 jokers
if (cards.Skip(jokers).Distinct().Count() + jokers != 5) return Hand.Invalid; //duplicate cards
if (jokers == 2) return (from c0 in deck from c1 in deck select Evaluate(cards.With(0, c0).With(1, c1))).Max();
if (jokers == 1) return (from c0 in deck select Evaluate(cards.With(0, c0))).Max();
return Evaluate(cards);
}
static List<Card> ParseHand(string hand) =>
hand.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries)
.Select(card => ParseCard(card.ToLower())).ToList();
static Card ParseCard(string card) => (card.Length, card) switch {
(5, "joker") => Card.Joker,
(3, _) when card[..2] == "10" => (10, ParseSuit(card[2])),
(2, _) => (ParseRank(card[0]), ParseSuit(card[1])),
(_, _) => Card.Invalid
};
static int ParseRank(char rank) => rank switch {
'a' => 1,
'j' => 11,
'q' => 12,
'k' => 13,
_ when rank >= '2' && rank <= '9' => rank - '0',
_ => -1
};
static int ParseSuit(char suit) => suit switch {
C => 1, 'c' => 1,
D => 2, 'd' => 2,
H => 3, 'h' => 3,
S => 4, 's' => 4,
_ => -1
};
static Hand Evaluate(List<Card> hand) {
var frequencies = hand.GroupBy(c => c.Rank).Select(g => g.Count()).OrderByDescending(c => c).ToArray();
(int f0, int f1) = (frequencies[0], frequencies.Length > 1 ? frequencies[1] : 0);
return (IsFlush(), IsStraight(), f0, f1) switch {
(_, _, 5, _) => Hand.Five_Of_A_Kind,
(Y, Y, _, _) => Hand.Straight_Flush,
(_, _, 4, _) => Hand.Four_Of_A_Kind,
(_, _, 3, 2) => Hand.Full_House,
(Y, _, _, _) => Hand.Flush,
(_, Y, _, _) => Hand.Straight,
(_, _, 3, _) => Hand.Three_Of_A_Kind,
(_, _, 2, 2) => Hand.Two_Pair,
(_, _, 2, _) => Hand.One_Pair,
_ => Hand.High_Card
};
bool IsFlush() => hand.Aggregate(suitMask, (r, c) => r & c.Code) > 0;
bool IsStraight() {
int r = hand.Aggregate(0, (r, c) => r | c.Code) & rankMask;
for (int i = 0; i < 4; i++) r &= r << 1;
return r > 0;
}
}
} |
Polyspiral | C sharp|C# from Java | A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
;Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
;Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
| using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Windows.Threading;
namespace Polyspiral
{
public partial class Form1 : Form
{
private double inc;
public Form1()
{
Width = Height = 640;
StartPosition = FormStartPosition.CenterScreen;
SetStyle(
ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.DoubleBuffer,
true);
var timer = new DispatcherTimer();
timer.Tick += (s, e) => { inc = (inc + 0.05) % 360; Refresh(); };
timer.Interval = new TimeSpan(0, 0, 0, 0, 40);
timer.Start();
}
private void DrawSpiral(Graphics g, int len, double angleIncrement)
{
double x1 = Width / 2;
double y1 = Height / 2;
double angle = angleIncrement;
for (int i = 0; i < 150; i++)
{
double x2 = x1 + Math.Cos(angle) * len;
double y2 = y1 - Math.Sin(angle) * len;
g.DrawLine(Pens.Blue, (int)x1, (int)y1, (int)x2, (int)y2);
x1 = x2;
y1 = y2;
len += 3;
angle = (angle + angleIncrement) % (Math.PI * 2);
}
}
protected override void OnPaint(PaintEventArgs args)
{
var g = args.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.White);
DrawSpiral(g, 5, ToRadians(inc));
}
private double ToRadians(double angle)
{
return Math.PI * angle / 180.0;
}
}
} |
Population count | C sharp|C# | The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.
''Population count'' is also known as:
::::* ''pop count''
::::* ''popcount''
::::* ''sideways sum''
::::* ''bit summation''
::::* ''Hamming weight''
For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.
''Evil numbers'' are non-negative integers that have an ''even'' population count.
''Odious numbers'' are positive integers that have an ''odd'' population count.
;Task:
* write a function (or routine) to return the population count of a non-negative integer.
* all computation of the lists below should start with '''0''' (zero indexed).
:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').
:* display the 1st thirty ''evil'' numbers.
:* display the 1st thirty ''odious'' numbers.
* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
;See also
* The On-Line Encyclopedia of Integer Sequences: A000120 population count.
* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| using System;
using System.Linq;
namespace PopulationCount
{
class Program
{
private static int PopulationCount(long n)
{
string binaryn = Convert.ToString(n, 2);
return binaryn.ToCharArray().Where(t => t == '1').Count();
}
static void Main(string[] args)
{
Console.WriteLine("Population Counts:");
Console.Write("3^n : ");
int count = 0;
while (count < 30)
{
double n = Math.Pow(3f, (double)count);
int popCount = PopulationCount((long)n);
Console.Write(string.Format("{0} ", popCount));
count++;
}
Console.WriteLine();
Console.Write("Evil: ");
count = 0;
int i = 0;
while (count < 30)
{
int popCount = PopulationCount(i);
if (popCount % 2 == 0)
{
count++;
Console.Write(string.Format("{0} ", i));
}
i++;
}
Console.WriteLine();
Console.Write("Odious: ");
count = 0;
i = 0;
while (count < 30)
{
int popCount = PopulationCount(i);
if (popCount % 2 != 0)
{
count++;
Console.Write(string.Format("{0} ", i));
}
i++;
}
Console.ReadKey();
}
}
}
|
Priority queue | C sharp | A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
;Task:
Create a priority queue. The queue must support at least two operations:
:# Insertion. An element is added to the queue with a priority (a numeric value).
:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
'''Priority''' '''Task'''
---------- ----------------
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| namespace PriorityQ {
using KeyT = UInt32;
using System;
using System.Collections.Generic;
using System.Linq;
class Tuple<K, V> { // for DotNet 3.5 without Tuple's
public K Item1; public V Item2;
public Tuple(K k, V v) { Item1 = k; Item2 = v; }
public override string ToString() {
return "(" + Item1.ToString() + ", " + Item2.ToString() + ")";
}
}
class MinHeapPQ<V> {
private struct HeapEntry {
public KeyT k; public V v;
public HeapEntry(KeyT k, V v) { this.k = k; this.v = v; }
}
private List<HeapEntry> pq;
private MinHeapPQ() { this.pq = new List<HeapEntry>(); }
private bool mt { get { return pq.Count == 0; } }
private int sz {
get {
var cnt = pq.Count;
return (cnt == 0) ? 0 : cnt - 1;
}
}
private Tuple<KeyT, V> pkmn {
get {
if (pq.Count == 0) return null;
else {
var mn = pq[0];
return new Tuple<KeyT, V>(mn.k, mn.v);
}
}
}
private void psh(KeyT k, V v) { // add extra very high item if none
if (pq.Count == 0) pq.Add(new HeapEntry(UInt32.MaxValue, v));
var i = pq.Count; pq.Add(pq[i - 1]); // copy bottom item...
for (var ni = i >> 1; ni > 0; i >>= 1, ni >>= 1) {
var t = pq[ni - 1];
if (t.k > k) pq[i - 1] = t; else break;
}
pq[i - 1] = new HeapEntry(k, v);
}
private void siftdown(KeyT k, V v, int ndx) {
var cnt = pq.Count - 1; var i = ndx;
for (var ni = i + i + 1; ni < cnt; ni = ni + ni + 1) {
var oi = i; var lk = pq[ni].k; var rk = pq[ni + 1].k;
var nk = k;
if (k > lk) { i = ni; nk = lk; }
if (nk > rk) { ni += 1; i = ni; }
if (i != oi) pq[oi] = pq[i]; else break;
}
pq[i] = new HeapEntry(k, v);
}
private void rplcmin(KeyT k, V v) {
if (pq.Count > 1) siftdown(k, v, 0);
}
private void dltmin() {
var lsti = pq.Count - 2;
if (lsti <= 0) pq.Clear();
else {
var lkv = pq[lsti];
pq.RemoveAt(lsti); siftdown(lkv.k, lkv.v, 0);
}
}
private void reheap(int i) {
var lfti = i + i + 1;
if (lfti < sz) {
var rghti = lfti + 1; reheap(lfti); reheap(rghti);
var ckv = pq[i]; siftdown(ckv.k, ckv.v, i);
}
}
private void bld(IEnumerable<Tuple<KeyT, V>> sq) {
var sqm = from e in sq
select new HeapEntry(e.Item1, e.Item2);
pq = sqm.ToList<HeapEntry>();
var sz = pq.Count;
if (sz > 0) {
var lkv = pq[sz - 1];
pq.Add(new HeapEntry(KeyT.MaxValue, lkv.v));
reheap(0);
}
}
private IEnumerable<Tuple<KeyT, V>> sq() {
return from e in pq
where e.k != KeyT.MaxValue
select new Tuple<KeyT, V>(e.k, e.v); }
private void adj(Func<KeyT, V, Tuple<KeyT, V>> f) {
var cnt = pq.Count - 1;
for (var i = 0; i < cnt; ++i) {
var e = pq[i];
var r = f(e.k, e.v);
pq[i] = new HeapEntry(r.Item1, r.Item2);
}
reheap(0);
}
public static MinHeapPQ<V> empty { get { return new MinHeapPQ<V>(); } }
public static bool isEmpty(MinHeapPQ<V> pq) { return pq.mt; }
public static int size(MinHeapPQ<V> pq) { return pq.sz; }
public static Tuple<KeyT, V> peekMin(MinHeapPQ<V> pq) { return pq.pkmn; }
public static MinHeapPQ<V> push(KeyT k, V v, MinHeapPQ<V> pq) {
pq.psh(k, v); return pq; }
public static MinHeapPQ<V> replaceMin(KeyT k, V v, MinHeapPQ<V> pq) {
pq.rplcmin(k, v); return pq; }
public static MinHeapPQ<V> deleteMin(MinHeapPQ<V> pq) { pq.dltmin(); return pq; }
public static MinHeapPQ<V> merge(MinHeapPQ<V> pq1, MinHeapPQ<V> pq2) {
return fromSeq(pq1.sq().Concat(pq2.sq())); }
public static MinHeapPQ<V> adjust(Func<KeyT, V, Tuple<KeyT, V>> f, MinHeapPQ<V> pq) {
pq.adj(f); return pq; }
public static MinHeapPQ<V> fromSeq(IEnumerable<Tuple<KeyT, V>> sq) {
var pq = new MinHeapPQ<V>(); pq.bld(sq); return pq; }
public static Tuple<Tuple<KeyT, V>, MinHeapPQ<V>> popMin(MinHeapPQ<V> pq) {
var rslt = pq.pkmn; if (rslt == null) return null;
pq.dltmin(); return new Tuple<Tuple<KeyT, V>, MinHeapPQ<V>>(rslt, pq); }
public static IEnumerable<Tuple<KeyT, V>> toSeq(MinHeapPQ<V> pq) {
for (; !pq.mt; pq.dltmin()) yield return pq.pkmn; }
public static IEnumerable<Tuple<KeyT, V>> sort(IEnumerable<Tuple<KeyT, V>> sq) {
return toSeq(fromSeq(sq)); }
}
} |
Pythagorean quadruples | C sharp|C# from Java | One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''):
:::::::: a2 + b2 + c2 = d2
An example:
:::::::: 22 + 32 + 62 = 72
::::: which is:
:::::::: 4 + 9 + 36 = 49
;Task:
For positive integers up '''2,200''' (inclusive), for all values of '''a''',
'''b''', '''c''', and '''d''',
find (and show here) those values of '''d''' that ''can't'' be represented.
Show the values of '''d''' on one line of output (optionally with a title).
;Related tasks:
* [[Euler's sum of powers conjecture]].
* [[Pythagorean triples]].
;Reference:
:* the Wikipedia article: Pythagorean quadruple.
| using System;
namespace PythagoreanQuadruples {
class Program {
const int MAX = 2200;
const int MAX2 = MAX * MAX * 2;
static void Main(string[] args) {
bool[] found = new bool[MAX + 1]; // all false by default
bool[] a2b2 = new bool[MAX2 + 1]; // ditto
int s = 3;
for(int a = 1; a <= MAX; a++) {
int a2 = a * a;
for (int b=a; b<=MAX; b++) {
a2b2[a2 + b * b] = true;
}
}
for (int c = 1; c <= MAX; c++) {
int s1 = s;
s += 2;
int s2 = s;
for (int d = c + 1; d <= MAX; d++) {
if (a2b2[s1]) found[d] = true;
s1 += s2;
s2 += 2;
}
}
Console.WriteLine("The values of d <= {0} which can't be represented:", MAX);
for (int d = 1; d < MAX; d++) {
if (!found[d]) Console.Write("{0} ", d);
}
Console.WriteLine();
}
}
} |
Pythagorean triples | C sharp|C# | A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.
They are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\rm gcd}(a, b) = {\rm gcd}(a, c) = {\rm gcd}(b, c) = 1.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\rm gcd}(a, b) = 1).
Each triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.
;Task:
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
;Extra credit:
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
;Related tasks:
* [[Euler's sum of powers conjecture]]
* [[List comprehensions]]
* [[Pythagorean quadruples]]
| using System;
namespace RosettaCode.CSharp
{
class Program
{
static void Count_New_Triangle(ulong A, ulong B, ulong C, ulong Max_Perimeter, ref ulong Total_Cnt, ref ulong Primitive_Cnt)
{
ulong Perimeter = A + B + C;
if (Perimeter <= Max_Perimeter)
{
Primitive_Cnt = Primitive_Cnt + 1;
Total_Cnt = Total_Cnt + Max_Perimeter / Perimeter;
Count_New_Triangle(A + 2 * C - 2 * B, 2 * A + 2 * C - B, 2 * A + 3 * C - 2 * B, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);
Count_New_Triangle(A + 2 * B + 2 * C, 2 * A + B + 2 * C, 2 * A + 2 * B + 3 * C, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);
Count_New_Triangle(2 * B + 2 * C - A, B + 2 * C - 2 * A, 2 * B + 3 * C - 2 * A, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);
}
}
static void Count_Pythagorean_Triples()
{
ulong T_Cnt, P_Cnt;
for (int I = 1; I <= 8; I++)
{
T_Cnt = 0;
P_Cnt = 0;
ulong ExponentNumberValue = (ulong)Math.Pow(10, I);
Count_New_Triangle(3, 4, 5, ExponentNumberValue, ref T_Cnt, ref P_Cnt);
Console.WriteLine("Perimeter up to 10E" + I + " : " + T_Cnt + " Triples, " + P_Cnt + " Primitives");
}
}
static void Main(string[] args)
{
Count_Pythagorean_Triples();
}
}
} |
Quaternion type | C sharp | complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''.
A quaternion has one real part and ''three'' imaginary parts, i, j, and k.
A quaternion might be written as a + bi + cj + dk.
In the quaternion numbering system:
:::* ii = jj = kk = ijk = -1, or more simply,
:::* ii = jj = kk = ijk = -1.
The order of multiplication is important, as, in general, for two quaternions:
:::: q1 and q2: q1q2 q2q1.
An example of a quaternion might be 1 +2i +3j +4k
There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position.
So the example above would be written as (1, 2, 3, 4)
;Task:
Given the three quaternions and their components:
q = (1, 2, 3, 4) = (a, b, c, d)
q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)
q2 = (3, 4, 5, 6) = (a2, b2, c2, d2)
And a wholly real number r = 7.
Create functions (or classes) to perform simple maths with quaternions including computing:
# The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2}
# The negative of a quaternion: = (-a, -b, -c, -d)
# The conjugate of a quaternion: = ( a, -b, -c, -d)
# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d)
# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2)
# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr)
# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 )
# Show that, for the two quaternions q1 and q2: q1q2 q2q1
If a language has built-in support for quaternions, then use it.
;C.f.:
* [[Vector products]]
* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
| using System;
struct Quaternion : IEquatable<Quaternion>
{
public readonly double A, B, C, D;
public Quaternion(double a, double b, double c, double d)
{
this.A = a;
this.B = b;
this.C = c;
this.D = d;
}
public double Norm()
{
return Math.Sqrt(A * A + B * B + C * C + D * D);
}
public static Quaternion operator -(Quaternion q)
{
return new Quaternion(-q.A, -q.B, -q.C, -q.D);
}
public Quaternion Conjugate()
{
return new Quaternion(A, -B, -C, -D);
}
// implicit conversion takes care of real*quaternion and real+quaternion
public static implicit operator Quaternion(double d)
{
return new Quaternion(d, 0, 0, 0);
}
public static Quaternion operator +(Quaternion q1, Quaternion q2)
{
return new Quaternion(q1.A + q2.A, q1.B + q2.B, q1.C + q2.C, q1.D + q2.D);
}
public static Quaternion operator *(Quaternion q1, Quaternion q2)
{
return new Quaternion(
q1.A * q2.A - q1.B * q2.B - q1.C * q2.C - q1.D * q2.D,
q1.A * q2.B + q1.B * q2.A + q1.C * q2.D - q1.D * q2.C,
q1.A * q2.C - q1.B * q2.D + q1.C * q2.A + q1.D * q2.B,
q1.A * q2.D + q1.B * q2.C - q1.C * q2.B + q1.D * q2.A);
}
public static bool operator ==(Quaternion q1, Quaternion q2)
{
return q1.A == q2.A && q1.B == q2.B && q1.C == q2.C && q1.D == q2.D;
}
public static bool operator !=(Quaternion q1, Quaternion q2)
{
return !(q1 == q2);
}
#region Object Members
public override bool Equals(object obj)
{
if (obj is Quaternion)
return Equals((Quaternion)obj);
return false;
}
public override int GetHashCode()
{
return A.GetHashCode() ^ B.GetHashCode() ^ C.GetHashCode() ^ D.GetHashCode();
}
public override string ToString()
{
return string.Format("Q({0}, {1}, {2}, {3})", A, B, C, D);
}
#endregion
#region IEquatable<Quaternion> Members
public bool Equals(Quaternion other)
{
return other == this;
}
#endregion
} |
Quaternion type | .NET Core 2.1 | complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''.
A quaternion has one real part and ''three'' imaginary parts, i, j, and k.
A quaternion might be written as a + bi + cj + dk.
In the quaternion numbering system:
:::* ii = jj = kk = ijk = -1, or more simply,
:::* ii = jj = kk = ijk = -1.
The order of multiplication is important, as, in general, for two quaternions:
:::: q1 and q2: q1q2 q2q1.
An example of a quaternion might be 1 +2i +3j +4k
There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position.
So the example above would be written as (1, 2, 3, 4)
;Task:
Given the three quaternions and their components:
q = (1, 2, 3, 4) = (a, b, c, d)
q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)
q2 = (3, 4, 5, 6) = (a2, b2, c2, d2)
And a wholly real number r = 7.
Create functions (or classes) to perform simple maths with quaternions including computing:
# The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2}
# The negative of a quaternion: = (-a, -b, -c, -d)
# The conjugate of a quaternion: = ( a, -b, -c, -d)
# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d)
# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2)
# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr)
# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 )
# Show that, for the two quaternions q1 and q2: q1q2 q2q1
If a language has built-in support for quaternions, then use it.
;C.f.:
* [[Vector products]]
* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
| Option Compare Binary
Option Explicit On
Option Infer On
Option Strict On
Structure Quaternion
Implements IEquatable(Of Quaternion), IStructuralEquatable
Public ReadOnly A, B, C, D As Double
Public Sub New(a As Double, b As Double, c As Double, d As Double)
Me.A = a
Me.B = b
Me.C = c
Me.D = d
End Sub
Public ReadOnly Property Norm As Double
Get
Return Math.Sqrt((Me.A ^ 2) + (Me.B ^ 2) + (Me.C ^ 2) + (Me.D ^ 2))
End Get
End Property
Public ReadOnly Property Conjugate As Quaternion
Get
Return New Quaternion(Me.A, -Me.B, -Me.C, -Me.D)
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
If TypeOf obj IsNot Quaternion Then Return False
Return Me.Equals(DirectCast(obj, Quaternion))
End Function
Public Overloads Function Equals(other As Quaternion) As Boolean Implements IEquatable(Of Quaternion).Equals
Return other = Me
End Function
Public Overloads Function Equals(other As Object, comparer As IEqualityComparer) As Boolean Implements IStructuralEquatable.Equals
If TypeOf other IsNot Quaternion Then Return False
Dim q = DirectCast(other, Quaternion)
Return comparer.Equals(Me.A, q.A) AndAlso
comparer.Equals(Me.B, q.B) AndAlso
comparer.Equals(Me.C, q.C) AndAlso
comparer.Equals(Me.D, q.D)
End Function
Public Overrides Function GetHashCode() As Integer
Return HashCode.Combine(Me.A, Me.B, Me.C, Me.D)
End Function
Public Overloads Function GetHashCode(comparer As IEqualityComparer) As Integer Implements IStructuralEquatable.GetHashCode
Return HashCode.Combine(
comparer.GetHashCode(Me.A),
comparer.GetHashCode(Me.B),
comparer.GetHashCode(Me.C),
comparer.GetHashCode(Me.D))
End Function
Public Overrides Function ToString() As String
Return $"Q({Me.A}, {Me.B}, {Me.C}, {Me.D})"
End Function
#Region "Operators"
Public Shared Operator =(left As Quaternion, right As Quaternion) As Boolean
Return left.A = right.A AndAlso
left.B = right.B AndAlso
left.C = right.C AndAlso
left.D = right.D
End Operator
Public Shared Operator <>(left As Quaternion, right As Quaternion) As Boolean
Return Not left = right
End Operator
Public Shared Operator +(q1 As Quaternion, q2 As Quaternion) As Quaternion
Return New Quaternion(q1.A + q2.A, q1.B + q2.B, q1.C + q2.C, q1.D + q2.D)
End Operator
Public Shared Operator -(q As Quaternion) As Quaternion
Return New Quaternion(-q.A, -q.B, -q.C, -q.D)
End Operator
Public Shared Operator *(q1 As Quaternion, q2 As Quaternion) As Quaternion
Return New Quaternion(
(q1.A * q2.A) - (q1.B * q2.B) - (q1.C * q2.C) - (q1.D * q2.D),
(q1.A * q2.B) + (q1.B * q2.A) + (q1.C * q2.D) - (q1.D * q2.C),
(q1.A * q2.C) - (q1.B * q2.D) + (q1.C * q2.A) + (q1.D * q2.B),
(q1.A * q2.D) + (q1.B * q2.C) - (q1.C * q2.B) + (q1.D * q2.A))
End Operator
Public Shared Widening Operator CType(d As Double) As Quaternion
Return New Quaternion(d, 0, 0, 0)
End Operator
#End Region
End Structure |
Quine | C sharp | A quine is a self-referential program that can,
without any external access, output its own source.
A '''quine''' (named after Willard Van Orman Quine) is also known as:
::* ''self-reproducing automata'' (1972)
::* ''self-replicating program'' or ''self-replicating computer program''
::* ''self-reproducing program'' or ''self-reproducing computer program''
::* ''self-copying program'' or ''self-copying computer program''
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.
The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.
;Task:
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
** Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
** If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.
'''Next to the Quines presented here, many other versions can be found on the Quine page.'''
;Related task:
:* print itself.
| class Program { static void Main() { var s = "class Program {{ static void Main() {{ var s = {0}{1}{0}; System.Console.WriteLine(s, (char)34, s); }} }}"; System.Console.WriteLine(s, (char)34, s); } } |
RIPEMD-160 | C sharp|C# | '''RIPEMD-160''' is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like [[MD4]] (RFC 1320).
Find the RIPEMD-160 message digest of a string of [[octet]]s.
Use the ASCII encoded string "Rosetta Code".
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
| using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string text = "Rosetta Code";
byte[] bytes = Encoding.ASCII.GetBytes(text);
RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
byte[] hashValue = myRIPEMD160.ComputeHash(bytes);
var hexdigest = BitConverter.ToString(hashValue).Replace("-", "").ToLower();
Console.WriteLine(hexdigest);
Console.ReadLine();
}
} |
RPG attributes generator | C sharp|C# from Visual Basic .NET | '''RPG''' = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.
Some players like to assign values to their attributes in the order they're rolled.
To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:
* The total of all character attributes must be at least 75.
* At least two of the attributes must be at least 15.
However, this can require a lot of manual dice rolling. A programatic solution would be much faster.
;Task:
Write a program that:
# Generates 4 random, whole values between 1 and 6.
# Saves the sum of the 3 largest values.
# Generates a total of 6 values this way.
# Displays the total, and all 6 values once finished.
* The order in which each value was generated must be preserved.
* The total of all 6 values must be at least 75.
* At least 2 of the values must be 15 or more.
| using System;
using System.Collections.Generic;
using System.Linq;
static class Module1
{
static Random r = new Random();
static List<int> getThree(int n)
{
List<int> g3 = new List<int>();
for (int i = 0; i < 4; i++) g3.Add(r.Next(n) + 1);
g3.Sort(); g3.RemoveAt(0); return g3;
}
static List<int> getSix()
{
List<int> g6 = new List<int>();
for (int i = 0; i < 6; i++) g6.Add(getThree(6).Sum());
return g6;
}
static void Main(string[] args)
{
bool good = false; do {
List<int> gs = getSix(); int gss = gs.Sum(); int hvc = gs.FindAll(x => x > 14).Count;
Console.Write("attribs: {0}, sum={1}, ({2} sum, high vals={3})",
string.Join(", ", gs), gss, gss >= 75 ? "good" : "low", hvc);
Console.WriteLine(" - {0}", (good = gs.Sum() >= 75 && hvc > 1) ? "success" : "failure");
} while (!good);
}
} |
Ramer-Douglas-Peucker line simplification | C sharp|C# from Java | The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
;Task:
Using the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: '''1.0'''.
Display the remaining points here.
;Reference:
:* the Wikipedia article: Ramer-Douglas-Peucker algorithm.
| using System;
using System.Collections.Generic;
using System.Linq;
namespace LineSimplification {
using Point = Tuple<double, double>;
class Program {
static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) {
double dx = lineEnd.Item1 - lineStart.Item1;
double dy = lineEnd.Item2 - lineStart.Item2;
// Normalize
double mag = Math.Sqrt(dx * dx + dy * dy);
if (mag > 0.0) {
dx /= mag;
dy /= mag;
}
double pvx = pt.Item1 - lineStart.Item1;
double pvy = pt.Item2 - lineStart.Item2;
// Get dot product (project pv onto normalized direction)
double pvdot = dx * pvx + dy * pvy;
// Scale line direction vector and subtract it from pv
double ax = pvx - pvdot * dx;
double ay = pvy - pvdot * dy;
return Math.Sqrt(ax * ax + ay * ay);
}
static void RamerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> output) {
if (pointList.Count < 2) {
throw new ArgumentOutOfRangeException("Not enough points to simplify");
}
// Find the point with the maximum distance from line between the start and end
double dmax = 0.0;
int index = 0;
int end = pointList.Count - 1;
for (int i = 1; i < end; ++i) {
double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]);
if (d > dmax) {
index = i;
dmax = d;
}
}
// If max distance is greater than epsilon, recursively simplify
if (dmax > epsilon) {
List<Point> recResults1 = new List<Point>();
List<Point> recResults2 = new List<Point>();
List<Point> firstLine = pointList.Take(index + 1).ToList();
List<Point> lastLine = pointList.Skip(index).ToList();
RamerDouglasPeucker(firstLine, epsilon, recResults1);
RamerDouglasPeucker(lastLine, epsilon, recResults2);
// build the result list
output.AddRange(recResults1.Take(recResults1.Count - 1));
output.AddRange(recResults2);
if (output.Count < 2) throw new Exception("Problem assembling output");
}
else {
// Just return start and end points
output.Clear();
output.Add(pointList[0]);
output.Add(pointList[pointList.Count - 1]);
}
}
static void Main(string[] args) {
List<Point> pointList = new List<Point>() {
new Point(0.0,0.0),
new Point(1.0,0.1),
new Point(2.0,-0.1),
new Point(3.0,5.0),
new Point(4.0,6.0),
new Point(5.0,7.0),
new Point(6.0,8.1),
new Point(7.0,9.0),
new Point(8.0,9.0),
new Point(9.0,9.0),
};
List<Point> pointListOut = new List<Point>();
RamerDouglasPeucker(pointList, 1.0, pointListOut);
Console.WriteLine("Points remaining after simplification:");
pointListOut.ForEach(p => Console.WriteLine(p));
}
}
} |
Random Latin squares | C sharp|C# from Kotlin | A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.
For the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.
;Example n=4 randomised Latin square:
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
;Task:
# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
# Use the function to generate ''and show here'', two randomly generated squares of size 5.
;Note:
Strict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.
;Related tasks:
* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]
* [[Latin Squares in reduced form]]
;Reference:
* Wikipedia: Latin square
* OEIS: A002860
| using System;
using System.Collections.Generic;
namespace RandomLatinSquares {
using Matrix = List<List<int>>;
// Taken from https://stackoverflow.com/a/1262619
static class Helper {
private static readonly Random rng = new Random();
public static void Shuffle<T>(this IList<T> list) {
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
class Program {
static void PrintSquare(Matrix latin) {
foreach (var row in latin) {
Console.Write('[');
var it = row.GetEnumerator();
if (it.MoveNext()) {
Console.Write(it.Current);
}
while (it.MoveNext()) {
Console.Write(", ");
Console.Write(it.Current);
}
Console.WriteLine(']');
}
Console.WriteLine();
}
static void LatinSquare(int n) {
if (n <= 0) {
Console.WriteLine("[]");
return;
}
var latin = new Matrix();
for (int i = 0; i < n; i++) {
List<int> temp = new List<int>();
for (int j = 0; j < n; j++) {
temp.Add(j);
}
latin.Add(temp);
}
// first row
latin[0].Shuffle();
// middle row(s)
for (int i = 1; i < n - 1; i++) {
bool shuffled = false;
while (!shuffled) {
latin[i].Shuffle();
for (int k = 0; k < i; k++) {
for (int j = 0; j < n; j++) {
if (latin[k][j] == latin[i][j]) {
goto shuffling;
}
}
}
shuffled = true;
shuffling: { }
}
}
// last row
for (int j = 0; j < n; j++) {
List<bool> used = new List<bool>();
for (int i = 0; i < n; i++) {
used.Add(false);
}
for (int i = 0; i < n-1; i++) {
used[latin[i][j]] = true;
}
for (int k = 0; k < n; k++) {
if (!used[k]) {
latin[n - 1][j] = k;
break;
}
}
}
PrintSquare(latin);
}
static void Main() {
LatinSquare(5);
LatinSquare(5);
LatinSquare(10); // for good measure
}
}
} |
Random number generator (device) | C sharp | If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
;Related task
* [[Random_number_generator_(included)]]
| const long m = 2147483647L;
const long a = 48271L;
const long q = 44488L;
const long r = 3399L;
static long r_seed = 12345678L;
public static byte gen()
{
long hi = r_seed / q;
long lo = r_seed - q * hi;
long t = a * lo - r * hi;
if (t > 0)
r_seed = t;
else
r_seed = t + m;
return (byte)r_seed;
}
public static void ParkMiller(byte[] arr)
{
byte[] arr = new byte[10900000];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = gen();
}
} |
Random number generator (included) | C sharp | The task is to:
: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
: If possible, give a link to a wider explanation of the algorithm used.
Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
| The .NET Random class says that it uses Knuth's subtractive random number generator algorithm.[http://msdn.microsoft.com/en-us/library/system.random.aspx#remarksToggle]
|
Range consolidation | C sharp 7 | Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''.
That range can be shown as:
::::::::: '''[b0, b1]'''
:::::::: or equally as:
::::::::: '''[b1, b0]'''
Given two ranges, the act of consolidation between them compares the two ranges:
* If one range covers all of the other then the result is that encompassing range.
* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.
* Otherwise the act of consolidation is to return the two non-touching ranges.
Given '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible.
If '''N < 2''' then range consolidation has no strict meaning and the input can be returned.
;Example 1:
: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then
: there is no common region between the ranges and the result is the same as the input.
;Example 2:
: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then
: there is : an overlap '''[2.5, 1.8]''' between the ranges and
: the result is the single range '''[1, 4.7]'''.
: Note that order of bounds in a range is not (yet) stated.
;Example 3:
: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then
: they touch at '''7.2''' and
: the result is the single range '''[6.1, 8.3]'''.
;Example 4:
: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]'''
: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]'''
: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and
: consolidate to produce the range '''[1, 5]'''.
: This range, in turn, overlaps the other range '''[4, 8]''', and
: so consolidates to the final output of the single range '''[1, 8]'''.
;Task:
Let a normalized range display show the smaller bound to the left; and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.
Output the ''normalized'' result of applying consolidation to these five sets of ranges:
[1.1, 2.2]
[6.1, 7.2], [7.2, 8.3]
[4, 3], [2, 1]
[4, 3], [2, 1], [-1, -2], [3.9, 10]
[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.
;See also:
* [[Set consolidation]]
* [[Set of real numbers]]
| using static System.Math;
using System.Linq;
using System;
public static class RangeConsolidation
{
public static void Main() {
foreach (var list in new [] {
new[] { (1.1, 2.2) }.ToList(),
new[] { (6.1, 7.2), (7.2, 8.3) }.ToList(),
new[] { (4d, 3d), (2, 1) }.ToList(),
new[] { (4d, 3d), (2, 1), (-1, 2), (3.9, 10) }.ToList(),
new[] { (1d, 3d), (-6, -1), (-4, -5), (8, 2), (-6, -6) }.ToList()
})
{
for (int z = list.Count-1; z >= 1; z--) {
for (int y = z - 1; y >= 0; y--) {
if (Overlap(list[z], list[y])) {
list[y] = Consolidate(list[z], list[y]);
list.RemoveAt(z);
break;
}
}
}
Console.WriteLine(string.Join(", ", list.Select(Normalize).OrderBy(range => range.s)));
}
}
private static bool Overlap((double s, double e) left, (double s, double e) right) =>
Max(left.s, left.e) > Max(right.s, right.e)
? Max(right.s, right.e) >= Min(left.s, left.e)
: Max(left.s, left.e) >= Min(right.s, right.e);
private static (double s, double e) Consolidate((double s, double e) left, (double s, double e) right) =>
(Min(Min(left.s, left.e), Min(right.s, right.e)), Max(Max(left.s, left.e), Max(right.s, right.e)));
private static (double s, double e) Normalize((double s, double e) range) =>
(Min(range.s, range.e), Max(range.s, range.e));
} |
Range expansion | C sharp 3.0 | {{:Range extraction/Format}}
;Task:
Expand the range description:
-6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the '''range from minus 3 to ''minus'' 1'''.
;Related task:
* [[Range extraction]]
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
var rangeString = "-6,-3--1,3-5,7-11,14,15,17-20";
var matches = Regex.Matches(rangeString, @"(?<f>-?\d+)-(?<s>-?\d+)|(-?\d+)");
var values = new List<string>();
foreach (var m in matches.OfType<Match>())
{
if (m.Groups[1].Success)
{
values.Add(m.Value);
continue;
}
var start = Convert.ToInt32(m.Groups["f"].Value);
var end = Convert.ToInt32(m.Groups["s"].Value) + 1;
values.AddRange(Enumerable.Range(start, end - start).Select(v => v.ToString()));
}
Console.WriteLine(string.Join(", ", values));
}
} |
Range expansion | C sharp 3.5+ | {{:Range extraction/Format}}
;Task:
Expand the range description:
-6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the '''range from minus 3 to ''minus'' 1'''.
;Related task:
* [[Range extraction]]
| using System;
using System.Collections.Generic;
using System.Linq;
namespace RangeExpansion {
internal static class StringExtensions {
internal static IEnumerable<int> ExpandRange(this string s) {
return s.Split(',')
.Select(rstr => {
int start;
if (int.TryParse(rstr, out start))
return new {Start = start, End = start};
var istr = new string(("+-".Any(_ => rstr[0] == _)
? rstr.Take(1).Concat(rstr.Skip(1).TakeWhile(char.IsDigit))
: rstr.TakeWhile(char.IsDigit)
).ToArray());
rstr = rstr.Substring(istr.Length + 1, (rstr.Length - istr.Length) - 1);
return new {Start = int.Parse(istr), End = int.Parse(rstr)};
}).SelectMany(_ => Enumerable.Range(_.Start, _.End - _.Start + 1));
}
}
internal static class Program {
private static void Main() {
const string RANGE_STRING = "-6,-3--1,3-5,7-11,14,15,17-20";
var values = RANGE_STRING.ExpandRange().ToList();
var vstr = string.Join(", ", values.Select(_ => _.ToString()));
Console.WriteLine(vstr);
}
}
} |
Range extraction | C sharp | {{:Range extraction/Format}}
;Task:
* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
* Show the output of your program.
;Related task:
* [[Range expansion]]
| using System;
using System.Collections.Generic;
using System.Linq;
class RangeExtraction
{
static void Main()
{
const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39";
var result = String.Join(",", RangesToStrings(GetRanges(testString)));
Console.Out.WriteLine(result);
}
public static IEnumerable<IEnumerable<int>> GetRanges(string testString)
{
var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x));
var current = new List<int>();
foreach (var n in numbers)
{
if (current.Count == 0)
{
current.Add(n);
}
else
{
if (current.Max() + 1 == n)
{
current.Add(n);
}
else
{
yield return current;
current = new List<int> { n };
}
}
}
yield return current;
}
public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges)
{
foreach (var range in ranges)
{
if (range.Count() == 1)
{
yield return range.Single().ToString();
}
else if (range.Count() == 2)
{
yield return range.Min() + "," + range.Max();
}
else
{
yield return range.Min() + "-" + range.Max();
}
}
}
}
|
Read a specific line from a file | C sharp | Some languages have special semantics for obtaining a known line number from a file.
;Task:
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
| using System;
using System.IO;
namespace GetLine
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(GetLine(args[0], uint.Parse(args[1])));
}
private static string GetLine(string path, uint line)
{
using (var reader = new StreamReader(path))
{
try
{
for (uint i = 0; i <= line; i++)
{
if (reader.EndOfStream)
return string.Format("There {1} less than {0} line{2} in the file.", line,
((line == 1) ? "is" : "are"), ((line == 1) ? "" : "s"));
if (i == line)
return reader.ReadLine();
reader.ReadLine();
}
}
catch (IOException ex)
{
return ex.Message;
}
catch (OutOfMemoryException ex)
{
return ex.Message;
}
}
throw new Exception("Something bad happened.");
}
}
} |
Recaman's sequence | C sharp|C# from Kotlin | The '''Recaman's sequence''' generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.
If the conditions ''don't'' hold then a(n) = a(n-1) + n.
;Task:
# Generate and show here the first 15 members of the sequence.
# Find and show here, the first duplicated number in the sequence.
# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.
;References:
* A005132, The On-Line Encyclopedia of Integer Sequences.
* The Slightly Spooky Recaman Sequence, Numberphile video.
* Recaman's sequence, on Wikipedia.
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
} |
Remove lines from a file | C sharp 6 | Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2
Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.
An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
} |
Repeat | C sharp|C# from Java | Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| using System;
namespace Repeat {
class Program {
static void Repeat(int count, Action<int> fn) {
if (null == fn) {
throw new ArgumentNullException("fn");
}
for (int i = 0; i < count; i++) {
fn.Invoke(i + 1);
}
}
static void Main(string[] args) {
Repeat(3, x => Console.WriteLine("Example {0}", x));
}
}
} |
Resistor mesh | C sharp|C# from Java | Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,
find the resistance between points '''A''' and '''B'''.
;See also:
* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)
* An article on how to calculate this and an implementation in Mathematica
| using System;
using System.Collections.Generic;
namespace ResistorMesh {
class Node {
public Node(double v, int fixed_) {
V = v;
Fixed = fixed_;
}
public double V { get; set; }
public int Fixed { get; set; }
}
class Program {
static void SetBoundary(List<List<Node>> m) {
m[1][1].V = 1.0;
m[1][1].Fixed = 1;
m[6][7].V = -1.0;
m[6][7].Fixed = -1;
}
static double CalcuateDifference(List<List<Node>> m, List<List<Node>> d, int w, int h) {
double total = 0.0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
double v = 0.0;
int n = 0;
if (i > 0) {
v += m[i - 1][j].V;
n++;
}
if (j > 0) {
v += m[i][j - 1].V;
n++;
}
if (i + 1 < h) {
v += m[i + 1][j].V;
n++;
}
if (j + 1 < w) {
v += m[i][j + 1].V;
n++;
}
v = m[i][j].V - v / n;
d[i][j].V = v;
if (m[i][j].Fixed == 0) {
total += v * v;
}
}
}
return total;
}
static double Iter(List<List<Node>> m, int w, int h) {
List<List<Node>> d = new List<List<Node>>(h);
for (int i = 0; i < h; i++) {
List<Node> t = new List<Node>(w);
for (int j = 0; j < w; j++) {
t.Add(new Node(0.0, 0));
}
d.Add(t);
}
double[] curr = new double[3];
double diff = 1e10;
while (diff > 1e-24) {
SetBoundary(m);
diff = CalcuateDifference(m, d, w, h);
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
m[i][j].V -= d[i][j].V;
}
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
int k = 0;
if (i != 0) k++;
if (j != 0) k++;
if (i < h - 1) k++;
if (j < w - 1) k++;
curr[m[i][j].Fixed + 1] += d[i][j].V * k;
}
}
return (curr[2] - curr[0]) / 2.0;
}
const int S = 10;
static void Main(string[] args) {
List<List<Node>> mesh = new List<List<Node>>(S);
for (int i = 0; i < S; i++) {
List<Node> t = new List<Node>(S);
for (int j = 0; j < S; j++) {
t.Add(new Node(0.0, 0));
}
mesh.Add(t);
}
double r = 2.0 / Iter(mesh, S, S);
Console.WriteLine("R = {0:F15}", r);
}
}
} |
Reverse words in a string | C sharp|C# | Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
;Example:
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
;Input data
(ten lines within the box)
line
+----------------------------------------+
1 | ---------- Ice and Fire ------------ |
2 | | <--- a blank line here.
3 | fire, in end will world the say Some |
4 | ice. in say Some |
5 | desire of tasted I've what From |
6 | fire. favor who those with hold I |
7 | | <--- a blank line here.
8 | ... elided paragraph last ... |
9 | | <--- a blank line here.
10 | Frost Robert ----------------------- |
+----------------------------------------+
;Cf.
* [[Phrase reversals]]
| using System;
public class ReverseWordsInString
{
public static void Main(string[] args)
{
string text = @"
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
";
foreach (string line in text.Split(Environment.NewLine)) {
//Splits on any whitespace, not just spaces
string[] words = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(words);
WriteLine(string.Join(" ", words));
}
}
} |
Roman numerals/Decode | C sharp|C# | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s (zeroes).
'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and
'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).
The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
| using System;
using System.Collections.Generic;
namespace Roman
{
internal class Program
{
private static void Main(string[] args)
{
// Decode and print the numerals.
Console.WriteLine("{0}: {1}", "MCMXC", Decode("MCMXC"));
Console.WriteLine("{0}: {1}", "MMVIII", Decode("MMVIII"));
Console.WriteLine("{0}: {1}", "MDCLXVI", Decode("MDCLXVI"));
}
// Dictionary to hold our numerals and their values.
private static readonly Dictionary<char, int> RomanDictionary = new Dictionary<char, int>
{
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
private static int Decode(string roman)
{
/* Make the input string upper-case,
* because the dictionary doesn't support lower-case characters. */
roman = roman.ToUpper();
/* total = the current total value that will be returned.
* minus = value to subtract from next numeral. */
int total = 0, minus = 0;
for (int i = 0; i < roman.Length; i++) // Iterate through characters.
{
// Get the value for the current numeral. Takes subtraction into account.
int thisNumeral = RomanDictionary[roman[i]] - minus;
/* Checks if this is the last character in the string, or if the current numeral
* is greater than or equal to the next numeral. If so, we will reset our minus
* variable and add the current numeral to the total value. Otherwise, we will
* subtract the current numeral from the next numeral, and continue. */
if (i >= roman.Length - 1 ||
thisNumeral + minus >= RomanDictionary[roman[i + 1]])
{
total += thisNumeral;
minus = 0;
}
else
{
minus = thisNumeral;
}
}
return total; // Return the total.
}
}
} |
Roman numerals/Encode | C sharp|C# | Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| using System;
class Program
{
static uint[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
static string[] rum = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
static string ToRoman(uint number)
{
string value = "";
for (int i = 0; i < nums.Length && number != 0; i++)
{
while (number >= nums[i])
{
number -= nums[i];
value += rum[i];
}
}
return value;
}
static void Main()
{
for (uint number = 1; number <= 1 << 10; number *= 2)
{
Console.WriteLine("{0} = {1}", number, ToRoman(number));
}
}
} |
Runge-Kutta method | C sharp|C# | Given the example Differential equation:
:y'(t) = t \times \sqrt {y(t)}
With initial condition:
:t_0 = 0 and y_0 = y(t_0) = y(0) = 1
This equation has an exact solution:
:y(t) = \tfrac{1}{16}(t^2 +4)^2
;Task
Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.
* Solve the given differential equation over the range t = 0 \ldots 10 with a step value of \delta t=0.1 (101 total points, the first being given)
* Print the calculated values of y at whole numbered t's (0.0, 1.0, \ldots 10.0) along with error as compared to the exact solution.
;Method summary
Starting with a given y_n and t_n calculate:
:\delta y_1 = \delta t\times y'(t_n, y_n)\quad
:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1)
:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2)
:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad
then:
:y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4)
:t_{n+1} = t_n + \delta t\quad
| using System;
namespace RungeKutta
{
class Program
{
static void Main(string[] args)
{
//Incrementers to pass into the known solution
double t = 0.0;
double T = 10.0;
double dt = 0.1;
// Assign the number of elements needed for the arrays
int n = (int)(((T - t) / dt)) + 1;
// Initialize the arrays for the time index 's' and estimates 'y' at each index 'i'
double[] y = new double[n];
double[] s = new double[n];
// RK4 Variables
double dy1;
double dy2;
double dy3;
double dy4;
// RK4 Initializations
int i = 0;
s[i] = 0.0;
y[i] = 1.0;
Console.WriteLine(" ===================================== ");
Console.WriteLine(" Beging 4th Order Runge Kutta Method ");
Console.WriteLine(" ===================================== ");
Console.WriteLine();
Console.WriteLine(" Given the example Differential equation: \n");
Console.WriteLine(" y' = t*sqrt(y) \n");
Console.WriteLine(" With the initial conditions: \n");
Console.WriteLine(" t0 = 0" + ", y(0) = 1.0 \n");
Console.WriteLine(" Whose exact solution is known to be: \n");
Console.WriteLine(" y(t) = 1/16*(t^2 + 4)^2 \n");
Console.WriteLine(" Solve the given equations over the range t = 0...10 with a step value dt = 0.1 \n");
Console.WriteLine(" Print the calculated values of y at whole numbered t's (0.0,1.0,...10.0) along with the error \n");
Console.WriteLine();
Console.WriteLine(" y(t) " +"RK4" + " ".PadRight(18) + "Absolute Error");
Console.WriteLine(" -------------------------------------------------");
Console.WriteLine(" y(0) " + y[i] + " ".PadRight(20) + (y[i] - solution(s[i])));
// Iterate and implement the Rk4 Algorithm
while (i < y.Length - 1)
{
dy1 = dt * equation(s[i], y[i]);
dy2 = dt * equation(s[i] + dt / 2, y[i] + dy1 / 2);
dy3 = dt * equation(s[i] + dt / 2, y[i] + dy2 / 2);
dy4 = dt * equation(s[i] + dt, y[i] + dy3);
s[i + 1] = s[i] + dt;
y[i + 1] = y[i] + (dy1 + 2 * dy2 + 2 * dy3 + dy4) / 6;
double error = Math.Abs(y[i + 1] - solution(s[i + 1]));
double t_rounded = Math.Round(t + dt, 2);
if (t_rounded % 1 == 0)
{
Console.WriteLine(" y(" + t_rounded + ")" + " " + y[i + 1] + " ".PadRight(5) + (error));
}
i++;
t += dt;
};//End Rk4
Console.ReadLine();
}
// Differential Equation
public static double equation(double t, double y)
{
double y_prime;
return y_prime = t*Math.Sqrt(y);
}
// Exact Solution
public static double solution(double t)
{
double actual;
actual = Math.Pow((Math.Pow(t, 2) + 4), 2)/16;
return actual;
}
}
} |
SHA-1 | C sharp | '''SHA-1''' or '''SHA1''' is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.
{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}
| using System;
using System.Security.Cryptography;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RosettaCode.SHA1
{
[TestClass]
public class SHA1CryptoServiceProviderTest
{
[TestMethod]
public void TestComputeHash()
{
var input = new UTF8Encoding().GetBytes("Rosetta Code");
var output = new SHA1CryptoServiceProvider().ComputeHash(input);
Assert.AreEqual(
"48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5",
BitConverter.ToString(output));
}
}
} |
Sailors, coconuts and a monkey problem | C sharp|C# from Java | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.
To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.
In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
;The task:
# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)
# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
# Show your answers here.
;Extra credit (optional):
* Give some indication of the number of coconuts each sailor hides during the night.
;Note:
* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!
;C.f:
* Monkeys and Coconuts - Numberphile (Video) Analytical solution.
* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).
| class Test
{
static bool valid(int n, int nuts)
{
for (int k = n; k != 0; k--, nuts -= 1 + nuts / n)
{
if (nuts % n != 1)
{
return false;
}
}
return nuts != 0 && (nuts % n == 0);
}
static void Main(string[] args)
{
int x = 0;
for (int n = 2; n < 10; n++)
{
while (!valid(n, x))
x++;
System.Console.WriteLine(n + ": " + x);
}
}
} |
Same fringe | c sharp|C# | Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.
Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.
Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Same_Fringe
{
class Program
{
static void Main()
{
var rnd = new Random(110456);
var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList();
var bt1 = new BinTree<int>(randList);
// Shuffling will create a tree with the same values but different topology
Shuffle(randList, 428);
var bt2 = new BinTree<int>(randList);
Console.WriteLine(bt1.CompareTo(bt2) ? "True compare worked" : "True compare failed");
// Insert a 0 in the first tree which should cause a failure
bt1.Insert(0);
Console.WriteLine(bt1.CompareTo(bt2) ? "False compare failed" : "False compare worked");
}
static void Shuffle<T>(List<T> values, int seed)
{
var rnd = new Random(seed);
for (var i = 0; i < values.Count - 2; i++)
{
var iSwap = rnd.Next(values.Count - i) + i;
var tmp = values[iSwap];
values[iSwap] = values[i];
values[i] = tmp;
}
}
}
// Define other methods and classes here
class BinTree<T> where T:IComparable
{
private BinTree<T> _left;
private BinTree<T> _right;
private T _value;
private BinTree<T> Left
{
get { return _left; }
}
private BinTree<T> Right
{
get { return _right; }
}
// On interior nodes, any value greater than or equal to Value goes in the
// right subtree, everything else in the left.
private T Value
{
get { return _value; }
}
public bool IsLeaf { get { return Left == null; } }
private BinTree(BinTree<T> left, BinTree<T> right, T value)
{
_left = left;
_right = right;
_value = value;
}
public BinTree(T value) : this(null, null, value) { }
public BinTree(IEnumerable<T> values)
{
// ReSharper disable PossibleMultipleEnumeration
_value = values.First();
foreach (var value in values.Skip(1))
{
Insert(value);
}
// ReSharper restore PossibleMultipleEnumeration
}
public void Insert(T value)
{
if (IsLeaf)
{
if (value.CompareTo(Value) < 0)
{
_left = new BinTree<T>(value);
_right = new BinTree<T>(Value);
}
else
{
_left = new BinTree<T>(Value);
_right = new BinTree<T>(value);
_value = value;
}
}
else
{
if (value.CompareTo(Value) < 0)
{
Left.Insert(value);
}
else
{
Right.Insert(value);
}
}
}
public IEnumerable<T> GetLeaves()
{
if (IsLeaf)
{
yield return Value;
yield break;
}
foreach (var val in Left.GetLeaves())
{
yield return val;
}
foreach (var val in Right.GetLeaves())
{
yield return val;
}
}
internal bool CompareTo(BinTree<T> other)
{
return other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f);
}
}
}
|
Self numbers | C#|CSharp from Pascal | A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
;See also:
;*OEIS: A003052 - Self numbers or Colombian numbers
;*Wikipedia: Self numbers
| using System;
using static System.Console;
class Program {
const int mc = 103 * 1000 * 10000 + 11 * 9 + 1;
static bool[] sv = new bool[mc + 1];
static void sieve() { int[] dS = new int[10000];
for (int a = 9, i = 9999; a >= 0; a--)
for (int b = 9; b >= 0; b--)
for (int c = 9, s = a + b; c >= 0; c--)
for (int d = 9, t = s + c; d >= 0; d--)
dS[i--] = t + d;
for (int a = 0, n = 0; a < 103; a++)
for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000)
for (int c = 0, s = d + dS[b] + n; c < 10000; c++)
sv[dS[c] + s++] = true; }
static void Main() { DateTime st = DateTime.Now; sieve();
WriteLine("Sieving took {0}s", (DateTime.Now - st).TotalSeconds);
WriteLine("\nThe first 50 self numbers are:");
for (int i = 0, count = 0; count <= 50; i++) if (!sv[i]) {
count++; if (count <= 50) Write("{0} ", i);
else WriteLine("\n\n Index Self number"); }
for (int i = 0, limit = 1, count = 0; i < mc; i++)
if (!sv[i]) if (++count == limit) {
WriteLine("{0,12:n0} {1,13:n0}", count, i);
if (limit == 1e9) break; limit *= 10; }
WriteLine("\nOverall took {0}s", (DateTime.Now - st). TotalSeconds);
}
} |
Semordnilap | C sharp | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: ''lager'' and ''regal''
;Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
| using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.IO;
public class Semordnilap
{
public static void Main() {
var results = FindSemordnilaps("http://www.puzzlers.org/pub/wordlists/unixdict.txt").ToList();
Console.WriteLine(results.Count);
var random = new Random();
Console.WriteLine("5 random results:");
foreach (string s in results.OrderBy(_ => random.Next()).Distinct().Take(5)) Console.WriteLine(s + " " + Reversed(s));
}
private static IEnumerable<string> FindSemordnilaps(string url) {
var found = new HashSet<string>();
foreach (string line in GetLines(url)) {
string reversed = Reversed(line);
//Not taking advantage of the fact the input file is sorted
if (line.CompareTo(reversed) != 0) {
if (found.Remove(reversed)) yield return reversed;
else found.Add(line);
}
}
}
private static IEnumerable<string> GetLines(string url) {
WebRequest request = WebRequest.Create(url);
using (var reader = new StreamReader(request.GetResponse().GetResponseStream(), true)) {
while (!reader.EndOfStream) {
yield return reader.ReadLine();
}
}
}
private static string Reversed(string value) => new string(value.Reverse().ToArray());
} |
Set consolidation | C sharp | Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:
* The two input sets if no common item exists between the two input sets of items.
* The single set that is the union of the two input sets if they share a common item.
Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.
;'''Example 1:'''
:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
;'''Example 2:'''
:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
;'''Example 3:'''
:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
;'''Example 4:'''
:The consolidation of the five sets:
::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
:Is the two sets:
::{A, C, B, D}, and {G, F, I, H, K}
'''See also'''
* Connected component (graph theory)
* [[Range consolidation]]
| using System;
using System.Linq;
using System.Collections.Generic;
public class SetConsolidation
{
public static void Main()
{
var setCollection1 = new[] {new[] {"A", "B"}, new[] {"C", "D"}};
var setCollection2 = new[] {new[] {"A", "B"}, new[] {"B", "D"}};
var setCollection3 = new[] {new[] {"A", "B"}, new[] {"C", "D"}, new[] {"B", "D"}};
var setCollection4 = new[] {new[] {"H", "I", "K"}, new[] {"A", "B"}, new[] {"C", "D"},
new[] {"D", "B"}, new[] {"F", "G", "H"}};
var input = new[] {setCollection1, setCollection2, setCollection3, setCollection4};
foreach (var sets in input) {
Console.WriteLine("Start sets:");
Console.WriteLine(string.Join(", ", sets.Select(s => "{" + string.Join(", ", s) + "}")));
Console.WriteLine("Sets consolidated using Nodes:");
Console.WriteLine(string.Join(", ", ConsolidateSets1(sets).Select(s => "{" + string.Join(", ", s) + "}")));
Console.WriteLine("Sets consolidated using Set operations:");
Console.WriteLine(string.Join(", ", ConsolidateSets2(sets).Select(s => "{" + string.Join(", ", s) + "}")));
Console.WriteLine();
}
}
/// <summary>
/// Consolidates sets using a connected-component-finding-algorithm involving Nodes with parent pointers.
/// The more efficient solution, but more elaborate code.
/// </summary>
private static IEnumerable<IEnumerable<T>> ConsolidateSets1<T>(IEnumerable<IEnumerable<T>> sets,
IEqualityComparer<T> comparer = null)
{
if (comparer == null) comparer = EqualityComparer<T>.Default;
var elements = new Dictionary<T, Node<T>>();
foreach (var set in sets) {
Node<T> top = null;
foreach (T value in set) {
Node<T> element;
if (elements.TryGetValue(value, out element)) {
if (top != null) {
var newTop = element.FindTop();
top.Parent = newTop;
element.Parent = newTop;
top = newTop;
} else {
top = element.FindTop();
}
} else {
elements.Add(value, element = new Node<T>(value));
if (top == null) top = element;
else element.Parent = top;
}
}
}
foreach (var g in elements.Values.GroupBy(element => element.FindTop().Value))
yield return g.Select(e => e.Value);
}
private class Node<T>
{
public Node(T value, Node<T> parent = null) {
Value = value;
Parent = parent ?? this;
}
public T Value { get; }
public Node<T> Parent { get; set; }
public Node<T> FindTop() {
var top = this;
while (top != top.Parent) top = top.Parent;
//Set all parents to the top element to prevent repeated iteration in the future
var element = this;
while (element.Parent != top) {
var parent = element.Parent;
element.Parent = top;
element = parent;
}
return top;
}
}
/// <summary>
/// Consolidates sets using operations on the HashSet<T> class.
/// Less efficient than the other method, but easier to write.
/// </summary>
private static IEnumerable<IEnumerable<T>> ConsolidateSets2<T>(IEnumerable<IEnumerable<T>> sets,
IEqualityComparer<T> comparer = null)
{
if (comparer == null) comparer = EqualityComparer<T>.Default;
var currentSets = sets.Select(s => new HashSet<T>(s)).ToList();
int previousSize;
do {
previousSize = currentSets.Count;
for (int i = 0; i < currentSets.Count - 1; i++) {
for (int j = currentSets.Count - 1; j > i; j--) {
if (currentSets[i].Overlaps(currentSets[j])) {
currentSets[i].UnionWith(currentSets[j]);
currentSets.RemoveAt(j);
}
}
}
} while (previousSize > currentSets.Count);
foreach (var set in currentSets) yield return set.Select(value => value);
}
} |
Set of real numbers | C sharp | All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of "between", depending on open or closed boundary:
* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }
* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }
* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }
* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }
Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.
'''Task'''
* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):
:* ''x'' ''A'': determine if ''x'' is an element of ''A''
:: example: 1 is in [1, 2), while 2, 3, ... are not.
:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}
:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]
:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set
:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) - (1, 3) = [0, 1]
* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
:* (0, 1] [0, 2)
:* [0, 2) (1, 2]
:* [0, 3) - (0, 1)
:* [0, 3) - [0, 1]
'''Implementation notes'''
* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.
* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).
'''Optional work'''
* Create a function to determine if a given set is empty (contains no element).
* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that
|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using RosettaCode.SetOfRealNumbers;
namespace RosettaCode.SetOfRealNumbersTest
{
[TestClass]
public class SetTest
{
[TestMethod]
public void TestUnion()
{
var set =
new Set<double>(value => 0d < value && value <= 1d).Union(
new Set<double>(value => 0d <= value && value < 2d));
Assert.IsTrue(set.Contains(0d));
Assert.IsTrue(set.Contains(1d));
Assert.IsFalse(set.Contains(2d));
}
[TestMethod]
public void TestIntersection()
{
var set =
new Set<double>(value => 0d <= value && value < 2d).Intersection(
new Set<double>(value => 1d < value && value <= 2d));
Assert.IsFalse(set.Contains(0d));
Assert.IsFalse(set.Contains(1d));
Assert.IsFalse(set.Contains(2d));
}
[TestMethod]
public void TestDifference()
{
var set =
new Set<double>(value => 0d <= value && value < 3d).Difference(
new Set<double>(value => 0d < value && value < 1d));
Assert.IsTrue(set.Contains(0d));
Assert.IsTrue(set.Contains(1d));
Assert.IsTrue(set.Contains(2d));
set =
new Set<double>(value => 0d <= value && value < 3d).Difference(
new Set<double>(value => 0d <= value && value <= 1d));
Assert.IsFalse(set.Contains(0d));
Assert.IsFalse(set.Contains(1d));
Assert.IsTrue(set.Contains(2d));
}
}
} |
Shoelace formula for polygonal area | C sharp|C# from Java | Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
;Task:
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| using System;
using System.Collections.Generic;
namespace ShoelaceFormula {
using Point = Tuple<double, double>;
class Program {
static double ShoelaceArea(List<Point> v) {
int n = v.Count;
double a = 0.0;
for (int i = 0; i < n - 1; i++) {
a += v[i].Item1 * v[i + 1].Item2 - v[i + 1].Item1 * v[i].Item2;
}
return Math.Abs(a + v[n - 1].Item1 * v[0].Item2 - v[0].Item1 * v[n - 1].Item2) / 2.0;
}
static void Main(string[] args) {
List<Point> v = new List<Point>() {
new Point(3,4),
new Point(5,11),
new Point(12,8),
new Point(9,5),
new Point(5,6),
};
double area = ShoelaceArea(v);
Console.WriteLine("Given a polygon with vertices [{0}],", string.Join(", ", v));
Console.WriteLine("its area is {0}.", area);
}
}
} |
Shortest common supersequence | C sharp from Java | The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task.
;;Task:
Given two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique.
Demonstrate this by printing s where u = "abcbdab" and v = "bdcaba".
;Also see:
* Wikipedia: shortest common supersequence
| public class ShortestCommonSupersequence
{
Dictionary<(string, string), string> cache = new();
public string scs(string x, string y)
{
if (x.Length == 0) return y;
if (y.Length == 0) return x;
if (cache.TryGetValue((x, y), out var result)) return result;
if (x[0] == y[0])
{
return cache[(x, y)] = x[0] + scs(x.Substring(1), y.Substring(1));
}
var xr = scs(x.Substring(1), y);
var yr = scs(x, y.Substring(1));
if (yr.Length <= xr.Length)
{
return cache[(x, y)] = y[0] + yr;
}
else
{
return cache[(x, y)] = x[0] + xr;
}
}
public static void Main(string[] args)
{
var scs = new ShortestCommonSupersequence();
Console.WriteLine(scs.scs("abcbdab", "bdcaba"));
}
}
|
Show ASCII table | C sharp | Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int start = 32; start + 16 * 5 < 128; start++) {
WriteLine(string.Concat(Range(0, 6).Select(i => $"{start+16*i, 3} : {Text(start+16*i), -6}")));
}
string Text(int index) => index == 32 ? "Sp" : index == 127 ? "Del" : (char)index + "";
}
} |
Show the epoch | C sharp|C# | Choose popular date libraries used by your language and show the epoch those libraries use.
A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.
For consistency's sake, show the date in UTC time where possible.
;Related task:
* [[Date format]]
| using System;
class Program
{
static void Main()
{
Console.WriteLine(new DateTime());
}
} |
Smith numbers | C sharp|C# from java | sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are ''excluded'' as they (naturally) satisfy this condition!
Smith numbers are also known as ''joke'' numbers.
;Example
Using the number '''166'''
Find the prime factors of '''166''' which are: '''2''' x '''83'''
Then, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''
Then, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''
Therefore, the number '''166''' is a Smith number.
;Task
Write a program to find all Smith numbers ''below'' 10000.
;See also
* from Wikipedia: [Smith number].
* from MathWorld: [Smith number].
* from OEIS A6753: [OEIS sequence A6753].
* from OEIS A104170: [Number of Smith numbers below 10^n].
* from The Prime pages: [Smith numbers].
| using System;
using System.Collections.Generic;
namespace SmithNumbers {
class Program {
static int SumDigits(int n) {
int sum = 0;
while (n > 0) {
n = Math.DivRem(n, 10, out int rem);
sum += rem;
}
return sum;
}
static List<int> PrimeFactors(int n) {
List<int> result = new List<int>();
for (int i = 2; n % i == 0; n /= i) {
result.Add(i);
}
for (int i = 3; i * i < n; i += 2) {
while (n % i == 0) {
result.Add(i);
n /= i;
}
}
if (n != 1) {
result.Add(n);
}
return result;
}
static void Main(string[] args) {
const int SIZE = 8;
int count = 0;
for (int n = 1; n < 10_000; n++) {
var factors = PrimeFactors(n);
if (factors.Count > 1) {
int sum = SumDigits(n);
foreach (var f in factors) {
sum -= SumDigits(f);
}
if (sum == 0) {
Console.Write("{0,5}", n);
if (count == SIZE - 1) {
Console.WriteLine();
}
count = (count + 1) % SIZE;
}
}
}
}
}
} |
Soloway's recurring rainfall | C sharp|C# | Soloway's Recurring Rainfall is commonly used to assess general programming knowledge by requiring basic program structure, input/output, and program exit procedure.
'''The problem:'''
Write a program that will read in integers and output their average. Stop reading when the value 99999 is input.
For languages that aren't traditionally interactive, the program can read in values as makes sense and stopping once 99999 is encountered. The classic rainfall problem comes from identifying success of Computer Science programs with their students, so the original problem statement is written above -- though it may not strictly apply to a given language in the modern era.
'''Implementation Details:'''
* Only Integers are to be accepted as input
* Output should be floating point
* Rainfall can be negative (https://www.geographyrealm.com/what-is-negative-rainfall/)
* For languages where the user is inputting data, the number of data inputs can be "infinite"
* A complete implementation should handle error cases reasonably (asking the user for more input, skipping the bad value when encountered, etc)
The purpose of this problem, as originally proposed in the 1980's through its continued use today, is to just show fundamentals of CS: iteration, branching, program structure, termination, management of data types, input/output (where applicable), etc with things like input validation or management of numerical limits being more "advanced". It isn't meant to literally be a rainfall calculator so implementations should strive to implement the solution clearly and simply.
'''References:'''
* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf
* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf
* https://en.wikipedia.org/wiki/Moving_average#Cumulative_average
| namespace RosettaCode
{
class CSharpRecurringRainfall
{
static int ReadNextInput()
{
System.Console.Write("Enter rainfall int, 99999 to quit: ");
string input = System.Console.ReadLine();
if (System.Int32.TryParse(input, out int num))
{
return num;
}
else
{
System.Console.WriteLine("Invalid input");
return ReadNextInput();
}
}
static void Main()
{
double currentAverage = 0;
int currentEntryNumber = 0;
for (int lastInput = ReadNextInput(); lastInput != 99999; lastInput = ReadNextInput())
{
currentEntryNumber++;
currentAverage = currentAverage + (1.0/(float)currentEntryNumber)*lastInput - (1.0/(float)currentEntryNumber)*currentAverage;
System.Console.WriteLine("New Average: " + currentAverage);
}
}
}
}
|
Solve a Hidato puzzle | C sharp | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
** The grid is not necessarily rectangular.
** The grid may have holes in it.
** The grid is always connected.
** The number "1" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from "1" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
** A square may only contain one number.
* In a proper Hidato puzzle, the solution is unique.
For example the following problem
Sample Hidato problem, from Wikipedia
has the following solution, with path marked on it:
Solution to sample Hidato problem
;Related tasks:
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]];
| using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
//other puzzle types elided
hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)};
private (int dx, int dy)[] moves;
public static void Main()
{
Print(new Solver(hidatoMoves).Solve(false, new [,] {
{ 0, 33, 35, 0, 0, -1, -1, -1 },
{ 0, 0, 24, 22, 0, -1, -1, -1 },
{ 0, 0, 0, 21, 0, 0, -1, -1 },
{ 0, 26, 0, 13, 40, 11, -1, -1 },
{ 27, 0, 0, 0, 9, 0, 1, -1 },
{ -1, -1, 0, 0, 18, 0, 0, -1 },
{ -1, -1, -1, -1, 0, 7, 0, 0 },
{ -1, -1, -1, -1, -1, -1, 5, 0 }
}));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
} |
Solve a Holy Knight's tour | C sharp | Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution to such problems. At least demonstrate your program by solving the following:
;Example:
0 0 0
0 0 0
0 0 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0 0 0
0 0 0
0 0 0
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
;Related tasks:
* [[A* search algorithm]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
//other puzzle types elided
knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};
private (int dx, int dy)[] moves;
public static void Main()
{
var knightSolver = new Solver(knightMoves);
Print(knightSolver.Solve(true,
".000....",
".0.00...",
".0000000",
"000..0.0",
"0.0..000",
"1000000.",
"..00.0..",
"...000.."));
Print(knightSolver.Solve(true,
".....0.0.....",
".....0.0.....",
"....00000....",
".....000.....",
"..0..0.0..0..",
"00000...00000",
"..00.....00..",
"00000...00000",
"..0..0.0..0..",
".....000.....",
"....00000....",
".....0.0.....",
".....0.0....."
));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
} |
Solve a Hopido puzzle | C sharp | Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:
"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7x7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!"
Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.
Example:
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 0 . . .
Extra credits are available for other interesting designs.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
//other puzzle types elided
hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},
private (int dx, int dy)[] moves;
public static void Main()
{
Print(new Solver(hopidoMoves).Solve(false,
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
} |
Solve a Numbrix puzzle | C sharp | Numbrix puzzles are similar to Hidato.
The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood).
Published puzzles also tend not to have holes in the grid and may not always indicate the end node.
Two examples follow:
;Example 1
Problem.
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
Solution.
49 50 51 52 53 54 75 76 81
48 47 46 45 44 55 74 77 80
37 38 39 40 43 56 73 78 79
36 35 34 41 42 57 72 71 70
31 32 33 14 13 58 59 68 69
30 17 16 15 12 61 60 67 66
29 18 19 20 11 62 63 64 65
28 25 24 21 10 1 2 3 4
27 26 23 22 9 8 7 6 5
;Example 2
Problem.
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
Solution.
9 10 13 14 19 20 63 64 65
8 11 12 15 18 21 62 61 66
7 6 5 16 17 22 59 60 67
34 33 4 3 24 23 58 57 68
35 32 31 2 25 54 55 56 69
36 37 30 1 26 53 74 73 70
39 38 29 28 27 52 75 72 71
40 43 44 47 48 51 76 77 78
41 42 45 46 49 50 81 80 79
;Task
Write a program to solve puzzles of this ilk,
demonstrating your program by solving the above examples.
Extra credit for other interesting examples.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve the no connection puzzle]]
| using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
//other puzzle types elided
numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};
private (int dx, int dy)[] moves;
public static void Main()
{
var numbrixSolver = new Solver(numbrixMoves);
Print(numbrixSolver.Solve(false, new [,] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 46, 45, 0, 55, 74, 0, 0 },
{ 0, 38, 0, 0, 43, 0, 0, 78, 0 },
{ 0, 35, 0, 0, 0, 0, 0, 71, 0 },
{ 0, 0, 33, 0, 0, 0, 59, 0, 0 },
{ 0, 17, 0, 0, 0, 0, 0, 67, 0 },
{ 0, 18, 0, 0, 11, 0, 0, 64, 0 },
{ 0, 0, 24, 21, 0, 1, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
}));
Print(numbrixSolver.Solve(false, new [,] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 11, 12, 15, 18, 21, 62, 61, 0 },
{ 0, 6, 0, 0, 0, 0, 0, 60, 0 },
{ 0, 33, 0, 0, 0, 0, 0, 57, 0 },
{ 0, 32, 0, 0, 0, 0, 0, 56, 0 },
{ 0, 37, 0, 1, 0, 0, 0, 73, 0 },
{ 0, 38, 0, 0, 0, 0, 0, 72, 0 },
{ 0, 43, 44, 47, 48, 51, 76, 77, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
}));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
} |
Split a character string based on change of character | C sharp | Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
| using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
string s = @"gHHH5YY++///\";
Console.WriteLine(s.RunLengthSplit().Delimit(", "));
}
public static class Extensions
{
public static IEnumerable<string> RunLengthSplit(this string source) {
using (var enumerator = source.GetEnumerator()) {
if (!enumerator.MoveNext()) yield break;
char previous = enumerator.Current;
int count = 1;
while (enumerator.MoveNext()) {
if (previous == enumerator.Current) {
count++;
} else {
yield return new string(Enumerable.Repeat(previous, count).ToArray());
previous = enumerator.Current;
count = 1;
}
}
yield return new string(Enumerable.Repeat(previous, count).ToArray());
}
}
public static string Delimit<T>(this IEnumerable<T> source, string separator = "") => string.Join(separator ?? "", source);
} |
Square but not cube | C sharp | Show the first '''30''' positive integers which are squares but not cubes of such integers.
Optionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.
| using System;
using System.Collections.Generic;
using static System.Console;
using static System.Linq.Enumerable;
public static class SquareButNotCube
{
public static void Main() {
var squares = from i in Integers() select i * i;
var cubes = from i in Integers() select i * i * i;
foreach (var x in Merge().Take(33)) {
WriteLine(x.isCube ? x.n + " (also cube)" : x.n + "");
}
IEnumerable<int> Integers() {
for (int i = 1; ;i++) yield return i;
}
IEnumerable<(int n, bool isCube)> Merge() {
using (var s = squares.GetEnumerator())
using (var c = cubes.GetEnumerator()) {
s.MoveNext();
c.MoveNext();
while (true) {
if (s.Current < c.Current) {
yield return (s.Current, false);
s.MoveNext();
} else if (s.Current == c.Current) {
yield return (s.Current, true);
s.MoveNext();
c.MoveNext();
} else {
c.MoveNext();
}
}
}
}
}
} |
Stern-Brocot sequence | C sharp|C# | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].
# The first and second members of the sequence are both 1:
#* 1, 1
# Start by considering the second member of the sequence
# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
#* 1, 1, 2
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1
# Consider the next member of the series, (the third member i.e. 2)
# GOTO 3
#*
#* --- Expanding another loop we get: ---
#*
# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
#* 1, 1, 2, 1, 3
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1, 3, 2
# Consider the next member of the series, (the fourth member i.e. 1)
;The task is to:
* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
;Related tasks:
:* [[Fusc sequence]].
:* [[Continued fraction/Arithmetic]]
;Ref:
* Infinite Fractions - Numberphile (Video).
* Trees, Teeth, and Time: The mathematics of clock making.
* A002487 The On-Line Encyclopedia of Integer Sequences.
| using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static List<int> l = new List<int>() { 1, 1 };
static int gcd(int a, int b) {
return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }
static void Main(string[] args) {
int max = 1000; int take = 15; int i = 1;
int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };
do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }
while (l.Count < max || l[l.Count - 2] != selection.Last());
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take);
Console.WriteLine("{0}\n", string.Join(", ", l.Take(take)));
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:");
foreach (int ii in selection) {
int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); }
Console.WriteLine(); bool good = true;
for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" +
" series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
}
} |
Stream merge | C sharp|C# | 2-stream merge
: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
; ''N''-stream merge
: The same as above, but reading from ''N'' sources.
: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| using System;
using System.Collections.Generic;
using System.Linq;
namespace RosettaCode
{
static class StreamMerge
{
static IEnumerable<T> Merge2<T>(IEnumerable<T> source1, IEnumerable<T> source2) where T : IComparable
{
var q1 = new Queue<T>(source1);
var q2 = new Queue<T>(source2);
while (q1.Any() && q2.Any())
{
var c = q1.Peek().CompareTo(q2.Peek());
if (c <= 0) yield return q1.Dequeue(); else yield return q2.Dequeue();
}
while (q1.Any()) yield return q1.Dequeue();
while (q2.Any()) yield return q2.Dequeue();
}
static IEnumerable<T> MergeN<T>(params IEnumerable<T>[] sources) where T : IComparable
{
var queues = sources.Select(e => new Queue<T>(e)).Where(q => q.Any()).ToList();
var headComparer = Comparer<Queue<T>>.Create((x, y) => x.Peek().CompareTo(y.Peek()));
queues.Sort(headComparer);
while (queues.Any())
{
var q = queues.First();
queues.RemoveAt(0);
yield return q.Dequeue();
if (q.Any())
{
var index = queues.BinarySearch(q, headComparer);
queues.Insert(index < 0 ? ~index : index, q);
}
}
}
static void Main()
{
var a = new[] { 1, 4, 7, 10 };
var b = new[] { 2, 5, 8, 11 };
var c = new[] { 3, 6, 9, 12 };
foreach (var i in Merge2(a, b)) Console.Write($"{i} ");
Console.WriteLine();
foreach (var i in MergeN(a, b, c)) Console.Write($"{i} ");
Console.WriteLine();
}
}
} |
Strip control codes and extended characters from a string | C sharp|C# | Strip control codes and extended characters from a string.
The solution should demonstrate how to achieve each of the following results:
:* a string with control codes stripped (but extended characters not stripped)
:* a string with control codes and extended characters stripped
In ASCII, the control codes have decimal codes 0 through to 31 and 127.
On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.
On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string test = "string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄";
Console.WriteLine("Original: {0}", test);
Console.WriteLine("Stripped of control codes: {0}", StripControlChars(test));
Console.WriteLine("Stripped of extended: {0}", StripExtended(test));
}
static string StripControlChars(string arg)
{
char[] arrForm = arg.ToCharArray();
StringBuilder buffer = new StringBuilder(arg.Length);//This many chars at most
foreach(char ch in arrForm)
if (!Char.IsControl(ch)) buffer.Append(ch);//Only add to buffer if not a control char
return buffer.ToString();
}
static string StripExtended(string arg)
{
StringBuilder buffer = new StringBuilder(arg.Length); //Max length
foreach(char ch in arg)
{
UInt16 num = Convert.ToUInt16(ch);//In .NET, chars are UTF-16
//The basic characters have the same code points as ASCII, and the extended characters are bigger
if((num >= 32u) && (num <= 126u)) buffer.Append(ch);
}
return buffer.ToString();
}
}
}
|
Subleq | C sharp|C# from Java | One-Instruction Set Computer (OISC).
It is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero.
;Task
Your task is to create an interpreter which emulates a SUBLEQ machine.
The machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:
::::* simple numeric values
::::* memory addresses
::::* characters for input or output
Any reasonable word size that accommodates all three of the above uses is fine.
The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:
:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.
:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.
:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.
:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.
:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.
:# If the instruction pointer becomes negative, execution halts.
Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).
For purposes of this task, show the output of your solution when fed the below "Hello, world!" program.
As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.
15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0
The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:
start:
0f 11 ff subleq (zero), (message), -1
11 ff ff subleq (message), -1, -1 ; output character at message
10 01 ff subleq (neg1), (start+1), -1
10 03 ff subleq (neg1), (start+3), -1
0f 0f 00 subleq (zero), (zero), start
; useful constants
zero:
00 .data 0
neg1:
ff .data -1
; the message to print
message: .data "Hello, world!\n\0"
48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
| using System;
namespace Subleq {
class Program {
static void Main(string[] args) {
int[] mem = {
15, 17, -1, 17, -1, -1, 16, 1, -1, 16,
3, -1, 15, 15, 0, 0, -1, 72, 101, 108,
108, 111, 44, 32, 119, 111, 114, 108, 100, 33,
10, 0,
};
int instructionPointer = 0;
do {
int a = mem[instructionPointer];
int b = mem[instructionPointer + 1];
if (a == -1) {
mem[b] = Console.Read();
}
else if (b == -1) {
Console.Write((char)mem[a]);
}
else {
mem[b] -= mem[a];
if (mem[b] < 1) {
instructionPointer = mem[instructionPointer + 2];
continue;
}
}
instructionPointer += 3;
} while (instructionPointer >= 0);
}
}
} |
Substring/Top and tail | C sharp | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
* String with first character removed
* String with last character removed
* String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
| using System;
class Program
{
static void Main(string[] args)
{
string testString = "test";
Console.WriteLine(testString.Substring(1));
Console.WriteLine(testString.Substring(0, testString.Length - 1));
Console.WriteLine(testString.Substring(1, testString.Length - 2));
}
}
|
Sum and product puzzle | C sharp | * Wikipedia: Sum and Product Puzzle
| using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const int maxSum = 100;
var pairs = (
from X in 2.To(maxSum / 2 - 1)
from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)
select new { X, Y, S = X + Y, P = X * Y }
).ToHashSet();
Console.WriteLine(pairs.Count);
var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
foreach (var pair in pairs) Console.WriteLine(pair);
}
}
public static class Extensions
{
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i <= end; i++) yield return i;
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
} |
Sum digits of an integer | C sharp|C# | Take a Natural Number in a given base and return the sum of its digits:
:* '''1'''10 sums to '''1'''
:* '''1234'''10 sums to '''10'''
:* '''fe'''16 sums to '''29'''
:* '''f0e'''16 sums to '''29'''
| namespace RosettaCode.SumDigitsOfAnInteger
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class Program
{
/// <summary>
/// Enumerates the digits of a number in a given base.
/// </summary>
/// <param name="number"> The number. </param>
/// <param name="base"> The base. </param>
/// <returns> The digits of the number in the given base. </returns>
/// <remarks>
/// The digits are enumerated from least to most significant.
/// </remarks>
private static IEnumerable<int> Digits(this int number, int @base = 10)
{
while (number != 0)
{
int digit;
number = Math.DivRem(number, @base, out digit);
yield return digit;
}
}
/// <summary>
/// Sums the digits of a number in a given base.
/// </summary>
/// <param name="number"> The number. </param>
/// <param name="base"> The base. </param>
/// <returns> The sum of the digits of the number in the given base. </returns>
private static int SumOfDigits(this int number, int @base = 10)
{
return number.Digits(@base).Sum();
}
/// <summary>
/// Demonstrates <see cref="SumOfDigits" />.
/// </summary>
private static void Main()
{
foreach (var example in
new[]
{
new {Number = 1, Base = 10},
new {Number = 12345, Base = 10},
new {Number = 123045, Base = 10},
new {Number = 0xfe, Base = 0x10},
new {Number = 0xf0e, Base = 0x10}
})
{
Console.WriteLine(example.Number.SumOfDigits(example.Base));
}
}
}
} |
Sum multiples of 3 and 5 | C sharp|C# | The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''.
Show output for ''n'' = 1000.
This is is the same as Project Euler problem 1.
'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.
| using System;
using System.Collections.Generic;
using System.Numerics;
namespace RosettaCode
{
class Program
{
static void Main()
{
List<BigInteger> candidates = new List<BigInteger>(new BigInteger[] { 1000, 100000, 10000000, 10000000000, 1000000000000000 });
candidates.Add(BigInteger.Parse("100000000000000000000"));
foreach (BigInteger candidate in candidates)
{
BigInteger c = candidate - 1;
BigInteger answer3 = GetSumOfNumbersDivisibleByN(c, 3);
BigInteger answer5 = GetSumOfNumbersDivisibleByN(c, 5);
BigInteger answer15 = GetSumOfNumbersDivisibleByN(c, 15);
Console.WriteLine("The sum of numbers divisible by 3 or 5 between 1 and {0} is {1}", c, answer3 + answer5 - answer15);
}
Console.ReadKey(true);
}
private static BigInteger GetSumOfNumbersDivisibleByN(BigInteger candidate, uint n)
{
BigInteger largest = candidate;
while (largest % n > 0)
largest--;
BigInteger totalCount = (largest / n);
BigInteger pairCount = totalCount / 2;
bool unpairedNumberOnFoldLine = (totalCount % 2 == 1);
BigInteger pairSum = largest + n;
return pairCount * pairSum + (unpairedNumberOnFoldLine ? pairSum / 2 : 0);
}
}
}
|
Sum to 100 | C sharp|C# | Find solutions to the ''sum to one hundred'' puzzle.
Add (insert) the mathematical
operators '''+''' or '''-''' (plus
or minus) before any of the digits in the
decimal numeric string '''123456789''' such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, '''100''').
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
:* Show all solutions that sum to '''100'''
:* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++)
:* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task
:* Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
++ (where ''infinity'' would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: '''5074'''
(which, of course, isn't the lowest positive sum that can't be expressed).
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// All unique expressions that have a plus sign in front of the 1; calculated in parallel
var expressionsPlus = Enumerable.Range(0, (int)Math.Pow(3, 8)).AsParallel().Select(i => new Expression(i, 1));
// All unique expressions that have a minus sign in front of the 1; calculated in parallel
var expressionsMinus = Enumerable.Range(0, (int)Math.Pow(3, 8)).AsParallel().Select(i => new Expression(i, -1));
var expressions = expressionsPlus.Concat(expressionsMinus);
var results = new Dictionary<int, List<Expression>>();
foreach (var e in expressions)
{
if (results.Keys.Contains(e.Value))
results[e.Value].Add(e);
else
results[e.Value] = new List<Expression>() { e };
}
Console.WriteLine("Show all solutions that sum to 100");
foreach (Expression e in results[100])
Console.WriteLine(" " + e);
Console.WriteLine("Show the sum that has the maximum number of solutions (from zero to infinity)");
var summary = results.Keys.Select(k => new Tuple<int, int>(k, results[k].Count));
var maxSols = summary.Aggregate((a, b) => a.Item2 > b.Item2 ? a : b);
Console.WriteLine(" The sum " + maxSols.Item1 + " has " + maxSols.Item2 + " solutions.");
Console.WriteLine("Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task");
var lowestPositive = Enumerable.Range(1, int.MaxValue).First(x => !results.Keys.Contains(x));
Console.WriteLine(" " + lowestPositive);
Console.WriteLine("Show the ten highest numbers that can be expressed using the rules for this task (extra credit)");
var highest = from k in results.Keys
orderby k descending
select k;
foreach (var x in highest.Take(10))
Console.WriteLine(" " + x);
}
}
public enum Operations { Plus, Minus, Join };
public class Expression
{
protected Operations[] Gaps;
// 123456789 => there are 8 "gaps" between each number
/// with 3 possibilities for each gap: plus, minus, or join
public int Value; // What this expression sums up to
protected int _one;
public Expression(int serial, int one)
{
_one = one;
Gaps = new Operations[8];
// This represents "serial" as a base 3 number, each Gap expression being a base-three digit
int divisor = 2187; // == Math.Pow(3,7)
int times;
for (int i = 0; i < 8; i++)
{
times = Math.DivRem(serial, divisor, out serial);
divisor /= 3;
if (times == 0)
Gaps[i] = Operations.Join;
else if (times == 1)
Gaps[i] = Operations.Minus;
else
Gaps[i] = Operations.Plus;
}
// go ahead and calculate the value of this expression
// because this is going to be done in a parallel thread (save time)
Value = Evaluate();
}
public override string ToString()
{
string ret = _one.ToString();
for (int i = 0; i < 8; i++)
{
switch (Gaps[i])
{
case Operations.Plus:
ret += "+";
break;
case Operations.Minus:
ret += "-";
break;
}
ret += (i + 2);
}
return ret;
}
private int Evaluate()
/* Calculate what this expression equals */
{
var numbers = new int[9];
int nc = 0;
var operations = new List<Operations>();
int a = 1;
for (int i = 0; i < 8; i++)
{
if (Gaps[i] == Operations.Join)
a = a * 10 + (i + 2);
else
{
if (a > 0)
{
if (nc == 0)
a *= _one;
numbers[nc++] = a;
a = i + 2;
}
operations.Add(Gaps[i]);
}
}
if (nc == 0)
a *= _one;
numbers[nc++] = a;
int ni = 0;
int left = numbers[ni++];
foreach (var operation in operations)
{
int right = numbers[ni++];
if (operation == Operations.Plus)
left = left + right;
else
left = left - right;
}
return left;
}
} |
Tarjan | C sharp|C# | {{wikipedia|Graph}}
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
;References:
* The article on Wikipedia.
See also: [[Kosaraju]]
| using System;
using System.Collections.Generic;
class Node
{
public int LowLink { get; set; }
public int Index { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
Index = -1;
LowLink = 0;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>> Adj { get; }
/// <summary>
/// Tarjan's strongly connected components algorithm
/// </summary>
public void Tarjan()
{
var index = 0; // number of nodes
var S = new Stack<Node>();
Action<Node> StrongConnect = null;
StrongConnect = (v) =>
{
// Set the depth index for v to the smallest unused index
v.Index = index;
v.LowLink = index;
index++;
S.Push(v);
// Consider successors of v
foreach (var w in Adj[v])
if (w.Index < 0)
{
// Successor w has not yet been visited; recurse on it
StrongConnect(w);
v.LowLink = Math.Min(v.LowLink, w.LowLink);
}
else if (S.Contains(w))
// Successor w is in stack S and hence in the current SCC
v.LowLink = Math.Min(v.LowLink, w.Index);
// If v is a root node, pop the stack and generate an SCC
if (v.LowLink == v.Index)
{
Console.Write("SCC: ");
Node w;
do
{
w = S.Pop();
Console.Write(w.N + " ");
} while (w != v);
Console.WriteLine();
}
};
foreach (var v in V)
if (v.Index < 0)
StrongConnect(v);
}
} |
Temperature conversion | C sharp|C# | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
: 0 degrees Celsius corresponds to 273.15 kelvin.
: 0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
: 0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
;Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
;Example:
K 21.00
C -252.15
F -421.87
R 37.80
| using System;
namespace TemperatureConversion
{
class Program
{
static Func<double, double> ConvertKelvinToFahrenheit = x => (x * 1.8) - 459.67;
static Func<double, double> ConvertKelvinToRankine = x => x * 1.8;
static Func<double, double> ConvertKelvinToCelsius = x => x = 273.13;
static void Main(string[] args)
{
Console.Write("Enter a Kelvin Temperature: ");
string inputVal = Console.ReadLine();
double kelvinTemp = 0f;
if (double.TryParse(inputVal, out kelvinTemp))
{
Console.WriteLine(string.Format("Kelvin: {0}", kelvinTemp));
Console.WriteLine(string.Format("Fahrenheit: {0}", ConvertKelvinToFahrenheit(kelvinTemp)));
Console.WriteLine(string.Format("Rankine: {0}", ConvertKelvinToRankine(kelvinTemp)));
Console.WriteLine(string.Format("Celsius: {0}", ConvertKelvinToCelsius(kelvinTemp)));
Console.ReadKey();
}
else
{
Console.WriteLine("Invalid input value: " + inputVal);
}
}
}
} |
Test integerness | C sharp|C# | {| class="wikitable"
|-
! colspan=2 | Input
! colspan=2 | Output
! rowspan=2 | Comment
|-
! Type
! Value
! exact
! tolerance = 0.00001
|-
| rowspan=3 | decimal
| 25.000000
| colspan=2 | true
|
|-
| 24.999999
| false
| true
|
|-
| 25.000100
| colspan=2 | false
|
|-
| rowspan=4 | floating-point
| -2.1e120
| colspan=2 | true
| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.
|-
| -5e-2
| colspan=2 | false
|
|-
| NaN
| colspan=2 | false
|
|-
| Inf
| colspan=2 | false
| This one is debatable. If your code considers it an integer, that's okay too.
|-
| rowspan=2 | complex
| 5.0+0.0i
| colspan=2 | true
|
|-
| 5-5i
| colspan=2 | false
|
|}
(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)
| namespace Test_integerness
{
class Program
{
public static void Main(string[] args)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine(" ***************************************************");
Console.WriteLine(" * *");
Console.WriteLine(" * Integerness test *");
Console.WriteLine(" * *");
Console.WriteLine(" ***************************************************");
Console.WriteLine();
ConsoleKeyInfo key = new ConsoleKeyInfo('Y',ConsoleKey.Y,true,true,true);
while(key.Key == ConsoleKey.Y)
{
// Get number value from keyboard
Console.Write(" Enter number value : ");
string LINE = Console.ReadLine();
// Get tolerance value from keyboard
Console.Write(" Enter tolerance value : ");
double TOLERANCE = double.Parse(Console.ReadLine());
// Resolve entered number format and set NUMBER value
double NUMBER = 0;
string [] N;
// Real number value
if(!double.TryParse(LINE, out NUMBER))
{
// Rational number value
if(LINE.Contains("/"))
{
N = LINE.Split('/');
NUMBER = double.Parse(N[0]) / double.Parse(N[1]);
}
// Inf value
else if(LINE.ToUpper().Contains("INF"))
{
NUMBER = double.PositiveInfinity;
}
// Complex value
else if(LINE.ToUpper().Contains("I"))
{
// Delete letter i
LINE = LINE.ToUpper().Replace("I","");
string r = string.Empty; // real part
string i = string.Empty; // imaginary part
int s = 1; // sign offset
// Get sign
if(LINE[0]=='+' || LINE[0]=='-')
{
r+=LINE[0].ToString();
LINE = LINE.Remove(0,1);
s--;
}
// Get real part
foreach (char element in LINE)
{
if(element!='+' && element!='-')
r+=element.ToString();
else
break;
}
// get imaginary part
i = LINE.Substring(LINE.Length-(r.Length+s));
NUMBER = double.Parse(i);
if(NUMBER==0)
NUMBER = double.Parse(r);
else
NUMBER = double.NaN;
}
// NaN value
else
NUMBER = double.NaN;
}
// Test
bool IS_INTEGER = false;
bool IS_INTEGER_T = false;
if(double.IsNaN(NUMBER))
IS_INTEGER=false;
else if(Math.Round(NUMBER,0).ToString() == NUMBER.ToString())
IS_INTEGER = true;
else if((decimal)TOLERANCE >= (decimal)Math.Abs( (decimal)Math.Round(NUMBER,0) - (decimal)NUMBER ))
IS_INTEGER_T = true;
if(IS_INTEGER)
Console.WriteLine(" Is exact integer " + IS_INTEGER);
else
{
Console.WriteLine( " Is exact integer " + IS_INTEGER );
Console.WriteLine( " Is integer with tolerance " + IS_INTEGER_T );
}
Console.WriteLine();
Console.Write(" Another test < Y /N > . . . ");
key = Console.ReadKey(true);
Console.WriteLine();
Console.WriteLine();
}
}
}
}
|
The Name Game | C sharp|C# from Java | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
| using System;
using System.Collections.Generic;
using System.Text;
namespace TheNameGame {
class Program {
static void PrintVerse(string name) {
StringBuilder sb = new StringBuilder(name.ToLower());
sb[0] = Char.ToUpper(sb[0]);
string x = sb.ToString();
string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1);
string b = "b" + y;
string f = "f" + y;
string m = "m" + y;
switch (x[0]) {
case 'B':
b = y;
break;
case 'F':
f = y;
break;
case 'M':
m = y;
break;
}
Console.WriteLine("{0}, {0}, bo-{1}", x, b);
Console.WriteLine("Banana-fana fo-{0}", f);
Console.WriteLine("Fee-fi-mo-{0}", m);
Console.WriteLine("{0}!", x);
Console.WriteLine();
}
static void Main(string[] args) {
List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" };
nameList.ForEach(PrintVerse);
}
}
} |
The Twelve Days of Christmas | C sharp|C# | Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
| using System;
public class TwelveDaysOfChristmas {
public static void Main() {
string[] days = new string[12] {
"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
"tenth", "eleventh", "twelfth",
};
string[] gifts = new string[12] {
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"
};
for ( int i = 0; i < 12; i++ ) {
Console.WriteLine("On the " + days[i] + " day of Christmas, my true love gave to me");
int j = i + 1;
while ( j-- > 0 )
Console.WriteLine(gifts[j]);
Console.WriteLine();
if ( i == 0 )
gifts[0] = "And a partridge in a pear tree";
}
}
} |
Thue-Morse | C sharp|C# from Java | Create a Thue-Morse sequence.
;See also
* YouTube entry: The Fairest Sharing Sequence Ever
* YouTube entry: Math and OCD - My story with the Thue-Morse sequence
* Task: [[Fairshare between two and more]]
| using System;
using System.Text;
namespace ThueMorse
{
class Program
{
static void Main(string[] args)
{
Sequence(6);
}
public static void Sequence(int steps)
{
var sb1 = new StringBuilder("0");
var sb2 = new StringBuilder("1");
for (int i = 0; i < steps; i++)
{
var tmp = sb1.ToString();
sb1.Append(sb2);
sb2.Append(tmp);
}
Console.WriteLine(sb1);
Console.ReadLine();
}
}
} |
Tonelli-Shanks algorithm | C sharp|C# from Java | {{wikipedia}}
In computational number theory, the Tonelli-Shanks algorithm is a technique for solving for '''x''' in a congruence of the form:
:: x2 n (mod p)
where '''n''' is an integer which is a quadratic residue (mod p), '''p''' is an odd prime, and '''x,n Fp''' where Fp = {0, 1, ..., p - 1}.
It is used in cryptography techniques.
To apply the algorithm, we need the Legendre symbol:
The Legendre symbol '''(a | p)''' denotes the value of a(p-1)/2 (mod p).
* '''(a | p) 1''' if '''a''' is a square (mod p)
* '''(a | p) -1''' if '''a''' is not a square (mod p)
* '''(a | p) 0''' if '''a''' 0 (mod p)
;Algorithm pseudo-code:
All are taken to mean (mod p) unless stated otherwise.
* Input: '''p''' an odd prime, and an integer '''n''' .
* Step 0: Check that '''n''' is indeed a square: (n | p) must be 1 .
* Step 1: By factoring out powers of 2 from p - 1, find '''q''' and '''s''' such that p - 1 = q2s with '''q''' odd .
** If p 3 (mod 4) (i.e. s = 1), output the two solutions r +- n(p+1)/4 .
* Step 2: Select a non-square '''z''' such that (z | p) -1 and set c zq .
* Step 3: Set r n(q+1)/2, t nq, m = s .
* Step 4: Loop the following:
** If t 1, output '''r''' and '''p - r''' .
** Otherwise find, by repeated squaring, the lowest '''i''', 0 < i < m , such that t2i 1 .
** Let b c2(m - i - 1), and set r rb, t tb2, c b2 and m = i .
;Task:
Implement the above algorithm.
Find solutions (if any) for
* n = 10 p = 13
* n = 56 p = 101
* n = 1030 p = 10009
* n = 1032 p = 10009
* n = 44402 p = 100049
;Extra credit:
* n = 665820697 p = 1000000009
* n = 881398088036 p = 1000000000039
* n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577
;See also:
* [[Modular exponentiation]]
* [[Cipolla's algorithm]]
| using System;
using System.Collections.Generic;
using System.Numerics;
namespace TonelliShanks {
class Solution {
private readonly BigInteger root1, root2;
private readonly bool exists;
public Solution(BigInteger root1, BigInteger root2, bool exists) {
this.root1 = root1;
this.root2 = root2;
this.exists = exists;
}
public BigInteger Root1() {
return root1;
}
public BigInteger Root2() {
return root2;
}
public bool Exists() {
return exists;
}
}
class Program {
static Solution Ts(BigInteger n, BigInteger p) {
if (BigInteger.ModPow(n, (p - 1) / 2, p) != 1) {
return new Solution(0, 0, false);
}
BigInteger q = p - 1;
BigInteger ss = 0;
while ((q & 1) == 0) {
ss = ss + 1;
q = q >> 1;
}
if (ss == 1) {
BigInteger r1 = BigInteger.ModPow(n, (p + 1) / 4, p);
return new Solution(r1, p - r1, true);
}
BigInteger z = 2;
while (BigInteger.ModPow(z, (p - 1) / 2, p) != p - 1) {
z = z + 1;
}
BigInteger c = BigInteger.ModPow(z, q, p);
BigInteger r = BigInteger.ModPow(n, (q + 1) / 2, p);
BigInteger t = BigInteger.ModPow(n, q, p);
BigInteger m = ss;
while (true) {
if (t == 1) {
return new Solution(r, p - r, true);
}
BigInteger i = 0;
BigInteger zz = t;
while (zz != 1 && i < (m - 1)) {
zz = zz * zz % p;
i = i + 1;
}
BigInteger b = c;
BigInteger e = m - i - 1;
while (e > 0) {
b = b * b % p;
e = e - 1;
}
r = r * b % p;
c = b * b % p;
t = t * c % p;
m = i;
}
}
static void Main(string[] args) {
List<Tuple<long, long>> pairs = new List<Tuple<long, long>>() {
new Tuple<long, long>(10, 13),
new Tuple<long, long>(56, 101),
new Tuple<long, long>(1030, 10009),
new Tuple<long, long>(1032, 10009),
new Tuple<long, long>(44402, 100049),
new Tuple<long, long>(665820697, 1000000009),
new Tuple<long, long>(881398088036, 1000000000039),
};
foreach (var pair in pairs) {
Solution sol = Ts(pair.Item1, pair.Item2);
Console.WriteLine("n = {0}", pair.Item1);
Console.WriteLine("p = {0}", pair.Item2);
if (sol.Exists()) {
Console.WriteLine("root1 = {0}", sol.Root1());
Console.WriteLine("root2 = {0}", sol.Root2());
} else {
Console.WriteLine("No solution exists");
}
Console.WriteLine();
}
BigInteger bn = BigInteger.Parse("41660815127637347468140745042827704103445750172002");
BigInteger bp = BigInteger.Pow(10, 50) + 577;
Solution bsol = Ts(bn, bp);
Console.WriteLine("n = {0}", bn);
Console.WriteLine("p = {0}", bp);
if (bsol.Exists()) {
Console.WriteLine("root1 = {0}", bsol.Root1());
Console.WriteLine("root2 = {0}", bsol.Root2());
} else {
Console.WriteLine("No solution exists");
}
}
}
} |
Top rank per group | C sharp|C# | Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
class Employee
{
public Employee(string name, string id, int salary, string department)
{
Name = name;
Id = id;
Salary = salary;
Department = department;
}
public string Name { get; private set; }
public string Id { get; private set; }
public int Salary { get; private set; }
public string Department { get; private set; }
public override string ToString()
{
return String.Format("{0, -25}\t{1}\t{2}", Name, Id, Salary);
}
}
private static void Main(string[] args)
{
var employees = new List<Employee>
{
new Employee("Tyler Bennett", "E10297", 32000, "D101"),
new Employee("John Rappl", "E21437", 47000, "D050"),
new Employee("George Woltman", "E21437", 53500, "D101"),
new Employee("Adam Smith", "E21437", 18000, "D202"),
new Employee("Claire Buckman", "E39876", 27800, "D202"),
new Employee("David McClellan", "E04242", 41500, "D101"),
new Employee("Rich Holcomb", "E01234", 49500, "D202"),
new Employee("Nathan Adams", "E41298", 21900, "D050"),
new Employee("Richard Potter", "E43128", 15900, "D101"),
new Employee("David Motsinger", "E27002", 19250, "D202"),
new Employee("Tim Sampair", "E03033", 27000, "D101"),
new Employee("Kim Arlich", "E10001", 57000, "D190"),
new Employee("Timothy Grove", "E16398", 29900, "D190")
};
DisplayTopNPerDepartment(employees, 2);
}
static void DisplayTopNPerDepartment(IEnumerable<Employee> employees, int n)
{
var topSalariesByDepartment =
from employee in employees
group employee by employee.Department
into g
select new
{
Department = g.Key,
TopEmployeesBySalary = g.OrderByDescending(e => e.Salary).Take(n)
};
foreach (var x in topSalariesByDepartment)
{
Console.WriteLine("Department: " + x.Department);
foreach (var employee in x.TopEmployeesBySalary)
Console.WriteLine(employee);
Console.WriteLine("----------------------------");
}
}
} |
Truncate a file | C sharp | Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged.
If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.
On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.
This task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
| using System;
using System.IO;
namespace TruncateFile
{
internal class Program
{
private static void Main(string[] args)
{
TruncateFile(args[0], long.Parse(args[1]));
}
private static void TruncateFile(string path, long length)
{
if (!File.Exists(path))
throw new ArgumentException("No file found at specified path.", "path");
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Write))
{
if (fileStream.Length < length)
throw new ArgumentOutOfRangeException("length",
"The specified length is greater than that of the file.");
fileStream.SetLength(length);
}
}
}
} |
Truth table | C sharp 7 | A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.
;Task:
# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).
# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.
# Either reverse-polish or infix notation expressions are allowed.
;Related tasks:
* [[Boolean values]]
* [[Ternary logic]]
;See also:
* Wolfram MathWorld entry on truth tables.
* some "truth table" examples from Google.
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class TruthTable
{
enum TokenType { Unknown, WhiteSpace, Constant, Operand, Operator, LeftParenthesis, RightParenthesis }
readonly char trueConstant, falseConstant;
readonly IDictionary<char, Operator> operators = new Dictionary<char, Operator>();
public TruthTable(char falseConstant, char trueConstant)
{
this.trueConstant = trueConstant;
this.falseConstant = falseConstant;
Operators = new OperatorCollection(operators);
}
public OperatorCollection Operators { get; }
public void PrintTruthTable(string expression, bool isPostfix = false)
{
try {
foreach (string line in GetTruthTable(expression, isPostfix)) {
Console.WriteLine(line);
}
} catch (ArgumentException ex) {
Console.WriteLine(expression + " " + ex.Message);
}
}
public IEnumerable<string> GetTruthTable(string expression, bool isPostfix = false)
{
if (string.IsNullOrWhiteSpace(expression)) throw new ArgumentException("Invalid expression.");
//Maps parameters to an index in BitSet
//Makes sure they appear in the truth table in the order they first appear in the expression
var parameters = expression
.Where(c => TypeOf(c) == TokenType.Operand)
.Distinct()
.Reverse()
.Select((c, i) => (symbol: c, index: i))
.ToDictionary(p => p.symbol, p => p.index);
int count = parameters.Count;
if (count > 32) throw new ArgumentException("Cannot have more than 32 parameters.");
string header = count == 0 ? expression : string.Join(" ",
parameters.OrderByDescending(p => p.Value).Select(p => p.Key)) + " " + expression;
if (!isPostfix) expression = ConvertToPostfix(expression);
var values = default(BitSet);
var stack = new Stack<char>(expression.Length);
for (int loop = 1 << count; loop > 0; loop--) {
foreach (char token in expression) stack.Push(token);
bool result = Evaluate(stack, values, parameters);
if (header != null) {
if (stack.Count > 0) throw new ArgumentException("Invalid expression.");
yield return header;
header = null;
}
string line = (count == 0 ? "" : " ") + (result ? trueConstant : falseConstant);
line = string.Join(" ", Enumerable.Range(0, count)
.Select(i => values[count - i - 1] ? trueConstant : falseConstant)) + line;
yield return line;
values++;
}
}
public string ConvertToPostfix(string infix)
{
var stack = new Stack<char>();
var postfix = new StringBuilder();
foreach (char c in infix) {
switch (TypeOf(c)) {
case TokenType.WhiteSpace:
continue;
case TokenType.Constant:
case TokenType.Operand:
postfix.Append(c);
break;
case TokenType.Operator:
int precedence = Precedence(c);
while (stack.Count > 0 && Precedence(stack.Peek()) > precedence) {
postfix.Append(stack.Pop());
}
stack.Push(c);
break;
case TokenType.LeftParenthesis:
stack.Push(c);
break;
case TokenType.RightParenthesis:
char top = default(char);
while (stack.Count > 0) {
top = stack.Pop();
if (top == '(') break;
else postfix.Append(top);
}
if (top != '(') throw new ArgumentException("No matching left parenthesis.");
break;
default:
throw new ArgumentException("Invalid character: " + c);
}
}
while (stack.Count > 0) {
char top = stack.Pop();
if (top == '(') throw new ArgumentException("No matching right parenthesis.");
postfix.Append(top);
}
return postfix.ToString();
}
private bool Evaluate(Stack<char> expression, BitSet values, IDictionary<char, int> parameters)
{
if (expression.Count == 0) throw new ArgumentException("Invalid expression.");
char c = expression.Pop();
TokenType type = TypeOf(c);
while (type == TokenType.WhiteSpace) type = TypeOf(c = expression.Pop());
switch (type) {
case TokenType.Constant:
return c == trueConstant;
case TokenType.Operand:
return values[parameters[c]];
case TokenType.Operator:
bool right = Evaluate(expression, values, parameters);
Operator op = operators[c];
if (op.Arity == 1) return op.Function(right, right);
bool left = Evaluate(expression, values, parameters);
return op.Function(left, right);
default:
throw new ArgumentException("Invalid character: " + c);
}
}
private TokenType TypeOf(char c)
{
if (char.IsWhiteSpace(c)) return TokenType.WhiteSpace;
if (c == '(') return TokenType.LeftParenthesis;
if (c == ')') return TokenType.RightParenthesis;
if (c == trueConstant || c == falseConstant) return TokenType.Constant;
if (operators.ContainsKey(c)) return TokenType.Operator;
if (char.IsLetter(c)) return TokenType.Operand;
return TokenType.Unknown;
}
private int Precedence(char op) => operators.TryGetValue(op, out var o) ? o.Precedence : int.MinValue;
}
struct Operator
{
public Operator(char symbol, int precedence, Func<bool, bool> function) : this(symbol, precedence, 1, (l, r) => function(r)) { }
public Operator(char symbol, int precedence, Func<bool, bool, bool> function) : this(symbol, precedence, 2, function) { }
private Operator(char symbol, int precedence, int arity, Func<bool, bool, bool> function) : this()
{
Symbol = symbol;
Precedence = precedence;
Arity = arity;
Function = function;
}
public char Symbol { get; }
public int Precedence { get; }
public int Arity { get; }
public Func<bool, bool, bool> Function { get; }
}
public class OperatorCollection : IEnumerable
{
readonly IDictionary<char, Operator> operators;
internal OperatorCollection(IDictionary<char, Operator> operators) {
this.operators = operators;
}
public void Add(char symbol, int precedence, Func<bool, bool> function)
=> operators[symbol] = new Operator(symbol, precedence, function);
public void Add(char symbol, int precedence, Func<bool, bool, bool> function)
=> operators[symbol] = new Operator(symbol, precedence, function);
public void Remove(char symbol) => operators.Remove(symbol);
IEnumerator IEnumerable.GetEnumerator() => operators.Values.GetEnumerator();
}
struct BitSet
{
private int bits;
private BitSet(int bits) { this.bits = bits; }
public static BitSet operator ++(BitSet bitSet) => new BitSet(bitSet.bits + 1);
public bool this[int index] => (bits & (1 << index)) != 0;
}
class Program
{
public static void Main() {
TruthTable tt = new TruthTable('F', 'T') {
Operators = {
{ '!', 6, r => !r },
{ '&', 5, (l, r) => l && r },
{ '^', 4, (l, r) => l ^ r },
{ '|', 3, (l, r) => l || r }
}
};
//Add a crazy operator:
var rng = new Random();
tt.Operators.Add('?', 6, r => rng.NextDouble() < 0.5);
string[] expressions = {
"!!!T",
"?T",
"F & x | T",
"F & (x | T",
"F & x | T)",
"a ! (a & a)",
"a | (a * a)",
"a ^ T & (b & !c)",
};
foreach (string expression in expressions) {
tt.PrintTruthTable(expression);
Console.WriteLine();
}
//Define a different language
tt = new TruthTable('0', '1') {
Operators = {
{ '-', 6, r => !r },
{ '^', 5, (l, r) => l && r },
{ 'v', 3, (l, r) => l || r },
{ '>', 2, (l, r) => !l || r },
{ '=', 1, (l, r) => l == r },
}
};
expressions = new[] {
"-X v 0 = X ^ 1",
"(H > M) ^ (S > H) > (S > M)"
};
foreach (string expression in expressions) {
tt.PrintTruthTable(expression);
Console.WriteLine();
}
}
} |
URL decoding | C sharp | This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function
or mechanism to convert an URL-encoded string into its original unencoded form.
;Test cases:
* The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/".
* The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Baha".
* The encoded string "%25%32%35" should revert to the unencoded form "%25" and '''not''' "%".
| using System;
namespace URLEncode
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(Decode("http%3A%2F%2Ffoo%20bar%2F"));
}
private static string Decode(string uri)
{
return Uri.UnescapeDataString(uri);
}
}
} |
URL encoding | C sharp | Provide a function or mechanism to convert a provided string into URL encoding representation.
In URL encoding, special characters, control characters and extended characters
are converted into a percent symbol followed by a two digit hexadecimal code,
So a space character encodes into %20 within the string.
For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:
* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).
* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))
* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))
* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))
* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))
* Extended characters with character codes of 128 decimal (80 hex) and above.
;Example:
The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F".
;Variations:
* Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f".
* Special characters have different encodings for different standards:
** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~".
** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+".
** encodeURI function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#".
;Options:
It is permissible to use an exception string (containing a set of symbols
that do not need to be converted).
However, this is an optional feature and is not a requirement of this task.
;Related tasks:
* [[URL decoding]]
* [[URL parser]]
| using System;
namespace URLEncode
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(Encode("http://foo bar/"));
}
private static string Encode(string uri)
{
return Uri.EscapeDataString(uri);
}
}
} |
URL parser | C sharp|C# | URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
;Task:
Parse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ...
Note: this task has nothing to do with [[URL encoding]] or [[URL decoding]].
According to the standards, the characters:
:::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ]
only need to be percent-encoded ('''%''') in case of possible confusion.
Also note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
* Here is the official standard: https://tools.ietf.org/html/rfc3986,
* and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.
;Test cases:
According to T. Berners-Lee
'''foo://example.com:8042/over/there?name=ferret#nose''' should parse into:
::* scheme = foo
::* domain = example.com
::* port = :8042
::* path = over/there
::* query = name=ferret
::* fragment = nose
'''urn:example:animal:ferret:nose''' should parse into:
::* scheme = urn
::* path = example:animal:ferret:nose
'''other URLs that must be parsed include:'''
:* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
:* ftp://ftp.is.co.za/rfc/rfc1808.txt
:* http://www.ietf.org/rfc/rfc2396.txt#header1
:* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
:* mailto:[email protected]
:* news:comp.infosystems.www.servers.unix
:* tel:+1-816-555-1212
:* telnet://192.0.2.16:80/
:* urn:oasis:names:specification:docbook:dtd:xml:4.1.2
| using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo://example.com:8042/over/there?name=ferret#nose");
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true");
ParseUrl("ftp://ftp.is.co.za/rfc/rfc1808.txt");
ParseUrl("http://www.ietf.org/rfc/rfc2396.txt#header1");
ParseUrl("ldap://[2001:db8::7]/c=GB?objectClass?one");
ParseUrl("mailto:[email protected]");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet://192.0.2.16:80/");
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
|
UTF-8 encode and decode | C sharp|C# | As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.
The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding.
Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.
Demonstrate the functionality of your encoder and decoder on the following five characters:
Character Name Unicode UTF-8 encoding (hex)
---------------------------------------------------------------------------------
A LATIN CAPITAL LETTER A U+0041 41
o LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6
Zh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96
EUR EURO SIGN U+20AC E2 82 AC
MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E
Provided below is a reference implementation in Common Lisp.
| using System;
using System.Text;
namespace Rosetta
{
class Program
{
static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint));
static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes);
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8; // makes sure it doesn't print rectangles...
foreach (int unicodePoint in new int[] { 0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E})
{
byte[] asUtf8bytes = MyEncoder(unicodePoint);
string theCharacter = MyDecoder(asUtf8bytes);
Console.WriteLine("{0,8} {1,5} {2,-15}", unicodePoint.ToString("X4"), theCharacter, BitConverter.ToString(asUtf8bytes));
}
}
}
}
/* Output:
* 0041 A 41
00F6 ö C3-B6
0416 Ж D0-96
20AC € E2-82-AC
1D11E 𝄞 F0-9D-84-9E */
|
Unbias a random generator | C sharp | Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.
;Task details:
* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.
* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.
* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).
The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.
This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
| using System;
namespace Unbias
{
internal class Program
{
private static void Main(string[] args)
{
// Demonstrate.
for (int n = 3; n <= 6; n++)
{
int biasedZero = 0, biasedOne = 0, unbiasedZero = 0, unbiasedOne = 0;
for (int i = 0; i < 100000; i++)
{
if (randN(n))
biasedOne++;
else
biasedZero++;
if (Unbiased(n))
unbiasedOne++;
else
unbiasedZero++;
}
Console.WriteLine("(N = {0}):".PadRight(17) + "# of 0\t# of 1\t% of 0\t% of 1", n);
Console.WriteLine("Biased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}",
biasedZero, biasedOne,
biasedZero/1000, biasedOne/1000);
Console.WriteLine("Unbiased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}",
unbiasedZero, unbiasedOne,
unbiasedZero/1000, unbiasedOne/1000);
}
}
private static bool Unbiased(int n)
{
bool flip1, flip2;
/* Flip twice, and check if the values are the same.
* If so, flip again. Otherwise, return the value of the first flip. */
do
{
flip1 = randN(n);
flip2 = randN(n);
} while (flip1 == flip2);
return flip1;
}
private static readonly Random random = new Random();
private static bool randN(int n)
{
// Has an 1/n chance of returning 1. Otherwise it returns 0.
return random.Next(0, n) == 0;
}
}
} |
Unicode strings | C sharp|C# | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for Unicode?
;Task:
Discuss and demonstrate its unicode awareness and capabilities.
Some suggested topics:
:* How easy is it to present Unicode strings in source code?
:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?
:* How well can the language communicate with the rest of the world?
:* Is it good at input/output with Unicode?
:* Is it convenient to manipulate Unicode strings in the language?
:* How broad/deep does the language support Unicode?
:* What encodings (e.g. UTF-8, UTF-16, etc) can be used?
:* Does it support normalization?
;Note:
This task is a bit unusual in that it encourages general discussion rather than clever coding.
;See also:
* [[Unicode variable names]]
* [[Terminal control/Display an extended character]]
| In C#, the native string representation is actually determined by the Common Language Runtime. In CLR, the string data type is a sequence of char, and the char data type represents a UTF-16 code unit. The native string representation is essentially UTF-16, except that strings can contain sequences of UTF-16 code units that aren't valid in UTF-16 if the string contains incorrectly-used high and low surrogates.
C# string literals support the \u escape sequence for 4-digit hexadecimal Unicode code points, \U for 6-digit code points, and UTF-encoded source code is also supported so that "Unicode strings" can be included in the source code as-is.
C# benefits from the extensive support for Unicode in the .NET Base Class Library, including
* Various UTF encodings
* String normalization
* Unicode character database subset
* Breaking strings into text elements
|
Universal Turing machine | C sharp | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936-1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
;Task:
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
'''Simple incrementer'''
* '''States:''' q0, qf
* '''Initial state:''' q0
* '''Terminating states:''' qf
* '''Permissible symbols:''' B, 1
* '''Blank symbol:''' B
* '''Rules:'''
** (q0, 1, 1, right, q0)
** (q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
'''Three-state busy beaver'''
* '''States:''' a, b, c, halt
* '''Initial state:''' a
* '''Terminating states:''' halt
* '''Permissible symbols:''' 0, 1
* '''Blank symbol:''' 0
* '''Rules:'''
** (a, 0, 1, right, b)
** (a, 1, 1, left, c)
** (b, 0, 1, left, a)
** (b, 1, 1, right, b)
** (c, 0, 1, left, b)
** (c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
'''Bonus:'''
'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''
* '''States:''' A, B, C, D, E, H
* '''Initial state:''' A
* '''Terminating states:''' H
* '''Permissible symbols:''' 0, 1
* '''Blank symbol:''' 0
* '''Rules:'''
** (A, 0, 1, right, B)
** (A, 1, 1, left, C)
** (B, 0, 1, right, C)
** (B, 1, 1, right, B)
** (C, 0, 1, right, D)
** (C, 1, 0, left, E)
** (D, 0, 1, left, A)
** (D, 1, 1, left, D)
** (E, 0, 1, stay, H)
** (E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class TuringMachine
{
public static async Task Main() {
var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions(
("A", '0', '1', Right, "B"),
("A", '1', '1', Left, "C"),
("B", '0', '1', Right, "C"),
("B", '1', '1', Right, "B"),
("C", '0', '1', Right, "D"),
("C", '1', '0', Left, "E"),
("D", '0', '1', Left, "A"),
("D", '1', '1', Left, "D"),
("E", '0', '1', Stay, "H"),
("E", '1', '0', Left, "A")
);
var busyBeaverTask = fiveStateBusyBeaver.TimeAsync();
var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions(
("q0", '1', '1', Right, "q0"),
("q0", 'B', '1', Stay, "qf")
)
.WithInput("111");
foreach (var _ in incrementer.Run()) PrintLine(incrementer);
PrintResults(incrementer);
var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions(
("a", '0', '1', Right, "b"),
("a", '1', '1', Left, "c"),
("b", '0', '1', Left, "a"),
("b", '1', '1', Right, "b"),
("c", '0', '1', Left, "b"),
("c", '1', '1', Stay, "halt")
);
foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver);
PrintResults(threeStateBusyBeaver);
var sorter = new TuringMachine("A", '*', "X").WithTransitions(
("A", 'a', 'a', Right, "A"),
("A", 'b', 'B', Right, "B"),
("A", '*', '*', Left, "E"),
("B", 'a', 'a', Right, "B"),
("B", 'b', 'b', Right, "B"),
("B", '*', '*', Left, "C"),
("C", 'a', 'b', Left, "D"),
("C", 'b', 'b', Left, "C"),
("C", 'B', 'b', Left, "E"),
("D", 'a', 'a', Left, "D"),
("D", 'b', 'b', Left, "D"),
("D", 'B', 'a', Right, "A"),
("E", 'a', 'a', Left, "E"),
("E", '*', '*', Right, "X")
)
.WithInput("babbababaa");
sorter.Run().Last();
Console.WriteLine("Sorted: " + sorter.TapeString);
PrintResults(sorter);
sorter.Reset().WithInput("bbbababaaabba");
sorter.Run().Last();
Console.WriteLine("Sorted: " + sorter.TapeString);
PrintResults(sorter);
Console.WriteLine(await busyBeaverTask);
PrintResults(fiveStateBusyBeaver);
void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State);
void PrintResults(TuringMachine tm) {
Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}");
Console.WriteLine(tm.Steps + " steps");
Console.WriteLine("tape length: " + tm.TapeLength);
Console.WriteLine();
}
}
public const int Left = -1, Stay = 0, Right = 1;
private readonly Tape tape;
private readonly string initialState;
private readonly HashSet<string> terminatingStates;
private Dictionary<(string state, char read), (char write, int move, string toState)> transitions;
public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) {
State = this.initialState = initialState;
tape = new Tape(blankSymbol);
this.terminatingStates = terminatingStates.ToHashSet();
}
public TuringMachine WithTransitions(
params (string state, char read, char write, int move, string toState)[] transitions)
{
this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState));
return this;
}
public TuringMachine Reset() {
State = initialState;
Steps = 0;
tape.Reset();
return this;
}
public TuringMachine WithInput(string input) {
tape.Input(input);
return this;
}
public int Steps { get; private set; }
public string State { get; private set; }
public bool Success => terminatingStates.Contains(State);
public int TapeLength => tape.Length;
public string TapeString => tape.ToString();
public IEnumerable<string> Run() {
yield return State;
while (Step()) yield return State;
}
public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) {
var chrono = Stopwatch.StartNew();
await RunAsync(cancel);
chrono.Stop();
return chrono.Elapsed;
}
public Task RunAsync(CancellationToken cancel = default)
=> Task.Run(() => {
while (Step()) cancel.ThrowIfCancellationRequested();
});
private bool Step() {
if (!transitions.TryGetValue((State, tape.Current), out var action)) return false;
tape.Current = action.write;
tape.Move(action.move);
State = action.toState;
Steps++;
return true;
}
private class Tape
{
private List<char> forwardTape = new List<char>(), backwardTape = new List<char>();
private int head = 0;
private char blank;
public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol);
public void Reset() {
backwardTape.Clear();
forwardTape.Clear();
head = 0;
forwardTape.Add(blank);
}
public void Input(string input) {
Reset();
forwardTape.Clear();
forwardTape.AddRange(input);
}
public void Move(int direction) {
head += direction;
if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank);
if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank);
}
public char Current {
get => head < 0 ? backwardTape[~head] : forwardTape[head];
set {
if (head < 0) backwardTape[~head] = value;
else forwardTape[head] = value;
}
}
public int Length => backwardTape.Count + forwardTape.Count;
public override string ToString() {
int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1;
var builder = new StringBuilder(" ", Length * 2 + 1);
if (backwardTape.Count > 0) {
builder.Append(string.Join(" ", backwardTape)).Append(" ");
if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')');
for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]);
}
builder.Append(string.Join(" ", forwardTape)).Append(" ");
if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')');
return builder.ToString();
}
}
} |
Unix/ls | C sharp|C# | Write a program that will list everything in the current folder, similar to:
:::* the Unix utility "ls" [http://man7.org/linux/man-pages/man1/ls.1.html] or
:::* the Windows terminal command "DIR"
The output must be sorted, but printing extended details and producing multi-column output is not required.
;Example output
For the list of paths:
/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b
When the program is executed in `/foo`, it should print:
bar
and when the program is executed in `/foo/bar`, it should print:
1
2
a
b
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Unix_ls
{
public class UnixLS
{
public static void Main(string[] args)
{
UnixLS ls = new UnixLS();
ls.list(args.Length.Equals(0) ? "." : args[0]);
}
private void list(string folder)
{
foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(fileSystemInfo.Name);
}
}
}
} |
Validate International Securities Identification Number | C sharp|C# | An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.
;Task:
Write a function or program that takes a string as input, and checks whether it is a valid ISIN.
It is only valid if it has the correct format, ''and'' the embedded checksum is correct.
Demonstrate that your code passes the test-cases listed below.
;Details:
The format of an ISIN is as follows:
+------------- a 2-character ISO country code (A-Z)
| +----------- a 9-character security code (A-Z, 0-9)
| | +-- a checksum digit (0-9)
AU0000XVGZA3
For this task, you may assume that any 2-character alphabetic sequence is a valid country code.
The checksum can be validated as follows:
# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.
# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)
;Test cases:
:::: {| class="wikitable"
! ISIN
! Validity
! Comment
|-
| US0378331005 || valid ||
|-
| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.
|-
| U50378331005 || not valid || The substitution typo is caught by the format constraint.
|-
| US03378331005 || not valid || The duplication typo is caught by the format constraint.
|-
| AU0000XVGZA3 || valid ||
|-
| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.
|-
| FR0000988040 || valid ||
|}
(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)
Related task:
* [[Luhn test of credit card numbers]]
;Also see:
* Interactive online ISIN validator
* Wikipedia article: International Securities Identification Number
| using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ValidateIsin
{
public static class IsinValidator
{
public static bool IsValidIsin(string isin) =>
IsinRegex.IsMatch(isin) && LuhnTest(Digitize(isin));
private static readonly Regex IsinRegex =
new Regex("^[A-Z]{2}[A-Z0-9]{9}\\d$", RegexOptions.Compiled);
private static string Digitize(string isin) =>
string.Join("", isin.Select(c => $"{DigitValue(c)}"));
private static bool LuhnTest(string number) =>
number.Reverse().Select(DigitValue).Select(Summand).Sum() % 10 == 0;
private static int Summand(int digit, int i) =>
digit + (i % 2) * (digit - digit / 5 * 9);
private static int DigitValue(char c) =>
c >= '0' && c <= '9'
? c - '0'
: c - 'A' + 10;
}
public class Program
{
public static void Main()
{
string[] isins =
{
"US0378331005",
"US0373831005",
"U50378331005",
"US03378331005",
"AU0000XVGZA3",
"AU0000VXGZA3",
"FR0000988040"
};
foreach (string isin in isins) {
string validOrNot = IsinValidator.IsValidIsin(isin) ? "valid" : "not valid";
Console.WriteLine($"{isin} is {validOrNot}");
}
}
}
} |
Van Eck sequence | C#|CSharp from C | The sequence is generated by following this pseudo-code:
A: The first term is zero.
Repeatedly apply:
If the last term is *new* to the sequence so far then:
B: The next term is zero.
Otherwise:
C: The next term is how far back this last term occured previously.
;Example:
Using A:
:0
Using B:
:0 0
Using C:
:0 0 1
Using B:
:0 0 1 0
Using C: (zero last occurred two steps back - before the one)
:0 0 1 0 2
Using B:
:0 0 1 0 2 0
Using C: (two last occurred two steps back - before the zero)
:0 0 1 0 2 0 2 2
Using C: (two last occurred one step back)
:0 0 1 0 2 0 2 2 1
Using C: (one last appeared six steps back)
:0 0 1 0 2 0 2 2 1 6
...
;Task:
# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.
# Use it to display here, on this page:
:# The first ten terms of the sequence.
:# Terms 991 - to - 1000 of the sequence.
;References:
* Don't Know (the Van Eck Sequence) - Numberphile video.
* Wikipedia Article: Van Eck's Sequence.
* OEIS sequence: A181391.
| using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } } |
Van der Corput sequence | C sharp | When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.
So in the following table:
0.
1.
10.
11.
...
the binary number "10" is 1 \times 2^1 + 0 \times 2^0.
You can also have binary digits to the right of the "point", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2.
The weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.
If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.
.0
.1
.01
.11
...
The third member of the sequence, binary 0.01, is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4.
Monte Carlo simulations.
This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
'''Hint'''
A ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]
the above showing that 11 in decimal is 1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 1\times 2^0.
Reflected this would become .1101 or 1\times 2^{-1} + 1\times 2^{-2} + 0\times 2^{-3} + 1\times 2^{-4}
;Task description:
* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.
* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).
* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
;See also:
* The Basic Low Discrepancy Sequences
* [[Non-decimal radices/Convert]]
* Van der Corput sequence
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VanDerCorput
{
/// <summary>
/// Computes the Van der Corput sequence for any number base.
/// The numbers in the sequence vary from zero to one, including zero but excluding one.
/// The sequence possesses low discrepancy.
/// Here are the first ten terms for bases 2 to 5:
///
/// base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16
/// base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27
/// base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8
/// base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25
/// </summary>
/// <see cref="http://rosettacode.org/wiki/Van_der_Corput_sequence"/>
public class VanDerCorputSequence: IEnumerable<Tuple<long,long>>
{
/// <summary>
/// Number base for the sequence, which must bwe two or more.
/// </summary>
public int Base { get; private set; }
/// <summary>
/// Maximum number of terms to be returned by iterator.
/// </summary>
public long Count { get; private set; }
/// <summary>
/// Construct a sequence for the given base.
/// </summary>
/// <param name="iBase">Number base for the sequence.</param>
/// <param name="count">Maximum number of items to be returned by the iterator.</param>
public VanDerCorputSequence(int iBase, long count = long.MaxValue) {
if (iBase < 2)
throw new ArgumentOutOfRangeException("iBase", "must be two or greater, not the given value of " + iBase);
Base = iBase;
Count = count;
}
/// <summary>
/// Compute nth term in the Van der Corput sequence for the base specified in the constructor.
/// </summary>
/// <param name="n">The position in the sequence, which may be zero or any positive number.</param>
/// This number is always an integral power of the base.</param>
/// <returns>The Van der Corput sequence value expressed as a Tuple containing a numerator and a denominator.</returns>
public Tuple<long,long> Compute(long n)
{
long p = 0, q = 1;
long numerator, denominator;
while (n != 0)
{
p = p * Base + (n % Base);
q *= Base;
n /= Base;
}
numerator = p;
denominator = q;
while (p != 0)
{
n = p;
p = q % p;
q = n;
}
numerator /= q;
denominator /= q;
return new Tuple<long,long>(numerator, denominator);
}
/// <summary>
/// Compute nth term in the Van der Corput sequence for the given base.
/// </summary>
/// <param name="iBase">Base to use for the sequence.</param>
/// <param name="n">The position in the sequence, which may be zero or any positive number.</param>
/// <returns>The Van der Corput sequence value expressed as a Tuple containing a numerator and a denominator.</returns>
public static Tuple<long, long> Compute(int iBase, long n)
{
var seq = new VanDerCorputSequence(iBase);
return seq.Compute(n);
}
/// <summary>
/// Iterate over the Van Der Corput sequence.
/// The first value in the sequence is always zero, regardless of the base.
/// </summary>
/// <returns>A tuple whose items are the Van der Corput value given as a numerator and denominator.</returns>
public IEnumerator<Tuple<long, long>> GetEnumerator()
{
long iSequenceIndex = 0L;
while (iSequenceIndex < Count)
{
yield return Compute(iSequenceIndex);
iSequenceIndex++;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class Program
{
static void Main(string[] args)
{
TestBasesTwoThroughFive();
Console.WriteLine("Type return to continue...");
Console.ReadLine();
}
static void TestBasesTwoThroughFive()
{
foreach (var seq in Enumerable.Range(2, 5).Select(x => new VanDerCorputSequence(x, 10))) // Just the first 10 elements of the each sequence
{
Console.Write("base " + seq.Base + ":");
foreach(var vc in seq)
Console.Write(" " + vc.Item1 + "/" + vc.Item2);
Console.WriteLine();
}
}
}
}
|
Vector products | C sharp|C# | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.
Given the vectors:
A = (a1, a2, a3)
B = (b1, b2, b3)
C = (c1, c2, c3)
then the following common vector products are defined:
* '''The dot product''' (a scalar quantity)
:::: A * B = a1b1 + a2b2 + a3b3
* '''The cross product''' (a vector quantity)
:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1)
* '''The scalar triple product''' (a scalar quantity)
:::: A * (B x C)
* '''The vector triple product''' (a vector quantity)
:::: A x (B x C)
;Task:
Given the three vectors:
a = ( 3, 4, 5)
b = ( 4, 3, 5)
c = (-5, -12, -13)
# Create a named function/subroutine/method to compute the dot product of two vectors.
# Create a function to compute the cross product of two vectors.
# Optionally create a function to compute the scalar triple product of three vectors.
# Optionally create a function to compute the vector triple product of three vectors.
# Compute and display: a * b
# Compute and display: a x b
# Compute and display: a * (b x c), the scalar triple product.
# Compute and display: a x (b x c), the vector triple product.
;References:
* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.
* Wikipedia dot product.
* Wikipedia cross product.
* Wikipedia triple product.
;Related tasks:
* [[Dot product]]
* [[Quaternion type]]
| using System;
using System.Windows.Media.Media3D;
class VectorProducts
{
static double ScalarTripleProduct(Vector3D a, Vector3D b, Vector3D c)
{
return Vector3D.DotProduct(a, Vector3D.CrossProduct(b, c));
}
static Vector3D VectorTripleProduct(Vector3D a, Vector3D b, Vector3D c)
{
return Vector3D.CrossProduct(a, Vector3D.CrossProduct(b, c));
}
static void Main()
{
var a = new Vector3D(3, 4, 5);
var b = new Vector3D(4, 3, 5);
var c = new Vector3D(-5, -12, -13);
Console.WriteLine(Vector3D.DotProduct(a, b));
Console.WriteLine(Vector3D.CrossProduct(a, b));
Console.WriteLine(ScalarTripleProduct(a, b, c));
Console.WriteLine(VectorTripleProduct(a, b, c));
}
} |
Visualize a tree | C sharp | A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming.
It's often helpful to visually examine such a structure.
There are many ways to represent trees to a reader, such as:
:::* indented text (a la unix tree command)
:::* nested HTML tables
:::* hierarchical GUI widgets
:::* 2D or 3D images
:::* etc.
;Task:
Write a program to produce a visual representation of some tree.
The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.
Make do with the vague term "friendly" the best you can.
| using System;
public static class VisualizeTree
{
public static void Main() {
"A".t(
"B0".t(
"C1",
"C2".t(
"D".t("E1", "E2", "E3")),
"C3".t(
"F1",
"F2",
"F3".t("G"),
"F4".t("H1", "H2"))),
"B1".t(
"K1",
"K2".t(
"L1".t("M"),
"L2",
"L3"),
"K3")
).Print();
}
private static Tree t(this string value, params Tree[] children) => new Tree(value, children);
private static void Print(this Tree tree) => tree.Print(true, "");
private static void Print(this Tree tree, bool last, string prefix) {
(string current, string next) = last
? (prefix + "└─" + tree.Value, prefix + " ")
: (prefix + "├─" + tree.Value, prefix + "| ");
Console.WriteLine(current[2..]);
for (int c = 0; c < tree.Children.Length; c++) {
tree.Children[c].Print(c == tree.Children.Length - 1, next);
}
}
class Tree
{
public Tree(string value, params Tree[] children) => (Value, Children) = (value, children);
public static implicit operator Tree(string value) => new Tree(value);
public string Value { get; }
public Tree[] Children { get; }
}
} |
Water collected between towers | C sharp|C# | In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ## 9 ##
8 ## 8 ##
7 ## ## 7 ####
6 ## ## ## 6 ######
5 ## ## ## #### 5 ##########
4 ## ## ######## 4 ############
3 ###### ######## 3 ##############
2 ################ ## 2 ##################
1 #################### 1 ####################
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele
* Water collected between towers on Stack Overflow, from which the example above is taken)
* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| class Program
{
// Variable names key:
// i Iterator (of the tower block array).
// tba Tower block array.
// tea Tower elevation array.
// rht Right hand tower column number (position).
// wu Water units (count).
// bof Blocks on floor (count).
// col Column number in elevation array (position).
static void Main(string[] args)
{
int i = 1; int[][] tba = {new int[] { 1, 5, 3, 7, 2 },
new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },
new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};
foreach (int[] tea in tba)
{
int rht, wu = 0, bof; do
{
for (rht = tea.Length - 1; rht >= 0; rht--)
if (tea[rht] > 0) break;
if (rht < 0) break;
bof = 0; for (int col = 0; col <= rht; col++)
{
if (tea[col] > 0) { tea[col] -= 1; bof += 1; }
else if (bof > 0) wu++;
}
if (bof < 2) break;
} while (true);
System.Console.WriteLine(string.Format("Block {0} {1} water units.",
i++, wu == 0 ? "does not hold any" : "holds " + wu.ToString()));
}
}
} |
Weird numbers | C sharp|C# from D | In number theory, a perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').
For example:
* '''12''' is ''not'' a weird number.
** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),
** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.
* '''70''' ''is'' a weird number.
** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),
** and there is no subset of proper divisors that sum to '''70'''.
;Task:
Find and display, here on this page, the first '''25''' weird numbers.
;Related tasks:
:* Abundant, deficient and perfect number classifications
:* Proper divisors
;See also:
:* OEIS: A006037 weird numbers
:* Wikipedia: weird number
:* MathWorld: weird number
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WeirdNumbers {
class Program {
static List<int> Divisors(int n) {
List<int> divs = new List<int> { 1 };
List<int> divs2 = new List<int>();
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int j = n / i;
divs.Add(i);
if (i != j) {
divs2.Add(j);
}
}
}
divs.Reverse();
divs2.AddRange(divs);
return divs2;
}
static bool Abundant(int n, List<int> divs) {
return divs.Sum() > n;
}
static bool Semiperfect(int n, List<int> divs) {
if (divs.Count > 0) {
var h = divs[0];
var t = divs.Skip(1).ToList();
if (n < h) {
return Semiperfect(n, t);
} else {
return n == h
|| Semiperfect(n - h, t)
|| Semiperfect(n, t);
}
} else {
return false;
}
}
static List<bool> Sieve(int limit) {
// false denotes abundant and not semi-perfect.
// Only interested in even numbers >= 2
bool[] w = new bool[limit];
for (int i = 2; i < limit; i += 2) {
if (w[i]) continue;
var divs = Divisors(i);
if (!Abundant(i, divs)) {
w[i] = true;
} else if (Semiperfect(i, divs)) {
for (int j = i; j < limit; j += i) {
w[j] = true;
}
}
}
return w.ToList();
}
static void Main() {
var w = Sieve(17_000);
int count = 0;
int max = 25;
Console.WriteLine("The first 25 weird numbers:");
for (int n = 2; count < max; n += 2) {
if (!w[n]) {
Console.Write("{0} ", n);
count++;
}
}
Console.WriteLine();
}
}
} |
Word frequency | C sharp|C# from D | Given a text file and an integer '''n''', print/display the '''n''' most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
* A word is a sequence of one or more contiguous letters.
* You are free to define what a ''letter'' is.
* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
* You may treat a compound word like '''well-dressed''' as either one word or two.
* The word '''it's''' could also be one or two words as you see fit.
* You may also choose not to support non US-ASCII characters.
* Assume words will not span multiple lines.
* Don't worry about normalization of word spelling differences.
* Treat '''color''' and '''colour''' as two distinct words.
* Uppercase letters are considered equivalent to their lowercase counterparts.
* Words of equal frequency can be listed in any order.
* Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.
;History:
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
;References:
*McIlroy's program
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace WordCount {
class Program {
static void Main(string[] args) {
var text = File.ReadAllText("135-0.txt").ToLower();
var match = Regex.Match(text, "\\w+");
Dictionary<string, int> freq = new Dictionary<string, int>();
while (match.Success) {
string word = match.Value;
if (freq.ContainsKey(word)) {
freq[word]++;
} else {
freq.Add(word, 1);
}
match = match.NextMatch();
}
Console.WriteLine("Rank Word Frequency");
Console.WriteLine("==== ==== =========");
int rank = 1;
foreach (var elem in freq.OrderByDescending(a => a.Value).Take(10)) {
Console.WriteLine("{0,2} {1,-4} {2,5}", rank++, elem.Key, elem.Value);
}
}
}
} |