How do i get this output? (For loop) - c#

I'm trying to get the end result:
1
2 1
3 2 1
4 3 2 1
This is what I have tried so far and I have the shape but I need the number to decrease. How do I solve this? I understand that I have to subtract somewhere but it compromises the shape.
public static void DrawDiamond(int size)
{
int i, j;
for (i = 1; i <= size; i++)
{
for (j = 1; j < i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
}
My current results is this:
1
1 2
1 2 3
1 2 3 4

Hello JeremyM,
Logic
int i, j;
for (i = 1; i <= no_of_row; i++)
{
for (j = i; j>=1; j--)
{
Console.Write(j);
}
Console.WriteLine();
}
Solution
using System.IO;
using System;
class Program
{
static void Main()
{
int i, j;
for (i = 1; i <= no_of_row; i++)
{
for (j = i; j>=1; j--)
{
Console.Write(j);
}
Console.WriteLine();
}
}
}
For Example:
no_o_rows = 5 so output,
1
21
321
4321
54321
I hope my answer is helpful.
If any query so comment please.

Print value of i-j+1 insted of only j

Or if you prefer to work with Linq:
Enumerable.Range(1, 5).ToList().ForEach(x =>
{
Console.WriteLine();
Enumerable.Range(1, x).Reverse().ToList().ForEach(y => Console.Write(y));
});
which produces:
1
21
321
4321
54321

This works too:
Console.WriteLine(String.Join(Environment.NewLine,
Enumerable
.Range(1, 4)
.Select(x => String.Join(" ", Enumerable.Range(1, x).Reverse()))));
I get:
1
2 1
3 2 1
4 3 2 1

Related

How can i modify this nested for loop in C#?

I am trying to print out a pyramid/Pascal Triangle that will give output in series of 3. You can see it in the example below.
1
1 3 1
1 3 9 3 1
1 3 9 27 9 3 1
1 3 9 27 81 27 9 3 1
1 3 9 27 81 243 81 27 9 3 1
1 3 9 27 81 243 729 243 81 27 9 3 1
1 3 9 27 81 243 729 2187 729 243 81 27 9 3 1
Instead of getting the above output, I am getting this:
Here is my code:
using System;
namespace ConsoleApp
{
class PiscalTriangle
{
static void Main(string[] args)
{
Console.WriteLine("Enter length : ");
int num = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < num; i++)
{
for (int j = num; j > i; j--)
{
Console.Write(" ");
}
int val = 1;
for (int j = 0; j <= i; j++)
{
Console.Write(val + " ");
val = val * (i - j) / (j + 1);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
There are three main aspects to be considered for generating the desired ouput:
The depth of the pascal tree which is defined with the help of num variable and an iterator i which ranges from 1 to num
The elements in each row of the pascal tree are in the sequence 1,3,5,7.. which when correlated with depth of tree is equivalent to 2i-1. Hence the row values iterator j ranges from 1 to 2i-1
And finally the value (For example 3rd row, 1 3 9 3 1), can be written in the form of 3 power x, where x increases from 0 to i and then decreases to 0
By summing up the 3 conditions, we can get our desired output.
using System;
namespace ConsoleApp
{
class PiscalTriangle
{
static void Main(string[] args)
{
Console.WriteLine("Enter length : ");
int num = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= num; i++)
{
for (int j = num; j > i; j--)
{
Console.Write(" ");
}
var x = 0;
for (double j = 1; j <= 2*i-1; j++)
{
double val = Math.Pow(3, x);
Console.Write(val + " ");
if(j < i)
{
x++;
}
else
{
x--;
}
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

How do I print the output in one row below another?

For example I am trying to print the output in following way:
disk: 1 2 3 4 5
move: 1 3 7 15 31
How can I do that, can someone help me out please?
{
class Program
{
static void Main(string[] args)
{
int n = 2;
for (int j = 1; j <= 5; j++)
Console.WriteLine("disk: {0}", j);
for (int i = 1; i <= 5; i++)
Console.WriteLine("moves: {2:N0}",
n, i,(long)Math.Pow(n, i) - 1);
}
}
}
Console.WriteLine will, as it sounds, write a new line each time. If you don't want that behavior, use Console.Write.
Console.Write("Disk:");
for (int j = 1; j <= 5; j++)
Console.Write(" {0}", j);
Console.WriteLine();
Console.Write("Moves:");
for (int i = 1; i <= 5; i++)
Console.Write(" {2:N0}", (long)Math.Pow(n, i) - 1);
Console.WriteLine();
Use the string.PadLeft() method to justify your text. Of course you can replace the magic numbers with a constant value. This gives you the advantage of not having to count spaces, and automatically adds the right amount of spaces to bring the string up to the desired length.
Note that you can also get rid of the format insertion (i.e. no more curly braces).
static void Main(string[] args)
{
int power = 2;
Console.Write("disk:".PadLeft(8));
for (int j = 1; j <= 5; j++)
Console.Write(j.ToString().PadLeft(5));
Console.WriteLine();
Console.Write("moves:".PadLeft(8));
for (int i = 1; i <= 5; i++)
Console.Write(((long)Math.Pow(power, i) - 1).ToString().PadLeft(5));
Console.WriteLine();
Console.ReadLine();
}
This is the result:
You can use Console.Write and it wont print a carriage return.
However you dont need a for loop in this case. Just use Enumerable.Range
var n = 2;
var disks = Enumerable.Range(1, 5).ToList();
var moves = Enumerable.Range(1, 5).Select(i => (long) Math.Pow(n, i) - 1);
Console.WriteLine("disk: {0}", string.Join(" ", disks));
Console.WriteLine("moves: {0:N0}", string.Join(" ", moves));
Results:
disk: 1 2 3 4 5
moves: 1 3 7 15 31

Numbers cube, each row rotated to left by one

Basic C# question:
I need to have that result when entering some number (this case was entered 4):
4 3 2 1 0
3 2 1 0 4
2 1 0 4 3
1 0 4 3 2
I was trying that code, but cant figure out my mistake:
Console.WriteLine("Please write a Number: ");
Console.Write("Number: ");
int num = int.Parse(Console.ReadLine());
for (int i = 0; i <= num; i++)
{
for (int j = num - i; j >= 0; j--)
{
Console.Write(j);
}
for (int j = 1; j <= i; j++)
{
Console.Write(j);
}
Console.WriteLine();
}
Console.ReadLine();
This is the output I get:
4 3 2 1 0
3 2 1 0 1
2 1 0 1 2
1 0 1 2 3
0 1 2 3 4
Try this:
Console.WriteLine("Please write a Number: ");
Console.Write("Number: ");
int num = int.Parse(Console.ReadLine());
for (int i = 0; i <= num; i++)
{
for (int j = num - i; j >= 0; j--)
{
Console.Write(j);
}
for (int j = num; j > num - i; j--)
{
Console.Write(j);
}
Console.WriteLine();
}
Console.ReadLine();
The problem is that your second inner loop is starting at one and counting up rather than starting from num and counting down.
Change that loop to:
for (int j = num; j > num -i; j--)
{
Console.Write(j);
}
Also I'm not clear if you want the last line of 04321 or not. If you don't (as in the original example) then just change your loop check to i<num.
Try something like this
get a number(x) from user.
create a list of integer containing x to 0.
run a loop for x times.
every time print the list and pop the first number and push it at the end
var ints = new List<int> { 4, 3, 2, 1, 0 };
for (int i = 0; i < 4; i++)
{
ints.ForEach(n => Console.Write(n + " "));
Console.WriteLine("");
var a = ints[0];
ints.RemoveAt(0);
ints.Add(a);
}
As a hint I give you the main loop as a pseudo code:
for i from 0 to number_input-1 {
for j from number_input to 0 {
print((j-i)%(number_input+1) + " ")
}
print("\n")
}
Just for fun:
const int NUM = 4; // num from user
for (int start = NUM; start > 0; start--)
{
for (int i = 0; i <= NUM; i++)
{
int current = (start - i) >= 0 ? start - i : NUM + (start - i) + 1;
Console.Write(current + " ");
}
Console.WriteLine();
}
Honestly this is a classic sorting task. it's just hidden beyond "user types and bla bla bla" but I remember at school it was..
There is an array [4,3,2,1,0].. so
we swap 1 and 2 and get [3,4,2,1,0].
we swap 2 and 3 and get [3,2,4,1,0].
we swap 3 and 4 and get [3,2,1,4,0].
we swap 4 and 5 and get [3,2,1,0,4].
so just simple code
int[] numbers let say you have this array [4,3,2,1,0]
for(int i = 0; i < numbers.length - 2; i++){
for(int y = 0; y < numbers.length - 1; y++){
int buf = numbers[y];
numbers[y] = numbers[y + 1];
numbers[y + 1] = buf;
}
}

How can I calculate the number at a given row and column in Pascal's Triangle?

I'm trying to create a function that, given a row and column, will calculate the value at that position in Pascal's Triangle.
Example:
val = GetPasVal(3, 2); // returns 2
So here I'm specifying row 3, column 2, which as you can see:
1
1 1
1 2 1
...should be a 2.
The Pascal's triangle contains the Binomial Coefficients C(n,k);
There is a very convenient recursive formula
C(n, k) = C(n-1, k-1) + C(n-1, k)
You can use this formula to calculate the Binomial coefficients.
Using Armen's equation the recursive code for implementing pascals triangle will be like below:
using System;
using System.Collections.Generic;
public class Program
{
public void Main()
{
for(int i =0 ; i<5;i++)
{
int sum = 1;
Console.WriteLine();
for(int j =0 ; j<=i;j++)
{
Console.Write(pascal(i,j));
//Console.Write(sum); //print without recursion
sum= sum *(i-j) / (j + 1);
}
}
}
public int pascal(int x, int y)
{
if((x+1)==1 || (y+1)==1 || x==y)
{
return 1;
}
else
{
return pascal(x-1,y-1)+ pascal(x-1,y);
}
}
}
There is a formula from Combinations for working out the value at any place in Pascal's triangle:
It is commonly called n choose k and written like this:
n choose k = n! / k!(n-k)!
Notation: n choose k can also be written C(n,k), nCk.
static void Main(string[] args)
{
var x = GetPasVal(3, 2);
Console.WriteLine(x);
}
public static long GetPasVal(int row, int col)
{
int factOfRow = 1,i;
for(i = 1;i<=(row - 1);i++)
factOfRow *= i;
int factOfRowMinusCol = 1;
for(i = 1;i<=(row - 1)- (col - 1);i++)//check out below link to understand condition
factOfRowMinusCol *= i;
int factOfCol = 1;
for(i = 1;i<= (col - 1);i++)
factOfCol *=i;
int fact = factOfRow / (factOfCol * factOfRowMinusCol);
return fact;
}
https://www.mathsisfun.com/pascals-triangle.html
for row in range(10):
print('{: ^45}'.format(' '.join(str(pascal(row, col)) for col in range(row+1))))
Use the above code to print out your pascal triangle and thereby modify the code. The first 10 should look like:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
The GetPasVal method will calculate all the numbers in the Pascal's Triangle up to the point that you will give (height) and after that the method will return the value of the index on that row(width). This is something you can use. It's quite simple. You just have to use a jagged array.
static void Main(string[] args)
{
var x = GetPasVal(3, 2);
Console.WriteLine(x);
}
public static long GetPasVal(int height, int width)
{
long[][] triangle = new long[height][];
for (int i = 0; i < height; i++)
{
triangle[i] = new long[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
if (i >= 2)
{
for (int j = 1; j < i; j++)
{
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
}
return triangle[height - 1][width - 1];
}

Different combinations of an array (C#)

how can we find out different combination of the elements of an array using c# code.
are there any inbuilt library function for this.?
for eg: suppose an array has elements {2,3,4,5,6,7}
then the possible combination would be 2,3,4,5,6,7,2 3,2 3 4,2 3 4 5, etc
so basically wat i need is a function which gives different combination based on its input for eg: comb(array,2) gives output 2 3,1 2,3 4 and comb(array,3) gives output 1 2 3,2 3 4,3 4 5 and so on
Eg: valid comnbination for array= {1, 2, 3} and length = 2 are 1 2,1 3,2 3 .....
static void Main()
{
var cnk = comb(new [] {1,2,3},2);
foreach ( var c in cnk)
{
}
}
public static IEnumerable<int[]> comb(int[] a, int k)
{
if (a == null || a.Length == 0 || k < 1 || k > a.Length)
yield break;
int n = a.Length;
// 1
if ( k == 1)
for ( int i = 0; i < n; i++)
{
yield return new int[] {a[i]};
}
else
{
// k
for ( int i = 0; i < n - k + 1; i++)
{
var res = new int[k];
for (int t = i, c = 0; t < i + k - 1; t++, c++)
res[c] = a[t];
for (int j = i + k - 1; j < n; j++)
{
res[k-1] = a[j];
yield return res;
}
}
}
}
You should take the algorithm from here, my answer doesn't solve your problem
Algorithm to return all combinations of k elements from n
Seemed logic is not absolutely correct as:
var cnk = comb(new[] { 1, 2, 3, 4 }, 3);
This gives 3 variants, but as a matter of fact it is 4:
1 2 3
1 2 4
1 3 4
2 3 4
I guess comb is better to be implemented in recursive way.

Categories