Starpattern in console app - c#

I need to create the following pattern:
It is homework, this question I failed the first time.
I read now that I should have only used "*" one time, but how would this even work in that case?
Would appreciate if anyone could give me some insight in how to think.
My code is down below:
using System;
class StarPattern
{
public static void Main()
{
for (int i = 0; i < 5; i++)
{
Console.Write("*");
}
for (int a = 0; a <= 0; a++)
{
Console.WriteLine("");
Console.Write("*");
}
for (int c = 0; c <= 0; c++)
{
Console.WriteLine(" *");
}
for (int d = 0; d <= 1; d++ )
{
Console.Write("*");
Console.WriteLine(" *");
}
for (int e = 0; e < 5; e++ )
{
Console.Write("*");
}
Console.ReadLine();
}
}

You can simplify your code by nesting loops so outer (i) = rows and inner (j) = columns. From looking at your sample, you want to write out if you're on the boundary of either so you can add a condition to just write out on min and max.
private static void Main(string[] args)
{
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
if (i == 0 || i == 4 || j == 0 || j == 4)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
Console.ReadKey();
}
I'd probably replace 0 with a constant called MIN and 4 with a constant called MAX to save duplicating them. That way, you could increase the size of the square by just changing the constants.

Hardly anyone is commenting their code for you. How disappointing!
The trick here is to focus on what is important and define values that you will;
be using many times in the code
only want to change once if requirements need tweeking
These values are height and width - the core components of a rectangle.
The golden rule for the pattern is: If the row and column of each character is on the edge of the square, print a *
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stars
{
class Program
{
static int Width = 5; //define the width of the square in characters
static int Height = 5; //define the height of the square in characters
static void Main(string[] args)
{
for (int row = 0; row <= Height; row++) //Each iteration here is one row.
{
//loop representing columns. This is NESTED within the rows so
//that each row prints more than one column
for (int column = 0; column <= Width; column++)
{
if (IsCentreOfSquare(row, column)) //calculate if the current row and column coordinates are the interior of the square
{
Console.Write(" ");
}
else
{
Console.Write("*");
}
}
Console.WriteLine(); //this row is over. move to the next row
}
Console.ReadLine(); //pause so that the user can admire the pretty picture.
}
/// <summary>
/// Calculates if the row and column indexes specified are in the interior of the square pattern
/// </summary>
/// <returns></returns>
private static bool IsCentreOfSquare(int row, int col)
{
if (row > 0 && row < Height)
{
if (col > 0 && col < Width)
{
return true;
}
}
return false;
}
}
}

This might be overkill for such a simple program, but make it scalable and add some const ints to make the design able to be modified whenever you'd like!
Good question. It's fun to feel like I'm tutoring again! Glad to see you at least gave it an honest attempt :)
class Program
{
// Use string if you are okay with breaking the current pattern.
// private static string myDesign = "*";
// Use char if you want to ensure the integrity of your pattern.
private static char myDesign = '*';
private const int COLUMN_COUNT = 5;
private const int ROW_COUNT = 5;
private const int FIRST_ROW = 0;
private const int LAST_ROW = 4;
private const int FIRST_COLUMN = 0;
private const int LAST_COLUMN = 4;
static void Main(string[] args)
{
// Iterate through the desired amount of rows.
for (int row = 0; row < ROW_COUNT; row++)
{
// Iterate through the desired amount of columns.
for (int column = 0; column < COLUMN_COUNT; column++)
{
// If it is your first or last column or row, then write your character.
if (column == FIRST_COLUMN || column == LAST_COLUMN || row == FIRST_ROW || row == LAST_ROW)
{
Console.Write(myDesign);
}
// If anywhere in between provide your blank character.
else
{
Console.Write(" ");
}
}
Console.WriteLine("");
}
Console.Read();
}
}

