public static void Main(string[] args)
{
string text = Console.ReadLine();
int number = 0;
int powerOfFive = 1;
const string coders = " 0Oo1l";
const int five = 5;
for (int i = text.Length - 1; i >= 0; --i)
{
int decodedDigit = coders.IndexOf(text[i]);
number += powerOfFive * decodedDigit;
powerOfFive *= five;
}
Console.Write(number);
}
For input data:
11 ll 00 O OO oO o 10
The console will display:
24 30 6 2 12 17 3 21
In my code I can only take one pair of characters (except the case when there are single character) separated by a space at one input at a time.
How can I take the entire string in one input?
Looks like you are supposed to split the input string on space and then process each substring individually.
string text = Console.ReadLine();
const string coders = " 0Oo1l";
const int five = 5;
foreach (var code in text.Split(' '))
{
int number = 0;
int powerOfFive = 1;
for (int i = code.Length - 1; i >= 0; --i)
{
int decodedDigit = coders.IndexOf(code[i]);
number += powerOfFive * decodedDigit;
powerOfFive *= five;
}
Console.Write(number + " ");
}
Sample input/output:
11 ll 00 O OO oO o 10
24 30 6 2 12 17 3 21
Related
Is there an algorithm for calculating a factorial without using System.Numerics library? We receive an int number and we need to return factorial of this number as string(if n = 30, we should return "265252859812191058636308480000000", if n = 70, we should return "11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000" ect. Numbers are very big)
I tried to find out, did anyone already write an article about that, but I didn't find anything.
It suffices to implement multiplication of a large number as a string by a small integer.
Illustration: 12! = 11! x 12 is obtained by multiplying every digit by 12 and summing (with shifts):
39916800
36
108
108
12
72
96
0
0
---------
479001600
A lazy solution. It is possible to evaluate the factorial with just BigNum addition, replacing the multiplications by successive additions. (For n!, we will perform 1+2+3+...n-1 additions. This is acceptable for moderate n.)
The computation uses two pre-allocated string (arrays of char), which are initially filled with null bytes (Writeline skips them). When adding from right to left, we stop when we meet a null.
int n = 20;
// Factorial and temporary string; 100! fits in 158 digits
const int N = 158;
char[] f = new char[N], t = new char[N];
f[N - 1] = '1'; // 1!
// Product up to n by successive additions
for (int i = 2; i <= n; i++)
{
// t= f
f.CopyTo(t, 0);
for (int j = 0; j < i - 1; j++)
{
// f+= t, repeated i-1 times
int c = 0; // Carry
for (int k = N - 1; k >= 0; k--)
{
if (t[k] == 0 && c == 0) break; // Significant part exhausted
int d = Math.Max(0, t[k] - '0') + Math.Max(0, f[k] - '0') + c;
c= d / 10; d = d % 10; f[k] = (char)(d + '0'); // Next carry/digit
}
}
Console.WriteLine(f);
}
Output:
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
static string FindFactorial(int n)
{
int[] result = new int[500000];
result[0] = 1;
int resultSize = 1;
for (int x = 2; x <= n; x++)
resultSize = Multiply(x, result, resultSize);
string factorial = "";
for (int i = resultSize - 1; i >= 0; i--)
factorial += result[i].ToString();
return factorial;
}
static int Multiply(int x, int[] result, int resultSize)
{
int carry = 0;
for (int i = 0; i < resultSize; i++)
{
int product = result[i] * x + carry;
result[i] = product % 10;
carry = product / 10;
}
while (carry != 0)
{
result[resultSize] = carry % 10;
carry /= 10;
resultSize++;
}
return resultSize;
}
This will work
How to add method here to find out the number must be between 0 and 20?
And I want to Use TryParse() method to check that an integer has been entered is between 0 to 20 and that should be but here if i enter 21 that is also working which is wrong please help! here is my code
static void Main(string[] args)
{
int number;
int a = 0;
char ec;
Write("Enter number of participants between 0 to 20 >> ");
while (a == 0)
{
if (int.TryParse(ReadLine(), out number))
{
a = 1;
WriteLine("the expected revenue is " + ComputeRevenue(number).ToString("C"));
Sport[] player = new Sport[number];
for (int x = 0; x < number; x++)
{
player[x] = new Sport();
Write("Enter Player Name #{0} >> ", x + 1);
player[x].EventCode = ReadLine()[0];
}
You are not checking the value of the number you read.
You can check it with a simple if condition.
int number;
int a = 0;
char ec;
Write("Enter number of participants between 0 to 20 >> ");
while (a == 0)
{
if (int.TryParse(ReadLine(), out number))
{
if(number>=0 && number<20){
a = 1;
WriteLine("the expected revenue is " + ComputeRevenue(number).ToString("C"));
Sport[] player = new Sport[number];
for (int x = 0; x < number; x++)
{
player[x] = new Sport();
Write("Enter Player Name #{0} >> ", x + 1);
player[x].EventCode = ReadLine()[0];
}
}
I have another question about lottery. I have to make this problem: "You want to participate in the game of chance 6 out of 49 with only one variant and you want to know what chances you will win:category I (6 numbers),category II (5 numbers),category III (4 numbers). Write a application that receive as input data the total number of balls, the number of balls drawn and then prints the chances of winning with an accuracy of 10 decimals if played with a single variant". My question is: What is the formula to calculate this?I try to find that formula but i didn't find it. An example will be 40, 5 and II (5 numbers) and the result is 0.0002659542 or 45 , 15 and category III is 0.0000001324.I need to mention i am a beginner. My code is working but just for 6 from 49.
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
string extract = Console.ReadLine();
int category1 = category(extract);
switch (category1)
{
case 6:
calculateTheOddsToWin(n, k, extract);
break;
case 5:
calculateTheOddsToWin(n, k, extract);
break;
case 4:
calculateTheOddsToWin(n, k, extract);
break;
}
}
static void calculateTheOddsToWin(int n , int k , string extract)
{
double comb = combination(n, k);
decimal solution =(decimal)( 1 / comb);
decimal round = Math.Round(solution,10);
Console.WriteLine(round);
}
static double combination(int n, int k)
{
double factN = factorialN(n);
double factK = factorialK(k);
double factNK = substractFactorialNK(n, k);
double combination = factN / (factNK * factK);
return combination;
}
static double factorialN(int n)
{
double factorialN = 1;
for(int i = 1; i <= n; i++)
{
factorialN *= i;
}
return factorialN;
}
static double factorialK( int k)
{
double factorialK = 1;
for (int i = 1; i <= k; i++)
{
factorialK *= i;
}
return factorialK;
}
static double substractFactorialNK(int n, int k)
{
double factorialNK = 1;
int substract = n - k;
for (int i = 1; i <= substract; i++)
{
factorialNK *= i;
}
return factorialNK;
}
static int category(string extract)
{
if(extract == "I")
{
return 6;
}else if(extract == "II")
{
return 5;
}else if(extract == "III")
{
return 4;
}
else
{
return -1;
}
}
You need to calculate three numbers:
T: The total number of combinations
W: The number of ways to draw the desired amount of winning numbers
L: The number of ways to draw the desired amount of losing numbers
Then, the answer is W * L / T
Example: 40 numbers, 5 draws, 4 correct:
W = choose(5,4) = 5 (4 winners from 5 possibilities)
L = choose(35,1) = 35 (1 loser from 35 possibilities)
T = choose(40, 5) = 658008 (5 numbers from 40 possibilities)
5 * 35 / 658008 = 0.00265954
Generically:
n = count of numbers
d = count of available winning numbers = draw size
k = count of winning numbers drawn (d, d-1, and d-2 for I, II, III).
W = choose(d, k) (k winners from d possibilities)
L = choose(n-d, d-k) (d-k losers from n-d possibilities)
T = choose(n, d) (d numbers from n possibilities)
This question already has answers here:
How to convert a column number (e.g. 127) into an Excel column (e.g. AA)
(60 answers)
Closed 5 years ago.
I have a requirement for a custom number system in C# which goes as following:
A - 1
B - 2
...
Z - 26
AA - 27
AB - 28
I've made a function that converts from arbitrary strings to numbers like this:
private const int Min = 'A';
private const int Max = 'Z';
private const int Base = Max - Min + 1;
private static int GetCharValue(char c)
{
if (c < Min || c > Max)
throw new ArgumentOutOfRangeException(nameof(c), c, $"Character needs to be between '{Min}' and '{Max}', was '{c}'.");
return c - Min + 1;
}
public static int GetStringValue(string s)
{
char[] chars = s.ToCharArray();
int[] values = new int[chars.Length];
for (var i = 0; i < chars.Length; i++)
{
values[i] = GetCharValue(chars[i]);
}
int position = 1;
int value = 0;
for (var i = values.Length - 1; i >= 0; i--)
{
value += position * values[i];
position *= Base;
}
return value;
}
I've tested it to be working for up to AAA (not rigorously, just skimming over the output of printing them all). However, I can't for the life of me figure out how to write the reverse function. In other words, I need 1 to return A, 26 to return Z and 27 to return AA. The "problem" is that this number system has no 0, so it doesn't easily convert to any base. For instance, if A was 0, then AA would also be 0, but it's not. So how do I solve this?
you can simply generate it like this....
public static IEnumerable<string> generate()
{
long n = -1;
while (true) yield return toBase26(++n);
}
public static string toBase26(long i)
{
if (i == 0) return ""; i--;
return toBase26(i / 26) + (char)('A' + i % 26);
}
public static void BuildQuery()
{
IEnumerable<string> lstExcelCols = generate();
try
{
string s = lstExcelCols.ElementAtOrDefault(1) ;
}
catch (Exception exc)
{
}
}
I'm trying to create an method to evenly distribute an array into X numbers of new arrays, where there is only allowed 15 items pr array, and you are only allowed to create a new array, if the previous have 10 items, except if the array has less than 10 items.
EDIT
To make my question more understandable for future readers.
This is just like a fabric.
You need to build X number of products.
One product takes T amount to build for an employee.
How many employees do you need and how do you share the work load between them?
END EDIT
Max allowed number in array = 15;
Min allowed number in array = 10;
Number = Numbers of Items in the Collection.
Number 5 => [5]
Number 13 => [13]
Number 16 => [10] [6]
Number 29 => [15] [14]
Number 30 => [15] [15]
Number 31 => [11] [10] [10]
Number 32 => [12] [10] [10]
Number 33 => [11] [11] [11]
I'm trying to solve this in C#.
This is my code so far, but it fails at numbers like 16 = [16], 29 = [19][10], 38 = [18][10][10]
const int maxAllowedOrderLines = 15;
const int minAllowedOrderLines = 10;
var optimalOrderDisp = new List<int>();
Console.WriteLine("Number of OrderLines");
int linjer = Convert.ToInt32(Console.ReadLine());
if (linjer <= maxAllowedOrderLines)
optimalOrderDisp.Add(linjer);
else
{
for (var i = maxAllowedOrderLines; i > 0; i--)
{
var maxOrderLines = linjer%i;
if (maxOrderLines == 0 || i <= minAllowedOrderLines || linjer < maxAllowedOrderLines)
{
Console.WriteLine("Optimal number of order lines {0}--{1}", i, (double) linjer/(double) i);
var optimalNumberOfOrders = linjer/i;
for (var orderNumber = 0; orderNumber < optimalNumberOfOrders; orderNumber++)
{
optimalOrderDisp.Add(i);
}
if (maxOrderLines != 0)
optimalOrderDisp[0] += maxOrderLines;
break;
}
}
}
foreach (var i1 in optimalOrderDisp)
{
Console.Write("[{0}]", i1);
}
Console.WriteLine();
Erm ...
const double bucketSize = 15.0;
var totalItems = (double)linjer;
var optimumBuckets = Math.Ceiling(totalItems / bucketSize);
var itemsPerBucket = (int)Math.Ceiling(totalItems / optimumBuckets);
var buckets = new int[(int)optimumBuckets];
var itemsLeft = (int)totalItems
for (var i = 0; i < buckets.length; i++)
{
if (itemsLeft < itemsPerBucket)
{
buckets[i] = itemsLeft;
}
else
{
buckets[i] = itemsPerBucket;
}
itemsLeft -= itemsPerBucket;
}
seems to do what you want.
Fun question. I've given it a go:
const int maxAllowedOrderLines = 15;
const int minAllowedOrderLines = 10;
static List<int> optimalOrderDisp = new List<int>();
static void Main(string[] args)
{
int Lines = Convert.ToInt32(Console.ReadLine());
int MinNumberOfBuckets = (int) Math.Ceiling((double) Lines / minAllowedOrderLines);
int RemainingLines = Lines;
int BucketLines = Lines / MinNumberOfBuckets;
// Distribute evenly
for (int i = 0; i < MinNumberOfBuckets; i++)
{
optimalOrderDisp.Add(i != MinNumberOfBuckets - 1 ? BucketLines : RemainingLines);
RemainingLines -= BucketLines;
}
// Try to remove first bucket
while (RemoveBucket())
{
}
// Re-balance
Lines = optimalOrderDisp.Sum();
RemainingLines = Lines;
BucketLines = (int) Math.Round((double) Lines / (optimalOrderDisp.Count));
for (int i = 0; i < optimalOrderDisp.Count; i++)
{
optimalOrderDisp[i] = (i != optimalOrderDisp.Count - 1 ? BucketLines : RemainingLines);
RemainingLines -= BucketLines;
}
// Re-balance to comply to min size
for (int i = 0; i < optimalOrderDisp.Count - 1; i++)
if (optimalOrderDisp[i] < minAllowedOrderLines)
{
int delta = minAllowedOrderLines - optimalOrderDisp[i];
optimalOrderDisp[i] += delta;
optimalOrderDisp[optimalOrderDisp.Count - 1] -= delta;
}
Console.WriteLine(String.Join("\n", optimalOrderDisp.ToArray()));
}
static bool RemoveBucket()
{
if (optimalOrderDisp.Sum() > maxAllowedOrderLines * (optimalOrderDisp.Count - 1))
return false;
int Lines = optimalOrderDisp[0];
int RemainingLines = Lines;
int BucketLines = Lines / (optimalOrderDisp.Count - 1);
// Remove bucket and re-distribute content evenly
// Distribute evenly
for (int i = 1; i < optimalOrderDisp.Count; i++)
{
optimalOrderDisp[i] += (i != optimalOrderDisp.Count - 1 ? BucketLines : RemainingLines);
RemainingLines -= BucketLines;
}
optimalOrderDisp.RemoveAt(0);
return true;
}