I have this shape and I want to output it to ConoleApplication Windows.
I have this code but it doesn't work as I need :
int i,j;
for(i=0;i<5;i++)
{
for(j=5-i;j>0;j--)
Console.WriteLine(" ");
for(j=0;j<=2*i;j++)
Console.WriteLine("*");
Console.WriteLine("\n");
}
Thanks in advance.
EDIT : I am very sorry
As everyone knows, everything Just Works™ when using LINQ... so, have you tried doing it with LINQ?
int n = 6;
var result = string.Join("\r\n", from i in Enumerable.Range(1, n)
where i != 2
let stars = Enumerable.Repeat('*', i)
let indent = new string(' ', n - i)
select indent + string.Join(" ", stars));
Console.WriteLine(result);
*
* * *
* * * *
* * * * *
* * * * * *
Something like:
for (j = 0; j <= 2 * i; j += 2)
{
printf("*");
printf(" ");
// or Console.Write("* ") if we are talking C#
}
which writes the spaces between asterisks (plus a spare one; you could remove that if it is important).
You just used WriteLine instead of Write
Here is the correct code:
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 5 - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
Console.Write("*");
Console.WriteLine();
}
Related
So the problem that I'm trying to optimize is to find and print all four-digit numbers of the type ABCD for which: A + B = C + D.
For example:
1001
1010
1102
etc.
I have used four for loops to solve this (one for every digit of the number).
for (int a = 1; a <= 9; a++)
{
for (int b = 0; b <= 9; b++)
{
for (int c = 0; c <= 9; c++)
{
for (int d = 0; d <= 9; d++)
{
if ((a + b) == (c + d))
{
Console.WriteLine(" " + a + " " + b + " " + c + " " + d);
}
}
}
}
}
My question is: how can I solve this using only 3 for loops?
Here's an option with two loops (though still 10,000 iterations), separating the pairs of digits:
int sumDigits(int input)
{
int result = 0;
while (input != 0)
{
result += input % 10;
input /= 10;
}
return result;
}
//optimized for max of two digits
int sumDigitsAlt(int input)
{
return (input % 10) + ( (input / 10) % 10);
}
// a and b
for (int i = 0; i <= 99; i++)
{
int sum = sumDigits(i);
// c and d
for (int j = 0; j <= 99; j++)
{
if (sum == sumDigits(j))
{
Console.WriteLine( (100 * i) + j);
}
}
}
I suppose the while() loop inside of sumDigits() might count as a third loop, but since we know we have at most two digits we could remove it if needed.
And, of course, we can use a similar tactic to do this with one loop which counts from 0 to 9999, and even that we can hide:
var numbers = Enumerable.Range(0, 10000).
Where(n => {
// there is no a/b
if (n < 100 && n == 0) return true;
if (n < 100) return false;
int sumCD = n % 10;
n /= 10;
sumCD += n % 10;
n /= 10;
int sumAB = n % 10;
n /= 10;
sumAB += n % 10;
return (sumAB == sumCD);
});
One approach is to write a method that takes in an integer and returns true if the integer is four digits and the sum of the first two equal the sum of the second two:
public static bool FirstTwoEqualLastTwo(int input)
{
if (input < 1000 || input > 9999) return false;
var first = input / 1000;
var second = (input - first * 1000) / 100;
var third = (input - first * 1000 - second * 100) / 10;
var fourth = input - first * 1000 - second * 100 - third * 10;
return (first + second) == (third + fourth);
}
Then you can write a single loop from 1000-9999 and output the numbers for which this is true with a space between each digit (not sure why that's the output, but it appears that's what you were doing in your sample code):
static void Main(string[] args)
{
for (int i = 1000; i < 10000; i++)
{
if (FirstTwoEqualLastTwo(i))
{
Console.WriteLine(" " + string.Join(" ", i.ToString().ToArray()));
}
}
Console.Write("Done. Press any key to exit...");
Console.ReadKey();
}
We can compute the value of d from the values of a,b,c.
for (int a = 1; a <= 9; a++)
{
for (int b = 0; b <= 9; b++)
{
for (int c = 0; c <= 9; c++)
{
if (a + b >= c && a + b <= 9 + c)
{
int d = a + b - c;
Console.WriteLine(" " + a + " " + b + " " + c + " " + d);
}
}
}
}
We can further optimize by changing the condition of the third loop to for (int c = max(0, a + b - 9); c <= a + b; c++) and getting rid of the if statement.
I'm trying to compute
,
where Ci is the i-th Catalan number.
To solve the problem, I loop from 0 to n and sum the product of two Catalan numbers:
BigInteger catalanSum = 0;
for (int i = 0; i <= n; i++)
catalanSum += catalan(i) * catalan(n - i);
The catalan function is returning the binomial coefficent divided by n + 1:
BigInteger catalan(int n)
{
return NchooseK(2 * n, n) / (n + 1);
}
And to compute the binomial coefficient I use this function:
BigInteger NchooseK(int n, int k)
{
BigInteger res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
It works fine up to n = 1000, but as soon it get highers it really slows down alot. Is there any way I can optimize this calculation?
EDIT:
I sped up the computation by saving the catalans first using the following code-snippet, thanks to xanatos answer:
BigInteger[] catalans = new BigInteger[n+1];
BigInteger catalanSum = 0;
for (int i = 0; i <= n; i++)
catalans[i] = catalan(i);
for (int i = 0; i <= n; i++)
catalanSum += catalans[i] * catalans[n - i];
EDIT 2:
When catalan[i] == catalan[n - i], wouldn't the remaining half of computations have the same product as the first half?
The computation you are describing seems like the first recurrence relation for computing the nth Catalan Number (and you're needlessly applying a binomial computation as well when you could just use the Catalan numbers themselves in the recurrence). That's O(n^2) complexity plus the complexity for all the binomial computations. Why not use the second recurrence relation?
catalan(0) = 1
catalan(n + 1) = 2*(2*n + 1) / (n + 2) * n
There are two things you can do:
First, check OEIS for your sequence. You will find that the sequence has an entry. And this entry has a useful formula:
2*(2*n-1)*a(n-1) = (n+1)*a(n)
So, calculating the Catalan numbers can be done much more efficiently:
BigInteger lastCatalan = 1;
catalans[0] = lastCatalan;
for(int i = 1; i <= n; ++i)
{
lastCatalan = (2 * (2 * i - 1) * lastCatalan) / (i + 1);
catalans[i] = lastCatalan;
}
The second thing is that your summation is symmetric. I.e., you just need to sum half of the entries:
BigInteger catalanSum = 0;
for (int i = 0; i < (n + 1) / 2; i++)
catalanSum += catalans[i] * catalans[n - i];
catalanSum = 2 * catalanSum;
if (n % 2 == 0)
catalanSum += catalans[n / 2] * catalans[n / 2];
After גלעד ברקן pointed out that the sum you are looking for is the n+1-th Catalan number, this can be simplified drastically:
BigInteger catalanSum= 1;
for(int i = 1; i <= n + 1; ++i)
catalanSum = (2 * (2 * i - 1) * catalanSum) / (i + 1);
You could also cache the factorials.
There are a lot of examples to create a triangle in C#
but now i need a hollow one here fore there are a lot of examples in C or C++ but i need one in C# console , can some body give me a few examples
*
* * *
* * * *
* * * * *
* * * * * *
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 5 - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
Console.Write("*");
Console.WriteLine();
}
*
* *
* *
* *
* * * * * *
This Works...But if the value is greater than that s printable on a single line it breaks into next line. The maximum possible value without line break is 40. Till 40 it works well and good in my system. For larger values you have to increase the width of command prompt. It can be done using commands or by changing the width in properties of command prompt.
int i, j,n=5;
for (i = 0; i < n; i++)
{
for (j = n - i; j > 0; j--)
Console.Write(" ");
for (j = 0; j <= 2 * i; j++)
{
if (j < 2 * i && j > 0&&i!=(n-1))
Console.Write(" ");
else
Console.Write("*");
}
Console.WriteLine();
}
Try this:
void Main()
{
Int32 totalLines = 9;
for (Int32 i = 0; i <= totalLines; ++i)
Console.WriteLine(Line(i, totalLines));
}
String Line(Int32 i, Int32 totalLines)
{
Int32 charCount = 2 * totalLines + 1;
Int32 center = charCount / 2;
// Last line is filled completely
if (i == totalLines) return new String(Enumerable.Repeat('*', charCount).ToArray());
Char[] chars = Enumerable.Repeat(' ', charCount).ToArray();
chars[center-i] = '*';
chars[center+i] = '*';
return new String(chars);
}
This will only work with monospace fonts.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am practicing for my programming exam and that's one of the exams. This program crashes after the first for loop and I can't figure out why. Please help!
int n = int.Parse(Console.ReadLine());
Console.WriteLine("{0}{1}{0}", new string('-', n / 2), new string('*', n + 2));
for (int i = 0; i < n - 1; i++)
{
Console.WriteLine("{0}*{1}*{0}", new string('-', n / 2), new string('-', n));
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(
"{0}{1}{2}{1){0}",
new string('-', ((n - 1) / 2) - i),
new string('*', 1 + 2 * i),
new string('-', n - 2 * i));
if (i < n / 2)
{
i++;
}
else
{
i--;
}
}
"{0}{1}{2}{1){0}",
Your string format is error,you need to change your {1) to {1},but it seems the code never end while input is 5! and other input also take another exception,can you explain what you want to do ?
"{0}{1}{2}{1}{0}",
I changed your code to a method now
static void PrintDemo(int num)
{
if (num < 0 || num % 2 == 0)
{
return;//do nothing
}
Console.WriteLine("{0}{1}{0}", new string('-', num / 2), new string('*', num + 2));
for (int i = 0; i < num - 1; i++)
{
Console.WriteLine("{0}*{1}*{0}", new string('-', num / 2), new string('-', num));
}
for (int i = 0; i < num; i++)
{
var t1 = Math.Abs(num / 2 - i);
var t2 = t1 * 2 + 1;
var t3 = (num * 2 + 1 - t1 * 2 - t2) / 2;
Console.WriteLine(
"{0}{1}{2}{1}{0}",
new string('-', t1),
new string('*', t3),
new string('-', t2));
}
}
The first error has been answered by Sky Fang
After that you will get ArgumentOutOfRangeException. For this you will have to change your second forloop condition to this
for (int i = 0; i < (n-1)/2; i++)
{
....
}
This is because when you are printing this is one of your arguments
new string('-', ((n - 1) / 2) - i)
Your second argument is becoming negative as i increases to (n-1)/2
Edit
Here is the final code. Adding Console.Readline will keep the console up and will enable you to see the output
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Console.WriteLine("{0}{1}{0}", new string('-', n / 2), new string('*', n + 2));
for (int i = 0; i < n - 1; i++)
{
Console.WriteLine("{0}*{1}*{0}", new string('-', n / 2), new string('-', n));
}
for (int i = 0; i < (n - 1) / 2; i++)
{
Console.WriteLine(
"{0}{1}{2}{1}{0}",
new string('-', ((n - 1) / 2) - i),
new string('*', 1 + 2 * i),
new string('-', n - 2 * i));
if (i < n / 2)
{
i++;
}
else
{
i--;
}
}
Console.ReadLine();
}
I have a question about my console program.
It has to count using Horner algorithm. There is no exception thrown, however, it does not give the right results.
If anyone could help me I would be very grateful, because I do not know what to do ...
Here is the code of my program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Consola_Horner_Rekurencyjnie
{
class Program
{
static void Main(string[] args)
{
int n;
Console.WriteLine("Podaj stopień wielomioanu: ");
n = Convert.ToInt32(Console.ReadLine());
int[] a = new int[++n];
Console.WriteLine("Podaj wartosc a: ");
for (int i = 0; i < n; i++)
{
Console.WriteLine("a [" + i + "] = ");
a[i] = Convert.ToInt32(Console.ReadLine());
}
int x;
Console.WriteLine("Podaj x:");
x = Convert.ToInt32(Console.ReadLine());
int Horner;
Horner = a[0];
for (int i = 1; i < n; i++)
{
Horner = Horner * (i - 1) * x + a[i];
}
Console.WriteLine("Wynik to:" + Horner);
Console.ReadLine();
}
}
}
This is the second option calculates the code, but the counts are all wrong:
Func<int, int> Horner = null;
Horner = (i) => (i == 0) ? a[0] : Horner(i - 1) * x + a[i];
Console.WriteLine("Wynik to:" + Horner(x));
Console.ReadLine();
I wanted to rewrite the original code from C + + (in the form of a recursive algorithm).
The original code looks like:
int Horner;
int n;
int *a = new int[n];
int x;
int main()
{
cout <<"Podaj stopień wielomianu: ";
cin >> n;
cin.ignore();
cout << "Podaj wartość a: \n";
for (int i = 0; i <= n; i++)
{
cout <<"a[" <<i<<"] = ";
cin >> a[i];
cin.ignore();
}
cout <<"Podaj x: ";
cin >> x;
cin.ignore();
cout <<"Wynik to: " << Horner(n);
getchar ();
return 0;
}
int Horner (int i)
{
if (i == 0)
return a[0];
else
return Horner (i - 1) * x + a[i];
}
Already I do not know how to do it ... Wandering still in the same place ...
You're unnecesarily multiplying by (i-1) in your loop.
Change it to:
int Horner;
Horner = a[0];
for (int i = 1; i < n; i++)
{
Horner = Horner * x + a[i];
}
or even better to:
int Horner = 0;
foreach (int wspolczynnik in a)
{
Horner = Horner * x + wspolczynnik;
}
You probably saw some implementation that had Horner(i-1) * x + a(i), but the (i-1) is an array index in this case, not a multiplier.
edit:
On the other hand your recursive version takes one parameter - the degree of the polynomial, and you tried to call it with x. Do it with n!
int result = Horner(n);
IMO it would be much clearer if it took 2 parameters - degree of the polynomial, and x:
Func<int, int, int> Horner = null;
Horner = (i, x) => (i == 0) ? a[0] : Horner(i - 1, x) * x + a[i];
int result = Horner(n, x);
I found here "good" source code in c# for Horner scheme:
private IEnumerable<int> getDivisors(int n)
{
if (n == 0)
return (IEnumerable<int>)new int[] { 0 };
else
return Enumerable.Range(-Math.Abs(n), 2 * Math.Abs(n) + 1)
.Where(a => a != 0)
.Where(a => (n % a) == 0);
}
private bool findRootWithHornerScheme(int[] coefficientsA, int x, out int[] coefficientsB)
{
var lenght = coefficientsA.Length;
var tmpB = new int[lenght];
coefficientsB = new int[lenght - 1];
tmpB[0] = coefficientsA[0];
for (int i = 1; i < lenght; i++)
{
tmpB[i] = tmpB[i - 1] * x + coefficientsA[i];
}
//ak je posledny koefiecient B == 0 ,tak zadane x je korenom polynomu
if (tmpB[lenght - 1] == 0)
{
Array.Copy(tmpB, coefficientsB, lenght - 1);
return true;//bol najdeny koren
}
//nebol najdeny koren a metoda vrati false
return false;
}