How to print below Star pattern - c#

I can't get this answer:
*****
****
***
**
*
Multidimensional arrays, nested (do..while, while, for)
char[,] stars = new char[5, 3];
for (int i = 0; i < 5; i++)
{
for(int x=0;x<3;x++)
{
stars[i,x]=char.Parse("*");
Console.Write(stars[i, x]);
I want to get 5 "*" stars then 4 in a new Line then 3 in a new Line then 1 in a new Line

Here you need to understand pattern behind *.
star pattern in your program is,
0st Line : 5 starts //Considering starting index is 0
1st Line : 4 starts // starts = n starts - Line no. where n = 5
2nd Line : 3 starts
3rd Line : 2 starts
4th Line : 1 starts
i.e.
Number of stars in single line = n starts - Line number //
where n = 5
So your code will look like,
int n = 5;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{ //^^^^^ n - i is key behind this * pattern
Console.Write("*");
}
Console.WriteLine();
}

As this is not about array indexing or address calculation but actual countable objects (stars), I feel that 1-based indexes make more sense here.
Also, the number of stars should be decreasing, so counting backwards makes more sense as well:
for (int numStars = 5; numStars >= 1; --numStars)
{
for (int star = 1; star <= numStars; ++star)
Console.Write("*");
Console.WriteLine();
}

Related

Magic square array filled with random numbers doesn't accept even numbers

I found this code that i need for an assigment, but it only reads odd numbers and i need it to read even numbers too, but i don't know whats wrong. I need it to make the random magic squares go from 1 to 10.
Still very much a beginner and don't understand functions yet, please let me know if there is a way to dolve this.
using System;
class GFG
{
// Function to generate odd sized magic squares
static void generateSquare(int n)
{
int[,] magicSquare = new int[n, n];
// Initialize position for 1
int i = n / 2;
int 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 (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
// set number
magicSquare[i, j] = num++;
// 1st condition
j++;
i--;
}
// print magic square
Console.WriteLine("The Magic Square for " + n
+ ":");
Console.WriteLine("Sum of each row or column "
+ n * (n * n + 1) / 2 + ":");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
Console.Write(magicSquare[i, j] + " ");
Console.WriteLine();
}
}
// driver program
public static void Main()
{
Console.WriteLine("Value of n: ");
int n = int.Parse(Console.ReadLine());
// Works only when n is odd
generateSquare(n);
}
}
Step through the program with a debugger. Using n = 2 as an example, on your second loop through the for loop you get to this with i = 1 and j = 1:
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
And that makes i = 2 on the next loop through. Because there is no 2 index in the array you have created, it crashes when it gets to this same check the next loop.
Presumably odd numbers are working because they are getting floored on division (in the case of n = 5 -> i = 2).
That should be enough to point you in the right direction.

How can I print the following pattern with the for statement?

How can I print the following pattern with the for statement?
AAAA
AAAB
AABB
ABBB
BBBB
What I tried to do:
Code:
int stars = 4;
for (int row = stars; row >= 1; row--)
{
for (int i = 0; i < row; i++)
{
Console.Write("A");
}
Console.WriteLine();
}
You where almost there.
I made a small change in the first for loop to add another row (>= 1 to >= 0). We need 5 rows for 4 stars, 6 rows for 5 stars, etc.
Compared the second for loop to stars as well because we want 4 values on each row (when stars is 4).
Added an if statement to check if we need to write an A or B based on the iteration number of both loops.
See code below:
int stars = 4;
for(int i = stars; i >= 0; i--) {
for(int j = 0; j < stars; j++) {
if(i > j) {
Console.Write('A');
}
else {
Console.Write('B');
}
}
Console.WriteLine();
}

C# How to break out of a nested for loop and continue with a new loop?