It is not that difficult to do. You need to create two loops: one for the rows and one for the columns and then determine whether to print a star or not. Only the first and the last rows and columns have a star.
In my example I use two counters that start from 0 and count to 4. If the remainder of either counter value divided by 4 equals to 0 then I print a star, otherwise a space.
using System;
namespace Stars
{
internal static class StarPattern
{
private static void Main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write((i%4 == 0) | (j%4 == 0) ? '*' : ' ');
}
Console.WriteLine();
}
}
}
}

You need to print a certain number of lines with a certain sequence of characters per line.
One approach would be to create or find a method that prints whatever character sequence you need. Then create a method to sequence calls to to that. Finally, print the result of all that.
private void PrintBox(char c, int width, int height)
{
var result = new List<string>();
result.Add(new string(c, width)); // First line
for (var i = 0; i < height - 2; i++)
{
string iLine;
int spaceCount = width - 2;
iLine = new string(c, 1) + new string(' ', spaceCount) + new string(c, 1);
result.Add(iLine);
}
result.Add(new string(c, width)); // Last line
// FYI, there's a StringBuilder class that makes all this easier
foreach (var line in result)
{
Console.WriteLine(line);
}
}
The important OOP concept here is that we made use of a single reusable method for constructing a sequence of characters - new string(char, int). If we wanted to create a Circle, we could create a BuildCircle method based on the same principle.

Related

You can only display 60 characters per line

When running this program, my first line has 62 digits while the other lines only have 60. How can I place 2 spaces in front of the first line so each line of the array is no more then 60 characters? So basically it would look like ( with two spaces in the beginning)
9999999999999999999999999999999999999999999999999999999999
999999999999999999999999999999999999999999999999999999999999
999999999999999999999999999999999999999999999999999999999999
using System;
namespace BigFactorial
{
class Program
{
static int MAX = 5000;
//This is telling the program what to multiply.
private static void mult(int[] x, int n)
{
int y = 0, i, m;
for (i = 0; i < MAX; i++)
{
m = y + x[i] * n;
x[i] = m % 10000;
y = m / 10000;
}
}
//This is telling the program how to calculate factorial of n.
public static void Factorial(int[] a, int n)
{
a[0] = 1;
for (int i = n; i > 1; i--)
{
mult(a, i);
}
}
//This is displaing the factorial after the calculation.
public static void Display(int[] a)
{
int i;
for (i = MAX - 1; a[i] == 0; i--) ;
Console.Write(a[i]);
for (int j = i - 1, c = 1; j >= 0; j--, c++)
{
string s = "" + a[j];
Console.Write(s.PadLeft(4, '0'));
if (c % 15 == 0)
Console.WriteLine();
}
Console.WriteLine();
}
public static void Main(string[] args)
{
while (true)
{
//Telling user to enter a number.
Console.Write("Enter a number to factor or a negative number to quit: ");
int n = int.Parse(Console.ReadLine());
//Quit function
if (n < 0) break;
int[] arr = new int[MAX];
Factorial(arr, n);
Display(arr);
}
//100000 is the max number it can calculate
}
}
}
You have already demonstrated that you know how to use String.PadLeft(), so cache the strings that you are writing in memory so you can inspect them rather than writing directly out to the console.
using System.Linq;
using System.Text;
public static void Display(int[] a)
{
int i = 0;
// build the string in memory, so we can inspect the length of the lines
StringBuilder output = new StringBuilder();
output.Append(a[i]);
for (int j = i - 1, c = 1; j >= 0; j--, c++)
{
output.Append($"{a[j]}".PadLeft(4, '0'));
if (c % 15 == 0)
output.AppendLine();
}
// get the lines into an array so we can normalise the length,
// although we know the length today, calculating it expresses the intent better
var lines = output.ToString().Split(new string [] { Environment.NewLine }, StringSplitOptions.None);
var maxLength = lines.Max(x => x.Length);
// now write the output to the console
foreach(var line in lines)
Console.WriteLine(line.PadLeft(maxLength, ' '));
}
It is not necessary to use StringBuilder like this, you could have used a List<string> and that would simplify the code further. It is however useful to identify that code written targeting the Console can easily be refactored to write to memory via StringBuilder as the syntax is very similar.
You could also have used a StringWriter instance called Console and the syntax would be identical... But that was a step too far for a logic block as simple as this.

