Numbers cube, each row rotated to left by one - c#

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;
}
}

Related

Create Pyramid with decremental value

I'm trying to create a pyramid in c# using a number input.
I know how to create a normal pyramid that counts from 1-20 but I can't seem to find what to change on my code to make it.
Instead of:
1
2 2
3 3 3
4 4 4 4
I need it to be:
4
3 3
2 2 2
1 1 1 1
Here's my current code:
using System;
public class Exercise17
{
public static void Main()
{
int i,j,spc,rows,k;
Console.Write("\n\n");
Console.Write("Display the pattern like pyramid with repeating a number in same row:\n");
Console.Write("-----------------------------------------------------------------------");
Console.Write("\n\n");
Console.Write("Input number of rows : ");
rows= Convert.ToInt32(Console.ReadLine());
spc=rows+4-1;
for(i=1;i<=rows;i++)
{
for(j=spc;j>=1;j--)
{
Console.Write(" ");
}
for(k=1;k<=i;k++)
Console.Write("{0} ",i);
Console.Write("\n");
spc--;
}
}
}
First, you need to reverse the for loop. So that it starts with rows, loops while greater than zero, and decrements and each iteration
for (i = rows; i > 0; i--)
This is the main part. But you also need to take care of the spaces. So to do this we now need to keep track of how many iterations we have already performed. So we need a new variable initiated before the loop.
int iteration = 1;
for (i = rows; i > 0; i--)
.....
Then we need to use this, in the loop to output the number. And then increment it afterwards.
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
iteration++;
So the whole loop now looks like;
int iteration = 1;
for (i = rows; i > 0; i--)
{
for (j = spc; j >= 1; j--)
{
Console.Write(" ");
}
for (k = 1; k <= iteration; k++)
Console.Write("{0} ", i);
Console.Write("\n");
spc--;
iteration++;
}
Now the challenge is, can you try to optimise this further?
Instead of the following:
Console.Write("{0} ",i);
You can write:
Console.Write("{0} ", (rows - i) + 1);

How to store the results of an array matrix into a smaller array c#

I need to add a value which would be either p1(payoff one) or p2 (payoff two) to the surrounding four neighbours of a value in a matrix that'll then be printed into a new array matrix. If it's 1 then p1 will need to be added to it's neighbours or if its 0 then p2 will be added to its neighbours. I've tried to do this approach with a nested for loop but my 'if' statement in my for loop is giving me errors and Im not sure where to go next with it.
class MainClass
{
static void Main(string[] args)
{
int m, n, i, j, p1, p2;
// rows and columns of the matrix+
m = 3;
n = 3;
//Payoff matrix
p1 = 10; //cheat payoff matrix
p2 = 5; //co-op payoff matrix
int[,] arr = new int[3, 3];
Console.Write("To enter 1 it means to co-operate" );
Console.Write("To enter 0 it means to cheat");
Console.Write("Enter elements of the Matrix: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
arr[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
Console.WriteLine("Printing Matrix: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(arr[i, j] + "\t");
}
Console.WriteLine();
}
// how to change the values of the matrix
int[] payoffMatrix = new int[4];
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if(arr[i,j] == 1)
{
arr[i, j] = arr[i - 1, j] , arr[i + 1, j] , arr[i, j - 1] , arr[i, j + 1];
}
}
Console.WriteLine();
}
The result of the neighbouring values need to be printed into the payoff matrix aswell
If I understood correctly you need to make a copy of your array first. Because otherwise you would read e.g. "1" from a array position (i + 1) from the current iteration. That's probably not what you want.
Then you just set the desired values in your for-loop. You need some bound checking, because e.g. arrNew[i - 1] will only be accessible if i > 0
this gives you something like:
int[,] arrNew = arr.Clone() as int[,]; //creates a copy of arr
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (arr[i, j] == 1)
{
if (i > 0) //bounds checking
{
arrNew[i - 1, j] = 1;
}
if (i < m - 1) //bounds checking
{
arrNew[i + 1, j] = 1;
}
if (j > 0) //bounds checking
{
arrNew[i, j - 1] = 1;
}
if (j < n - 1) //bounds checking
{
arrNew[i, j + 1] = 1;
}
}
}
}
For a matrix:
0 0 0
0 1 0
0 0 0
the result would be
0 1 0
1 1 1
0 1 0