I am making a quest system for my game in Unity2D. I stored all my different kind of quests inside a dictionary but only 5 quests to be picked randomly for the player. I used nested loops first to get 5 random numbers, and then another foreach loop to access the elements inside the dictionary and lastly planned to use another for loop to print out all the picked quests. However, I am having problem because it printed out 25times, instead of 5. Is there a way to break out of the 2nd loop and go into the 3rd loop? Thanks!
void Start()
{
// missions
missions.Add("Visit Mural Stops x ", 1);
missions.Add("Collect Cards x ", 2);
missions.Add("Fight Monsters x", 3);
missions.Add("Collect Coins x ", 4);
missions.Add("Collect Items x", 5);
missions.Add("Fight SBM Boss x ", 6);
missions.Add("Find Mural Stops x", 7);
var numbers = new List<int>(missions.Count);
for (int i = 0; i < missions.Count; i++)
{
numbers.Add(i);
}
var randomNumbers = new int[text.Length];
// text.Length is always 5, as I only have 5 mission texts
for (int i = 0; i < randomNumbers.Length; i++)
{
var thisNumber = Random.Range(1, numbers.Count);
randomNumbers[i] = numbers[thisNumber];
numbers.RemoveAt(thisNumber);
//Debug.Log("random " + randomNumbers[i]);
foreach (KeyValuePair<string, int> pairs in missions)
{
if (pairs.Value == randomNumbers[i])
{
//Debug.Log(pairs.Key); // print out 5 missions
missionText = pairs.Key;
for (int j = 0; j < text.Length; j++)
{
text[j].text = missionText; // it only print out the last picked quests
Debug.Log(missionText); // each picked quest is printed out 5 times instead of once
// how do i print out only 5 times inside this loop?
}
}
}
}
}
Your problem is your last loop:
for (int j = 0; j < text.Length; j++)
{
text[j].text = missionText;
Debug.Log(missionText);
}
This is running the Debug.Log five times - once for each value of j (and you say earlier that text.Length is always 5).
In comments you say want to print all the picked quests into my texts.
You already have an index for your text - i - since your randomNumbers array is the same length as your texts and indeed the whole point of randomNumbers seems to be to generate a random number for each entry of text. So rather than that loop I quoted what you want to do is:
text[i].text = missionText;

Calculate Nth Pi Digit

I am trying to calculate the nth digit of Pi without using Math.Pi which can be specified as a parameter.
I modified an existing algorithm, since I like to find the Nth digit without using string conversions or default classes.
This is how my algorithm currently looks like:
static int CalculatePi(int pos)
{
List<int> result = new List<int>();
int digits = 102;
int[] x = new int[digits * 3 + 2];
int[] r = new int[digits * 3 + 2];
for (int j = 0; j < x.Length; j++)
x[j] = 20;
for (int i = 0; i < digits; i++)
{
int carry = 0;
for (int j = 0; j < x.Length; j++)
{
int num = (int)(x.Length - j - 1);
int dem = num * 2 + 1;
x[j] += carry;
int q = x[j] / dem;
r[j] = x[j] % dem;
carry = q * num;
}
if (i < digits - 1)
result.Add((int)(x[x.Length - 1] / 10));
r[x.Length - 1] = x[x.Length - 1] % 10; ;
for (int j = 0; j < x.Length; j++)
x[j] = r[j] * 10;
}
return result[pos];
}
So far its working till digit 32, and then, an error occurs.
When I try to print the digits like so:
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine("{0} digit of Pi is : {1}", i, CalculatePi(i));
}
Console.ReadKey();
}
This I get 10 for the 32rd digit and the 85rd digit and some others as well, which is obviously incorrect.
The original digits from 27 look like so:
...3279502884.....
but I get
...32794102884....
Whats wrong with the algorithm, how can I fix this problem?
And can the algorithm still be tweaked to improve the speed?
So far it works right up until the cursor reaches digit 32. Upon which, an exception is thrown.
Rules are as follows:
Digit 31 is incorrect, because it should be 5 not a 4.
Digit 32 should be a 0.
When you get a 10 digit result you need to carry 1 over to the previous digit to change the 10 to a 0.
The code changes below will work up to ~ digit 361 when 362 = 10.
Once the program enters the 900's then there are a lot of wrong numbers.
Inside your loop you can do this by keeping track of the previous digit, only adding it to the list after the succeeding digit has been computed.
Overflows need to be handled as they occur, as follows:
int prev = 0;
for (int i = 0; i < digits; i++)
{
int carry = 0;
for (int j = 0; j < x.Length; j++)
{
int num = (int)(x.Length - j - 1);
int dem = num * 2 + 1;
x[j] += carry;
int q = x[j] / dem;
r[j] = x[j] % dem;
carry = q * num;
}
// calculate the digit, but don't add to the list right away:
int digit = (int)(x[x.Length - 1] / 10);
// handle overflow:
if(digit >= 10)
{
digit -= 10;
prev++;
}
if (i > 0)
result.Add(prev);
// Store the digit for next time, when it will be the prev value:
prev = digit;
r[x.Length - 1] = x[x.Length - 1] % 10;
for (int j = 0; j < x.Length; j++)
x[j] = r[j] * 10;
}
Since the digits are being updated sequentially one-by-one, one whole iteration later than previously, the if (i < digits - 1) check can be removed.
However, you need to add a new one to replace it: if (i > 0), because you don't have a valid prev value on the first pass through the loop.
The happy coincidence of computing only the first 100 digits means the above will work.
However, what do you suppose will happen when a 10 digit result follows a 9 digit one? Not good news I'm afraid, because the 1 with need carrying over to the 9 (the previous value), which will make it 10.
A more robust solution is to finish your calculation, then do a loop over your list going backwards, carrying any 10s you encounter over to the previous digits, and propagating any carries.
Consider the following:
for (int pos = digits - 2; pos >= 1; pos--)
{
if(result[pos] >= 10)
{
result[pos] -= 10;
result[pos - 1] += 1;
}
}