fill a 2D array as a diamond shape

I want to fill my array with struct in a way that it will look like this
I have this code so far :
`for (int i = 1; i <= n; i++)
{
for (int j = 0; j <=(n - i); j++)
//i should fill m[,] here
for (int j = 1; j <= i; j++)
//i should fill m[,] here
for (int k = 1; k < i; k++)
//i should fill m[,] here
}
for (int i = n - 1; i >= 1; i--)
{
for (int j = 0; j < (n - i); j++)
//i should fill m[,] here
for (int j = 1; j <= i; j++)
//i should fill m[,] here
for (int k = 1; k < i; k++)
//i should fill m[,] here
}`
but I 'm a little bit confused with the index .
how can I adopt this code?
As it's unclear wether the array always has the size 5 I'll assume it has the size n with n being odd and n > 0 (The size is the x and the y size, as I assume that your matrix is quadratic). Then there are several ways to reach the goal your trying to reach, I'll try to present you one I thought of.
First of all we have to think about the array - as it's the easiest way, I'll assume it consists of boolean values (even though you said "I want to fill my array with struct", but as I'm not quite sure what you wanted to say with that and wether you really meant a struct, I'll let this up to you, as this shouldn't be the most difficult part):
var matrix = new bool[n,n];
Then we have to evalueate which fields have to be filled. Therefore we must realize a few things:
The filled fields are always central in their line
The first and last line always have one filled item
The following line always has two more/less filled items, so that the offset is one more than in the previous line
The center line has most items and is the turning point in the amount of filled items
As a first step in developing the algorithm, I'd write a function to fill lines of the array with specific amounts of fields:
private static void FillLine(int line, int count, bool[,] matrix)
{
//Firstly we have to evaluate the offset:
var offset = (matrix.GetLength(0) - count) / 2;
//Then we have to fill the line
for (var x = offset; x < offset + count; x++)
matrix[x, line] = true;
}
Now we simply have to fill the lines for the whole array:
public static void FillDiamond(bool[,] matrix)
{
var count = 1;
for (var line = 0; line < matrix.GetLength(1) / 2; line++)
{
FillLine(line, count, matrix);
count += 2;
}
FillLine(matrix.GetLength(1) / 2, count, matrix);
count = 1;
for (var line = matrix.GetLength(1) - 1; line > matrix.GetLength(1) / 2; line--)
{
FillLine(line, count, matrix);
count += 2;
}
}
Now in a console application you could use this like that:
using System;
namespace SO_c
{
internal static class Program
{
private static void Main()
{
while (true)
{
var n = int.Parse(Console.ReadLine());
if (n < 1 || n % 2 == 0)
continue;
var matrix = new bool[n, n];
FillDiamond(matrix);
for (var y = 0; y < matrix.GetLength(1); y++)
{
for (var x = 0; x < matrix.GetLength(0); x++)
Console.Write(matrix[x, y] ? "█" : " ");
Console.WriteLine();
}
}
}
private static void FillLine(int line, int count, bool[,] matrix)
{
//Firstly we have to evaluate the offset:
var offset = (matrix.GetLength(0) - count) / 2;
//Then we have to fill the line
for (var x = offset; x < offset + count; x++)
matrix[x, line] = true;
}
public static void FillDiamond(bool[,] matrix)
{
var count = 1;
for (var line = 0; line < matrix.GetLength(1) / 2; line++)
{
FillLine(line, count, matrix);
count += 2;
}
FillLine(matrix.GetLength(1) / 2, count, matrix);
count = 1;
for (var line = matrix.GetLength(1) - 1; line > matrix.GetLength(1) / 2; line--)
{
FillLine(line, count, matrix);
count += 2;
}
}
}
}
This can result in output like that:
That's it! Now you should get your diamond for every matrix that fits the rules :)
One way to do it is to calculate the center of the grid and fill in each row, from the center column. In each successive row, we increment the number of blocks we fill in on each side of the center column until we get to the center row, and then we decrement the number of blocks we fill in until we get to the end.
To determine how many blocks to put on each side of the center column for any given row, we can use the row index for the calculation.
Working our way from the top down to the center, the row index represents the number of blocks to add. So, for row index 0, we add 0 blocks on either side of the center column, row index 1 we add 1 block on each side, until we get to the center.
After we get to the center, we want to decrement the number of blocks each time, which can be done by subtracting the row index from the total number of rows.
The code says it better, I think:
private static void Main()
{
while (true)
{
// Get grid size from user and keep it between 1 and the window width
var gridSize = GetIntFromUser("Enter the size of the grid: ");
gridSize = Math.Min(Console.WindowWidth - 1, Math.Max(1, gridSize));
var grid = new bool[gridSize, gridSize];
var center = (gridSize - 1) / 2;
// Populate our grid with a diamond pattern
for (int rowIndex = 0; rowIndex < grid.GetLength(0); rowIndex++)
{
// Determine number of blocks to fill based on current row
var fillAmount = (rowIndex <= center)
? rowIndex : grid.GetUpperBound(0) - rowIndex;
for (int colIndex = 0; colIndex <= fillAmount; colIndex++)
{
grid[rowIndex, center - colIndex] = true;
grid[rowIndex, center + colIndex] = true;
}
}
// Display the final grid to the console
for (int row = 0; row < grid.GetLength(0); row++)
{
for (int col = 0; col < grid.GetLength(1); col++)
{
Console.Write(grid[row, col] ? "█" : " ");
}
Console.WriteLine();
}
}
}
Oh, and this is the helper function I used to get an integer from the user. It's pretty helpful to keep around because you don't have to do any validation in your main code:
private static int GetIntFromUser(string prompt)
{
int value;
// Write the prompt text and get input from user
Console.Write(prompt);
string input = Console.ReadLine();
// If input can't be converted to a double, keep trying
while (!int.TryParse(input, out value))
{
Console.Write($"'{input}' is not a valid number. Please try again: ");
input = Console.ReadLine();
}
// Input was successfully converted!
return value;
}
OUTPUT

Method that Searches 2-D array for a specific number and will return a Boolean value of true if found

I am writing a program that creats a two-dimensional array fills it with random numbers and then prompts the user to enter a number and searches the 2-d array for that number.
I have the entire program completed beside the last method which I am lost on.
I am supposed to have this method return a bool to indicate if the sought out number was found or not. I am supposed to initialize the row and column parameters to -1 and have this method to use first parameter and the 2-d array parameter to search the array for the number. If the number is found I am to assign the row and column parameters to the row and column index where it is found and stop searching the array right away.
Any advice on the searchArray() method is greatly appreciated. Thank you!
Here is the code filled with errors in the last method that I have so far:
static void Main(string[] args)
{
int [,] randomNumArray = new int[3, 5];
FillArray(randomNumArray);
PrintArray(randomNumArray);
SumRows(randomNumArray);
SumCols(randomNumArray);
SumArray(randomNumArray);
GetNumber();
}
public static void FillArray(int[,] randomNumbersArray)
{
Random num = new Random();
for (int r = 0; r < randomNumbersArray.GetLength(0); r++)
{
for (int c = 0; c < randomNumbersArray.GetLength(1); c++)
{
randomNumbersArray[r, c] = num.Next(15, 97);
}
}
}
public static void PrintArray(int[,] randomPrintArray)
{
for (int r = 0; r < randomPrintArray.GetLength(0); r++)
{
for (int c = 0; c < randomPrintArray.GetLength(1); c++)
{
Console.Write("{0,3:F0}", randomPrintArray[r, c]);
}
Console.WriteLine("");
}
Console.WriteLine("");
}
public static void SumRows(int[,] sumOfRowsArray)
{
int rowSum;
for (int r = 0; r < sumOfRowsArray.GetLength(0); r++)
{
rowSum = 0;
for (int c = 0; c < sumOfRowsArray.GetLength(1); c++)
{
rowSum += sumOfRowsArray[r, c];
}
Console.WriteLine("The total sum for row "+ (r + 1) + " is: " + rowSum + ".");
}
Console.WriteLine("");
}
public static void SumCols(int[,] sumOfColsArray)
{
int colsSum;
for (int c = 0; c < sumOfColsArray.GetLength(1); c++)
{
colsSum = 0;
for (int r = 0; r < sumOfColsArray.GetLength(0); r++)
{
colsSum += sumOfColsArray[r, c];
}
Console.WriteLine("The total sum for column " + (c + 1) + " is: " + colsSum + ".");
}
Console.WriteLine("");
}
public static void SumArray(int[,] sumOfAllArray)
{
int sumOfAll = 0;
for (int r = 0; r < sumOfAllArray.GetLength(0); r++)
{
for (int c = 0; c < sumOfAllArray.GetLength(1); c++)
{
sumOfAll += sumOfAllArray[r, c];
}
}
Console.WriteLine("Total for sum of the Array is: " + sumOfAll + "\n");
}
public static int GetNumber()
{
Console.Write("Please enter a number between 15 and 96: ");
int chosenNumber = int.Parse(Console.ReadLine());
while (chosenNumber > 96 || chosenNumber < 15)
{
Console.Write("Number not between 15 and 96. Try again: ");
chosenNumber = int.Parse(Console.ReadLine());
}
return chosenNumber;
}
public static bool SearchArray(int soughtOutNum, int [,] searchableArray, out int rowIndex, out int colsIndex)
{
bool itsTrue == false;
for (int c = 0; c < searchableArray.GetLength(0); c++)
{
for (int r = 0; r < searchableArray.GetLength(1); r++)
{
if (searchableArray[r, c] == soughtOutNum)
{
return itsTrue == true;
break;
}
}
}
Console.WriteLine("");
}
}
}
Your code has four problems that I can see.
First, two of your parameters are marked as out parameters, but you haven't filled in a value for them. Think of out parameters like multiple return values: instead of the caller passing your function something, you're passing it back out. Since the person calling this function is probably going to rely on the values in those, you have to explicitly give them a value. This is probably giving you compiler errors.
I would start by assigning -1 to each of the two out parameters at the beginning of your function, and when you find the number you're searching for (that inner if statement), overwrite those -1's with the real answer (hint: how do you know what column and row you're on?)
Second, your use if itsTrue is a bit odd. In C# (and many other languages), we use a single = for assignment, and a double == for comparison. If you fix that, it should work, and give you the right answer. However, from a code clarity standpoint, why do you need the variable at all? It's never used except as a return value... why don't you just return true directly when you find the number you're looking for.
Third, your method isn't guaranteed to return a value: what happens if it never finds a number? Eventually, you're going to fall outside of both for loops, and you'll reach that Console.WriteLine(""); you have at the bottom... but what do you return in that case?
Finally, when you call the method, you need to let C# know where to stick the values of those out parameters. Right now, when you try to call SearchNumber(10), it can't find a method with just ONE parameter. There's only one with 3. You should instead declare variables where you can store the row and column, and then pass those in, like so:
int row, col;
SearchNumber(10, out row, out col);
I think you are not so far away from the solution if I understood you correctly. Are you looking for something like this?
public static bool SearchArray(int soughtOutNum, int[,] searchableArray, out int rowIndex, out int colsIndex)
{
rowIndex = -1;
colsIndex = -1;
// Assuming your c is column and r is row
for (int c = 0; c < searchableArray.GetLength(0); c++)
{
for (int r = 0; r < searchableArray.GetLength(1); r++)
{
if (searchableArray[r, c] == soughtOutNum)
{
rowIndex = r;
colsIndex = c;
//Console.WriteLine("found number");
return true;
}
}
}
//Console.WriteLine("Number not found");
return false;
}
Update to answer to the comment:
I coded it without a Visual Studio at hand so look out for typos.
static void Main(string[] args)
{
int [,] randomNumArray = new int[3, 5];
FillArray(randomNumArray);
PrintArray(randomNumArray);
SumRows(randomNumArray);
SumCols(randomNumArray);
SumArray(randomNumArray);
int row;
int column;
int search = GetNumber();
if (SearchArray(search, randomNumArray, out row, out column))
{
Console.WriteLine("found " + search + " at row " + row + " col " + column);
}
else
{
Console.WriteLine("Number not found");
}
}
Update 2:
There is also an error in the last method.
You have constructed your array like this: randomNumbersArray[row, column]
In all methods r is from GetLength(0) and c is GetLength(1). But in the last method you switch and your r is GetLength(1) and c is GetLength(0). So you switch the numbers when accessing the array and essentially call randomNumbersArray[column, row]. This will give you an error when c_max != r_max.

How is my boundaries outside of the array?

On my array, on line 40, my boundaries are outside of the array, but I am not sure how to format this since this is my first program with a multi dimensional array. Please help me. Thanks! (Line 40 is array[i, 0] = randomArray.Next(0, 100);)
namespace Exercise6
{
class Program
{
static void Main(string[] args)
{
OtherClass aTable = new OtherClass(); //instantiate class
Console.WriteLine("How many rows do you want your two-dimensional array to be?");
aTable.SRows = Console.ReadLine(); //reads input for how many rows that the user would like
aTable.IntRows = int.Parse(aTable.SRows); //convert rows to int
Console.WriteLine("Thanks you! How many columns would you like your two-dimensional arry to be?");
aTable.SColumns = Console.ReadLine(); //reads input for how many columns that the user would like
aTable.IntColumns = int.Parse(aTable.SColumns); //convert columns to int
//set two dimensional array based upon the size that the user has requested
int[ , ] array = new int[aTable.IntColumns, aTable.IntRows];
Random randomArray = new Random(); //call to random class to ask for random numbers
for (int i = 0; i <= aTable.IntColumns; i++) // rows
{
array[i, 0] = randomArray.Next(0, 100); // for every value in each row, insert a random number
}
//both arrays here are overloaded. See this site to see if can get help. Site is below after last close loop
for (int y = 0; y <= aTable.IntRows; y++) // columns
{
array[y, y] = randomArray.Next(0, 100);
}
Console.WriteLine(array);
}
}
}
namespace Exercise6
{
class OtherClass
{
private string sRows;
public string SRows { get; set; }
private int intRows;
public int IntRows { get; set; }
private string sColumns;
public string SColumns { get; set; }
private int intColumns;
public int IntColumns { get; set; }
}
}
Change loop condition to i < aTable.IntColumns
You loop starts from 0 and goes to value of aTable.IntColumns - 1
and code becomes
for (int i = 0; i < aTable.IntColumns; i++)
{
array[i, 0] = randomArray.Next(0, 100);
}
Since arrays are zero based, you can't go up to the max value:
// This line is incorrect
for (int i = 0; i <= aTable.IntColumns; i++)
That line should be:
for (int i = 0; i < aTable.IntColumns; i++)
That will let it go from 0 to aTable.IntColumns-1, which are the valid indices for for an array of aTable.IntColumns length. The same is true of the rows.
C# arrays used zero-relative offsets as their indices. That means that for an array of length n, the domain of its index i is 0 <= i <= n-1. A 100-element array has an index that ranges from 0-99. If you are trying to fill an m*n array with random values.
If your assignment is fill the array with random values (as seems likely), you'll need to do something like this:
for ( int i=0 ; i < aTable.IntRows ; i++ ) // rows
{
for ( int j= 0 ; i < aTable.IntColumns ; j++ )
{
array[i,j] = randomArray.Next(0,100); // for every value in each row, insert a random number
}
}
You might also note that your comments don't match your code: you are iterating over rows and checking the column limit and vice-versa.
The error is in for loop:
for (int i = 0; i < aTable.IntColumns; i++) // rows
{
array[i, 0] = randomArray.Next(0, 100); // for every value in each row, insert a random number
}
i < aTable.IntColumns should be the stopping criteria

Properly printing a 2D array?

Currently working on writing a Conways life in C# for class. I've been taking small steps to get a hang out the language and game programming in general and have hit a snag in printing my 2D char array. Currently I'm using GetLength - 1 to not go over the bound but it fails to print out the last chars in the array.
What my initial file looks like
+*++
++*+
****
After its read into placed into Char (i believe)
*
*
****
What ends up printed
*
**
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace ConwaysLife
{
class Program
{
static char[,] universe;
static void bigBang(int h, int w, List<string> grid)
{
universe = new char[h,w];
int row = 0;
foreach (string line in grid)
{
for (int i = 0; i < line.Length; i++)
{
if (line.ToCharArray()[i] == '*')
{
universe[row, i] = '*';
}
}
row++;
}
}
//How I'm attempting to print out my 2D char array
static void offspring()
{
StringBuilder cellLine = new StringBuilder();
for (int y = 0; y < universe.GetLength(1)-1; y++)
{
for (int x = 0; x < universe.GetLength(0)-1; x++)
{
Console.Write(universe[y, x]);
}
Console.WriteLine();
}
//pause
Console.ReadLine();
}
static void Main(string[] args)
{
List<string> tempLine = new List<string>();
//Console.WriteLine("File Path?");
int width = 0;
int height = 0;
//read file into List
using (StreamReader r = new StreamReader("life.txt"))
{
while (r.Peek() >= 0)
{
tempLine.Add(r.ReadLine());
//compare current width to new width
if (tempLine[height].Length >= width) { width = tempLine[height].Length; }
//increase height when going to next row
height++;
}
bigBang(height, width, tempLine);
}
offspring();
}
}
}
Update Offspring()
static void offspring()
{
StringBuilder cellLine = new StringBuilder();
for (int x = 0; x <= universe.GetLength(1); x++)
{
for (int y = 0; y <= universe.GetLength(0); y++)
{
Console.Write(universe[x, y]);
}
Console.WriteLine();
}
//pause
Console.ReadLine();
}
You have an off-by-one error in your offspring function. Note that you're doing it correctly in the bigBang function.
You are looping while x < GetLength()-1. You just need x < GetLength(), because that excludes the case when x == GetLength().
An analagous loop:
for (i = 0; i < 4; i++)
Console.WriteLine(i);
Output:
0
1
2
3
I'm not familiar with the game principles, but there's a problem in your offspring method.
y < universe.GetLength(1)-1
This translates to y < 3 - 1 or y < 2, making your iteration go from y = 0 to 1.
To fix, simply remove the two occurences of -1.
for (int y = 0; y < universe.GetLength(1); y++)
{
for (int x = 0; x < universe.GetLength(0); x++)
{
In addition, you have your indices reversed when you access universe.
Console.Write(universe[y, x]);
There you're using the y variable to access the row, and x for the column. The inverse should be done like this:
Console.Write(universe[x, y]);
Giving a final output of
++*
*+*
+**
++*
While I'll delve deeper as to why it wasn't working as I expected it to I simply passed the sizes of the array when I created it to my offspring() and used those values when printing. Once that small change was the done the output came out as expected.
*
*
****

Categories

Resources