Magic Square Code Single Even number in C#

can you help me to create a logic for magic square metric. In given example, I have created a code for generate Magic Square for odd numbers like 3x3, 5x5, 7x7 metric and double even numbers like 4×4 , 8×8 but unable to found a proper solution for create single even value magic square metric like 6x6, 10x10 etc.
In current implementation anyone can enter a number (n) in input and it will create a nxn magic square metric. But not working fine with single even numbers
class Program
{
public static void Main(string [] args )
{
Console.WriteLine("Please enter a number:");
int n1 = int.Parse(Console.ReadLine());
// int[,] matrix = new int[n1, n1];
if (n1 <= 0)
{
Negativ();
}
else if (n1 == 2)
{
Zwei();
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 2 != 0))
{
Odd (n1 );
}
else if ((n1 != 2) && !(n1 < 0) && ((n1 - 2) % 4 == 0))
{//singl Even
SingleEven(n1);
}
else if ((n1 != 2) && !(n1 < 0) && (n1 % 4 == 0))
{
DoubleEven (n1);
}
}
private static void Negativ(){
Console.WriteLine("Sorry, the number must be positive and greater than 3 ");
Console.ReadLine();
}
public static void Zwei(){
Console.WriteLine("Sorry,there is no magic square of 2x2 and the number must be and greater than 3 ");
Console.ReadLine();
}
public static void Odd ( int n)// odd method
{
int[,] magicSquareOdd = new int[n, n];
int i;
int j;
// Initialize position for 1
i = n / 2;
j = n - 1;
// One by one put all values in magic square
for (int num = 1; num <= n * n; )
{
if (i == -1 && j == n) //3rd condition
{
j = n - 2;
i = 0;
}
else
{
//1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
//1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i = n - 1;
}
//2nd condition
if (magicSquareOdd[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
{
//set number
magicSquareOdd[i, j] = num++;
//1st condition
j++; i--;
}
}
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for ( i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
Console.Write(" " + magicSquareOdd[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}
public static void SingleEven(int n )
{
// int n = magic .Length ;
int[,] magicSquareSingleEven = new int[n, n];
int halfN = n / 2;
int k = (n - 2) / 4;
int temp;
int[] swapcol = new int[n];
int index = 0;
int[,] minimagic = new int[halfN, halfN];
*Odd(minimagic) ;* // here is the problem
for (int i = 0; i < halfN; i++)
for (int j = 0; j < halfN; j++)
{
magicSquareSingleEven[i, j] = minimagic[i, j];
magicSquareSingleEven[i+ halfN , j+halfN ] = minimagic[i, j]+ halfN *halfN ;
magicSquareSingleEven[i, j + halfN] = minimagic[i, j] +2* halfN * halfN;
magicSquareSingleEven[i + halfN, j] = minimagic[i, j] +3* halfN * halfN;
}
for (int i =1; i< k ;i ++)
swapcol [index ++]=i ;
for (int i = n-k+2; i <= n ; i++)
swapcol[index++] = i;
for (int i =1; i<=halfN ;i ++)
for (int j = 1; j<= index ; j ++)
{
temp = magicSquareSingleEven[i - 1, swapcol[j - 1] - 1];
magicSquareSingleEven[i-1,swapcol[j-1]-1]=magicSquareSingleEven[i +halfN-1,swapcol[j-1]-1];
magicSquareSingleEven[i+halfN-1,swapcol[j-1]-1]=temp;
}
//swaping noses
temp=magicSquareSingleEven[k,0];
magicSquareSingleEven[k,0]=magicSquareSingleEven[k+halfN,0];
magicSquareSingleEven[k+halfN,0]=temp;
temp=magicSquareSingleEven[k+halfN,k];
magicSquareSingleEven[k+halfN,k]=magicSquareSingleEven[k,k];
magicSquareSingleEven[k,k]=temp;}
//end of swaping
// print magic square
Console.WriteLine("The Magic Square for " + n + " is : ");
Console.ReadLine();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write(" " + magicSquareSingleEven[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
Console.WriteLine(" The sum of each row or column is : " + n * (n * n + 1) / 2 + "");
Console.ReadLine();
}

How do i get this output? (For loop)

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

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

Categories