{
int woodchuckSim = 0;
int numOfDays = 0;
bool validNumber = false;
bool validDays = false;
Random ran1 = new Random();
//display banner
//Ask user how many woodchucks to simulate
while(!validNumber)
{
Write("How many woodchucks would you like to simulate? (1 - 100) ");
int.TryParse(ReadLine(), out woodchuckSim);
if((woodchuckSim <= 0) || (woodchuckSim > 100))
{
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
}
else
{
validNumber = true;
}
}
//Ask user how many days to simulate
while(!validDays)
{
Write("\nHow many days would you like to simulate? (1 - 10) ");
int.TryParse(ReadLine(), out numOfDays);
if((numOfDays <= 0) || (numOfDays > 10))
{
WriteLine("Please enter a positive whole number between 1 and 10: ");
}
else
{
validDays = true;
}
}
//Using random class populate each cell between 1 and 50 that represents # of pieces of wood chucked by specific woodchuck on that specific day
int[,] sim = new int[woodchuckSim, numOfDays];
WriteLine($"{woodchuckSim} {numOfDays}");
for (int i = 0; i < sim.GetLength(0); i++)
{
for (int j = 0; j < sim.GetLength(1); j++)
{
sim[i, j] = ran1.Next(1, 50);
Write(sim[i, j] + "\t");
}
{
WriteLine(i.ToString());
}
}
WriteLine("Press any key to continue...");
ReadLine();
}
This is my code so far in my woodchuck simulation coding assignment but I need a columns and rows label on the side and top like the picture. I really don't have any idea how to do this, and I'm not sure if I'm missing a code or typed something wrong. Also at the end of the code it prints out the number of woodchucks simulated in a straight line like if the user typed in 15 it would print 0-14 in a straight line at the end which is not something I want, any help will be appreciated, thanks! (The second picture is what my code is printing)
There are a few steps to do this, but it's not too hard:
Write the column headers (include blank space at the beginning where the row headers go
Write the column underlines
For each row, write the row header first
Then for each column in the row, write the column data
After the column data is written, write a newline to start the next row
Here's a sample that produces a table similar to your output. Note that we use PadLeft to pad each column data with spaces so they're all the same width. I've also included Sum and Avg columns based on your comment below. Additionally, to clean up the main code, I added methods to write text in a different color and a method to get an integer from the user:
private static readonly Random Random = new Random();
private static void WriteColor(string text,
ConsoleColor foreColor = ConsoleColor.Gray,
ConsoleColor backColor = ConsoleColor.Black)
{
Console.ForegroundColor = foreColor;
Console.BackgroundColor = backColor;
Console.Write(text);
Console.ResetColor();
}
private static void WriteLineColor(string text,
ConsoleColor foreColor = ConsoleColor.Gray,
ConsoleColor backColor = ConsoleColor.Black)
{
WriteColor(text + Environment.NewLine, foreColor, backColor);
}
public static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
var isValid = true;
int result;
do
{
if (!isValid)
{
WriteLineColor("Invalid input, please try again.", ConsoleColor.Red);
}
else isValid = false;
Console.Write(prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
(validator != null && !validator.Invoke(result)));
return result;
}
public static void Main()
{
int columnWidth = 6;
ConsoleColor sumForeColor = ConsoleColor.DarkRed;
ConsoleColor sumBackColor = ConsoleColor.Gray;
ConsoleColor avgForeColor = ConsoleColor.White;
ConsoleColor avgBackColor = ConsoleColor.DarkGreen;
int numWoodchucks = GetIntFromUser(
"How many woodchucks would you like to simulate? (1 - 100) ... ",
x => x >= 1 && x <= 100);
int numDays = GetIntFromUser(
"How many days would you like to simulate? (1 - 10) .......... ",
x => x >= 1 && x <= 10);
int[,] data = new int[numWoodchucks, numDays];
// Write column headers, starting with a blank row header
Console.WriteLine();
Console.Write(new string(' ', columnWidth));
for (int col = 1; col <= data.GetLength(1); col++)
{
Console.Write($"{col}".PadLeft(columnWidth));
}
Console.Write(" ");
WriteColor("Sum".PadLeft(columnWidth - 1), sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor("Avg".PadLeft(columnWidth - 1), avgForeColor, avgBackColor);
// Write column header underlines
Console.Write(new string(' ', columnWidth));
for (int col = 0; col < data.GetLength(1); col++)
{
Console.Write(" _____");
}
Console.Write(" ");
WriteColor("_____", sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor("_____", avgForeColor, avgBackColor);
int total = 0;
for (int row = 0; row < data.GetLength(0); row++)
{
// Write row header
Console.Write($"{row + 1} |".PadLeft(columnWidth));
int rowSum = 0;
// Store and write row data
for (int col = 0; col < data.GetLength(1); col++)
{
data[row, col] = Random.Next(1, 50);
Console.Write($"{data[row, col]}".PadLeft(columnWidth));
rowSum += data[row, col];
}
// Write sum and average
Console.Write(" ");
WriteColor($"{rowSum}".PadLeft(columnWidth - 1),
sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor($"{Math.Round((double) rowSum / data.GetLength(1), 1):F1}"
.PadLeft(columnWidth - 1), avgForeColor, avgBackColor);
total += rowSum;
}
// Write the sum of all the items
Console.Write(new string(' ', columnWidth + columnWidth * data.GetLength(1) + 1));
WriteColor("_____", sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor("_____", avgForeColor, avgBackColor);
// Write the average of all the items
Console.Write(new string(' ', columnWidth + columnWidth * data.GetLength(1) + 1));
WriteColor($"{total}".PadLeft(columnWidth - 1), sumForeColor, sumBackColor);
Console.Write(" ");
WriteLineColor(
$"{Math.Round((double) total / (data.GetLength(0) * data.GetLength(1)), 1):F1}"
.PadLeft(columnWidth - 1), avgForeColor, avgBackColor);
Console.Write("\nPress any key to continue...");
Console.ReadKey();
}
Output
Not tested, but something like this:
Write("\t");
for (int i = 0; i < sim.GetLength(0); i++)
{
Write(i.ToString() + "\t");
}
WriteLine("\t");
for (int i = 0; i < sim.GetLength(0); i++)
{
Write("_____\t");
}
WriteLine();
for (int i = 0; i < sim.GetLength(0); i++)
{
{
WriteLine(i.ToString().PadLeft(3) + " |\t");
}
for (int j = 0; j < sim.GetLength(1); j++)
{
sim[i, j] = ran1.Next(1, 50);
Write(sim[i, j] + "\t");
}
}
Like I said, not tested, just typed right into the editor here, but that should get you close. Also, look at the string.PadLeft(int) function to get your numbers to be right-justified like the example.
Related
Here's the code of a solid diamond and I want to remove the middle and leave the edges.
From this,
to this,
public void DiamondOne()
{
int i, j, count = 1, number;
Console.Write("Enter number of rows:");
number = int.Parse(Console.ReadLine());
count = number - 1;
for (j = 1; j <= number; j++)
{
for (i = 1; i <= count; i++)
Console.Write(" ");
count--;
for (i = 1; i <= 2 * j - 1; i++)
Console.Write("*");
Console.WriteLine();
}
count = 1;
for (j = 1; j <= number - 1; j++)
{
for (i = 1; i <= count; i++)
Console.Write(" ");
count++;
for (i = 1; i <= 2 * (number - j) - 1; i++)
Console.Write("*");
Console.WriteLine();
}
Console.ReadLine();
}
I would go with something like this:
public void Diamond()
{
Console.WriteLine("Enter number of rows:");
bool isNumber = int.TryParse(Console.ReadLine(), out int rowsNr);
if (!isNumber)
{
Console.WriteLine("Not a number!");
return;
}
// print the upper half
for (int rowIndex = 0; rowIndex < rowsNr - 1; rowIndex++)
{
for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)
{
if (colIndex == Math.Abs(rowsNr - rowIndex) || colIndex == Math.Abs(rowsNr + rowIndex))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
// print the lower half
for (int rowIndex = 1; rowIndex <= rowsNr; rowIndex++)
{
for (int colIndex = 0; colIndex <= 2 * rowsNr; colIndex++)
{
if (colIndex == rowIndex || colIndex == 2 * rowsNr - rowIndex)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
}
Basically you are looking for the x and y coordinates. Each of the 4 edges has its own equation (the upper-left one is x == y for instance) and you check for these while you iterate. I split the code in two parts, one for the upper half and one for the lower half. It's more readable and you don't put together too many if statements and lose the meaning of the code.
This is what I came up with:
// Get the number of rows
int rows;
do
{
Console.WriteLine("Enter number of rows:");
} while (!int.TryParse(Console.ReadLine(), out rows));
// Print diamond
DiamondOne(rows, Console.Out);
// Wait for key press
Console.WriteLine("Press any key to exit");
Console.ReadKey(true);
static void DiamondOne(int rows, TextWriter output)
{
for (int currentRow = 0; currentRow < rows; currentRow++)
{
OutputRow(rows, output, currentRow);
}
for (int currentRow = rows - 2; currentRow >= 0; currentRow--)
{
OutputRow(rows, output, currentRow);
}
}
static void OutputRow(int rows, TextWriter output, int currentRow)
{
int indentation = rows - currentRow - 1;
int diamondCentre = Math.Max((currentRow * 2) - 1, 0);
output.Write(new string(' ', indentation));
output.Write('*');
output.Write(new string(' ', diamondCentre));
if (currentRow != 0) output.Write('*');
output.WriteLine();
}
I made a program that calculates multiplication of matrices in c#. Is it possible to show the result like this?
(Matrix1) * (Matrix2) = (Result)
My code :
using System;
namespace MatrixMultiplication;
{
class MainClass
{
static void ShowMatrix(int [,] m){
for (int i = 0; i < m.GetLength(0); i++) {
for (int j = 0; j < m.GetLength(1); j++) {
Console.Write(m[i,j]+" ");
}
Console.WriteLine ();
}
}
static int[,] MultiplyMatrices(int [,] a , int [,] b){
int[,] result = new int[a.GetLength(0),a.GetLength(1)];
for (int i = 0; i < a.GetLength(0);i++) {
for (int j = 0; j < a.GetLength(0); j++) {
for (int k = 0; k < a.GetLength(1); k++) {
result [i, k] += a [i, j] * b [j, k];
}
}
}
return result;
}
public static void Main (string[] args)
{
int rows,columns;
Console.WriteLine ("Rows : ");
rows = Convert.ToInt32 (Console.ReadLine());
Console.WriteLine ("Columns : ");
columns = Convert.ToInt32(Console.ReadLine());
int [,] lhsm = new int[rows,columns];
int [,] rhsm = new int[rows,columns];
int [,] result = new int[rows,columns];
Console.WriteLine ("Enter Elements of the First matrix : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Console.WriteLine ("F[{0}][{1}] : ",i,j);
lhsm [i,j] = Convert.ToInt32 (Console.ReadLine ());
}
}
Console.WriteLine ("Enter Elements of the Second matrix : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Console.WriteLine ("L[{0}][{1}] : ",i,j);
rhsm [i,j] = Convert.ToInt32 (Console.ReadLine ());
}
}
result = MultiplyMatrices (lhsm, rhsm);
Console.Clear ();
Console.WriteLine ("Matrix 1 : ");
ShowMatrix (rhsm);
Console.WriteLine ("Matrix 2 : ");
ShowMatrix (lhsm);
Console.WriteLine ("Result : ");
ShowMatrix (result);
}
}
}
One way to do this using SetCursorPosition would be to modify your ShowMatrix method to first store the starting position of the cursor, and then reset the cursor to the original "left" value while incrementing the "top" value for each row. Note I'm also using a variable to track the column width, which I'm using to ensure that each column is the same width for each grid. This value may need to be increased if you use large numbers:
const int maxColumnWidth = 5;
static void ShowMatrix(int[,] matrix, string name)
{
var startColumn = Console.CursorLeft;
var startRow = Console.CursorTop;
Console.SetCursorPosition(startColumn, startRow);
Console.Write($"{name}:");
Console.SetCursorPosition(startColumn, ++startRow); // <-- Note this increments the row
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j].ToString().PadRight(maxColumnWidth));
}
Console.SetCursorPosition(startColumn, ++startRow); // <-- increment row again
}
}
Then, when you call the method, you can reset the cursor position back to the top and one space more to the right from the last grid that was shown (by multiplying the number of columns by the column width constant):
// code to get matrix values omitted
result = MultiplyMatrices(lhsm, rhsm);
Console.Clear();
// Capture initial cursor values
var cursorTop = Console.CursorTop;
var cursorLeft = Console.CursorLeft;
ShowMatrix(lhsm, "Matrix 1");
// Move cursor just to the right of the previous matrix, and at the same top
cursorLeft += lhsm.GetLength(1) * maxColumnWidth + 1;
Console.SetCursorPosition(cursorLeft, cursorTop);
ShowMatrix(rhsm, "Matrix 2");
// Move cursor just to the right of the previous matrix, and at the same top
cursorLeft += rhsm.GetLength(1) * maxColumnWidth + 1;
Console.SetCursorPosition(cursorLeft, cursorTop);
ShowMatrix(result, "Result");
// Move cursor back to the beginning, and just underneath the previous matrix
Console.SetCursorPosition(0, cursorTop + result.GetLength(0) + 1);
GetKeyFromUser("\nDone! Press any key to exit...");
}
I need to add binary number logic into this snippet. I just cannot wrap my head around how to implement binary numbers, I could just add 0s and 1s but that does not seem to be right
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
}
you can use modulo (%)
c = star % 2; // will print first the '1'
c = (star + 1) % 2; // will print first the '0'
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
int c = 0;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
c = star % 2; //this will return 1 if the value of star is odd then 0 if even
Console.Write(c);
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
VIEW DEMO
I have just started using 2D arrays, but can't seem to figure out how to get the average of each column. I am using a for loop to have the user enter the data( a students grade), then a for loop to display the information user entered. But after the information is displayed, I want to display the average of each column. What should I do get the average of each column?
This is the code I have so far
static void Main(string[] args)
{
double[,] grades = new double[2, 3];
double result;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("Enter Grade " + (j + 1) + " For Group" + (i + 1) + ": ==>> ");
if (double.TryParse(Console.ReadLine(), out result)) grades[i, j] = result;
else
{
Console.WriteLine("*** INVALID GRADE ENTERED. PLEASE REENTER.");
}
}
}
for (int row = 0; row < 1; row++)
{
Console.WriteLine();
Console.Write(" Group " + (row + 1) + ": ");
Console.WriteLine(" Group " + (row + 2) + ": ");
Console.Write("=========== ===========");
for (int col = 0; col < 3; col++)
{
//String.Format("{0,-10} | {1,-10} | {2,5}",
//make pring for execise 2 Console.Write(string.Format("{0,-5}", grades[row, col]));
Console.WriteLine();
Console.Write(string.Format("{0,-9}", ""));
Console.Write(string.Format("{0,-20}",grades[0, col]));
Console.Write(grades[1,col]);
}
Console.WriteLine();
Console.WriteLine("=========== ===========");
}
Console.WriteLine("\n\npress any key to exit...");
Console.ReadKey();
//print it for exercise 1 myArr[o, column]; myArr[ , column]
}`
If you are looking for a special command that will do it for you, you're out of luck! You'll just have to write the code to do it, the same way you would normally average a series of numbers. Hint: The number of elements in the 'y' dimension of a 2D array is given by e.g. grades.GetLength(1).
To get Average per columns you need to traverse columns for a fixed row and add their values like this:
int columnTotal, average;
for (int row = 0; row < 2; row++)
{
columnTotal = 0;
for (int col = 0; col < 2; col++)
{
columnTotal += grades[row, col];
}
average = columnTotal/2;
Console.WriteLine("Average: {0}", average);
}
So I'm building a multiplication table for my C# class. I've got the code for the table complete, and it works as advertised. The issue is that I need a dynamically changing top border, because the table is as wide as the number the user enters for the width digit, at 5 character spacing. Any thoughts?
static void Main(string[] args)
{
int width, height;
//int tableWidth;
Console.Write("How wide do we want the multiplication table? ");
width = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
height = Convert.ToInt32(Console.ReadLine());
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
for (int row = 1; row <= height; row++)
{
Console.Write("{0, 5}|", row);
for (int column = 1; column <= height; ++column)
{
Console.Write("{0, 5}", row * column);
}
Console.WriteLine();
}
Console.ReadLine();
}
I assume tableWidth needs to be calculated, and then a Console.Write("_") equal to the width of the total table. Thanks in advance for your help :)
You need to use another loop, like this:
Console.Write("How wide do we want the multiplication table? ");
int width = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int height = Convert.ToInt32(Console.ReadLine());
Console.Write(" ");
for (int i = 0; i < width; i++)
Console.Write("_____");
Console.WriteLine("__");
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
for (int row = 1; row <= height; row++)
{
Console.Write("{0, 5}|", row);
for (int column = 1; column <= height; ++column)
{
Console.Write("{0, 5}", row * column);
}
Console.WriteLine();
}
Console.ReadLine();
You basically want to multiply the width by the padding you have given (5). Something like this will work. Keep in mind that I think you should break some of the spacing out into variables because you are re-using constant values like 5 in many places. Also the spacing before the x and the pipe should probably be a string variable, otherwise it is hard to see how many spaces go into each one. Here is my solution keeping the code in the same format you have so far:
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
Console.Write(" |");
for (int x = 1; x <= (width * 5); x++)
Console.Write("-");
Console.WriteLine();
Making the whole method:
static void Main(string[] args)
{
int width, height;
//int tableWidth;
Console.Write("How wide do we want the multiplication table? ");
width = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
height = Convert.ToInt32(Console.ReadLine());
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
Console.Write(" |");
for (int x = 1; x <= (width * 5); x++)
Console.Write("-");
Console.WriteLine();
for (int row = 1; row <= height; row++)
{
Console.Write("{0, 5}|", row);
for (int column = 1; column <= height; ++column)
{
Console.Write("{0, 5}", row * column);
}
Console.WriteLine();
}
Console.ReadLine();
}
Here is your code with improved naming and top line drawing (btw you have incorrect rows displaying - you are iterating over rows instead of columns in second loop):
const int columnWidth = 5;
string cellFormat = "{0, " + columnWidth + "}";
Console.Write("How wide do we want the multiplication table? ");
int columnsCount = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int rowsCount = Convert.ToInt32(Console.ReadLine());
string title = String.Format(cellFormat + "|", "x");
Console.Write(title);
for (int i = 1; i <= columnsCount; i++)
Console.Write(cellFormat, i);
Console.WriteLine();
int tableWidth = columnWidth * columnsCount + title.Length;
Console.WriteLine(new String('-', tableWidth));
for (int row = 1; row <= rowsCount; row++)
{
Console.Write(cellFormat + "|", row);
for (int column = 1; column <= columnsCount; column++)
Console.Write(cellFormat, row * column);
Console.WriteLine();
}
Next refactoring step is extracting classes and methods:
Console.Write("How wide do we want the multiplication table? ");
int columnsCount = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int rowsCount = Convert.ToInt32(Console.ReadLine());
MultiplicationTable table = new MultiplicationTable(columnsCount, rowsCount);
table.Draw();
Now code is more clear - it tells that you have multiplication table, and you want to draw it. Drawing is simple - you draw column headers and raws:
public class MultiplicationTable
{
private const int columnWidth = 5;
private string cellFormat = "{0, " + columnWidth + "}";
private int columnsCount;
private int rowsCount;
public MultiplicationTable(int columnsCount, int rowsCount)
{
this.columnsCount = columnsCount;
this.rowsCount = rowsCount;
}
public void Draw()
{
DrawColumnHeaders();
DrawRaws();
}
private void DrawColumnHeaders()
{
string title = String.Format(cellFormat + "|", "x");
Console.Write(title);
for (int i = 1; i <= columnsCount; i++)
Console.Write(cellFormat, i);
Console.WriteLine();
int tableWidth = columnWidth * columnsCount + title.Length;
Console.WriteLine(new String('-', tableWidth));
}
private void DrawRaws()
{
for (int rowIndex = 1; rowIndex <= rowsCount; rowIndex++)
DrawRaw(rowIndex);
}
private void DrawRaw(int rowIndex)
{
DrawRawHeader(rowIndex);
for (int columnIndex = 1; columnIndex <= columnsCount; columnIndex++)
DrawCell(rowIndex * columnIndex);
Console.WriteLine();
}
private void DrawRawHeader(int rowIndex)
{
Console.Write(cellFormat + "|", rowIndex);
}
private void DrawCell(int value)
{
Console.Write(cellFormat, value);
}
}