Checkers Board Assistance

I'm just wondering if there is a simpler way of doing this:
for (int i = 0; i < 1; i++)
{
for (int j = 0; i < 8; j+2)
{
board[ i, j ] = 2;
board[( i + 1 ), j ] = 2;
board[( i + 2 ), j ] = 2;
}
}
What I'm trying to do is place checkers pieces on the actual checkers board. So this is to place the black pieces on the top.
P.S. If you could also give me some help on the bottom set of pieces(white).
Apart from fixing the loop you could otherwise explicitly place the pieces, makes it more readable
int[,] board = new[,]{{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}};
Modulo will do the trick but i think that TonyS's anwser was my first reaction and I would prefer that insteed the one shown below.
char[,] board = new char[8,8];
private void InitializeBoard()
{
string BoardRepresentation = "";
//for every board cell
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
//initialize board cell
board[i, j] = '0';
if (j <= 2)//black top
{
//Modulo is the trick
if ((j - i) == 0 || ((j - i) % 2) == 0)
{
board[i, j] = 'B';
}
}
else if (j >= 5) //white bot
{
if ((j - i) == 0 || ((j - i) % 2) == 0)
{
board[i, j] = 'W';
}
}
}
}
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < 8; i++)
{
BoardRepresentation += board[i, j] + " ";
}
BoardRepresentation += Environment.NewLine;
}
}
You missed to tell us what exactly is it that you want to achieve. I see several big errors in your code, so I'll assume that you don't have full grasp of how for loop works. I hope it's not too presumptuous that I'm trying to explain it here
For loop
For loop is used to execute same portion of code several times. How many times it will be executed depends on conditions you set. Most often, you will see it in this format:
for (int i = 0; i < n; i++)
{
// Some code
}
This for loop executed code within the brackets ({ and }) n times. This is not only way to define a loop. More thorough definition of a loop is following:
for (<initialization>; <condition>; <afterthought>)
Initialization - You can some variables needed for looping. This is executed once before code within the loop is executed first time. This is optional, and you can leave it empty and use variable declared before in condition.
Condition - This is executed before each execution of code within the loop. If condition expression evaluates to true, loop is executed. Once loop is executed and afterthought is executed, condition is evaluated again and again until it evaluates to false. Condition is also optional. If you leave it out, in C# loop will be executed again until you break the loop in a different way.
Afterthought - This is executed each time code within the loop is finished executing. This is usually used to increment a variable on which loop depends. This is also optional.
Fixing your code
I assume you wanted to mark fields in a 8x8 matrix like in a checkerboard, although this is not stated in your question. You could do it this way:
// For each row in a board (start with 0, go until 7, increase by 1)
for (int i = 0; i < 8; i++)
{
// start coloring the row. Determine which field within the row needs
// to be black. In first row, first field is black, in second second
// field is black, in third row first field is black again and so on.
// So, even rows have black field in first blace, odd rows have black
// on second place.
// We calculate this by determining division remained when dividing by 2.
int firstBlack = i % 2;
// Starting with calculated field, and until last field color fields black.
// Skip every second field. (start with firstBlack, go until 7, increase by 2)
for (int j = firstBlack; j < 8; j += 2)
{
// Color the field black (set to 2)
board[i][j] = 2;
}
}
You can see my comments inline.
Big errors in your code
// This loop would be executed only once. It goes from 0 to less than 1 and is increased
// after first execution. You might as well done it without the loop.
for (int i = 0; i < 1; i++)
{
// This doesn't make sense, because you use i in condition, and initialize
// and update j.
// Also, you are trying to update j, but you are not doing so. You are not
// assigning anything to you. You should do j+=2 to increase by two. Or you
// can do j = j + 2
for (int j = 0; i < 8; j+2)
{
// I didn't really understand what you were trying to achieve here
board[ i, j ] = 2;
board[( i + 1 ), j ] = 2;
board[( i + 2 ), j ] = 2;
}
}

Categories