First i should mention that i am a beginner to C#.
This is the code i have done so far:
for (int row = 1; row <= 25; row++)
{
for (int col = 1; col <= 39; col++)
{
switch (row)
{
case 1:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 3:
Console.ForegroundColor = ConsoleColor.Green;
break;
}
Console.Write("* ");
}
Console.WriteLine();
I would really like that the three colors: Yellow, Magenta, Green to be repeated.
The three first sentence are ok, but the rest are green.
And have every other line one step to the right?
All help is appreciated
Thanks
Change your code in switch:
for (int row = 1; row <= 25; row++) {
for (int col = 1; col <= 39; col++)
{
switch (row%3)
{
case 1:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 0:
Console.ForegroundColor = ConsoleColor.Green;
break;
}
Console.Write("* ");
}
Console.WriteLine();
for (int row = 1; row <= 25; row++) {
for (int col = 1; col <= 39; col++)
{
int rowInd = row % 3;
switch (rowInd)
{
case 0:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 1:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Green;
break;
}
Console.Write("* ");
}
Console.WriteLine();
giving just 1,2,3 rows will assign values for those only. So by using % sign, you will get remainder of row / 3. That is for 3 / 3, remainder = 0; for 4 / 3, remainder = 1; and for 5 / 3; remainder = 2; again 0 for 6 / 3;
Might try something like this:
ConsoleColor[] colors = new ConsoleColor[] {
ConsoleColor.Yellow,
ConsoleColor.Magenta,
ConsoleColor.Green
};
for (int row = 1; row <= 25; row++)
{
Console.ForegroundColor = colors[(row+1) % 3];
for (int col = 1; col <= 39; col++)
{
Console.Write("*");
}
Console.WriteLine();
}
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();
}
{
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.
I need a way to update a calculated Datatable's Column base on string in other string column.
for example:
x y FormulaCol ComputedCol
------------------------------ -----------
2 5 x+y 7
2 5 x*y 10
i know that i can use a for loop and calculate result column:
for (int i = 0; i < DT.Rows.Count; i++){
string formula=DT.Rows[i]["FormulaCol"].ToString().Replace("x",DT.Rows[i]["x"]).Replace("y",DT.Rows[i]["y"])
DT.Rows[i]["ComputedCol"] =(int)DT.Compute(formula , "")
}
Is there any better way?
If you don't want to use loop, try this...
DT = DT.AsEnumerable()
.Select(
row =>
{
row["ComputedCol"] = (int)DT.Compute(row["FormulaCol"].ToString()
.Replace("x", row["x"].ToString())
.Replace("y", row["y"].ToString()), "");
return row;
}
).CopyToDataTable<DataRow>();
A simple but long solution:
This is how your table will look like,
x y FormulaCol ComputedCol
------------------------------ -----------
2 5 + 7
2 5 * 10
and your code:
for (int i = 0; i < DT.Rows.Count; i++){
switch(DT.Rows[i]["FormulaCol"].ToString()){
case "+":
int formula=(int) DT.Rows[i]["x"] + (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
case "-":
int formula=(int) DT.Rows[i]["x"] - (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
case "*":
int formula=(int) DT.Rows[i]["x"] * (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
case "/":
int formula=(int) DT.Rows[i]["x"] / (int) DT.Rows[i]["y"];
DT.Rows[i]["ComputedCol"] = formula;
break;
}
}
Hope this helps!
for (int i = 0; i < DT.Rows.Count; i++){
string formula=DT.Rows[i]["FormulaCol"].ToString()
for (int j = 0; j < DT.Columns.Count; j++){
furmula=formula.Replace(DT.Columns[j].Name ,DT.Rows[i][j].ToString())
}
DT.Rows[i]["ComputedCol"] =(int)DT.Compute(formula , "")
}
i would like to create a 3x3 matrix with input numbers and then orders number from smaller to bigger and place it in the matrix like a vortex like : 1,2,3,4,5,6,7,8,9 and place number 1 to 0.0 position,2 to 0.1, 3 to 0.2, 4 to 1.2, 5 to 2.2, 6 to 2.1, 7 to 2.0, 8 to 1.0 and 9 to 1.1.
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
List<int> l = new List<int>(l);
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS * MATRIX_COLUMNS; ++i)
{
int input;
Console.Write("Enter value");
while (!int.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
l.Add(input);
}
l.Sort();
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
matrix[i, j] = l[i * 3 + j];
}
I start like that to get input numbers and i would like help for the second part.
this will present you with the "vortex like" result for the matrix:
List<int> nums = new List<int>();
double[,] matrix = new double[3,3];
for (int i = 0; i < 9; ++i)
{
double input;
Console.Write("Enter value");
while (!double.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
nums.Add(int.Parse(input.ToString()));
}
nums.Sort();
int block = 0;
int[] order = new int[] { 0, 1, 2, 2, 2, 1, 0, 0, 1 };
for (int i = 0 ; i < order.Length; i++)
{
switch (block)
{
case 0:
matrix[block, order[i]] = nums[i];
if (i == 2)
block = 1;
break;
case 1:
if (i < order.Length - 3)
{
matrix[block, order[i]] = nums[i];
block = 2;
}
else
matrix[block, order[i]] = nums[i];
break;
case 2:
if(i == order.Length - 3)
{
matrix[block, order[i]] = nums[i];
block = 1;
}
else
matrix[block, order[i]] = nums[i];
break;
}
}
Console.WriteLine("The Resulting Matrix is:");
for (int row = 0, col = 0; row < 3; row++)
{
Console.WriteLine("row " + row + ": {0} - {1} - {2}", matrix[row, col], matrix[row, col + 1], matrix[row, col + 2]);
col = 0;
}
EDIT:now it displays the results.
As I see it - you can declare a List<int> l somewhere at the beginning, read the whole data by l.Add(x); then perform l.Sort() and after the data is sorted - populate your matrix. Let me know if you have further questions.
So you will get something like
const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;
List<int> l = new List<int>();
double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];
for (int i = 0; i < MATRIX_ROWS * MATRIX_COLUMNS; ++i)
{
double input;
Console.Write("Enter value");
while (!double.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter correct value!");
}
l.Add(input);
}
l.Sort();
for (int i = 0; i < MATRIX_ROWS; i++)
{
for (int j = 0; j < MATRIX_COLUMNS; j++)
{
matrix[i, j] = l[i*3 + j];
}
}
I'm trying to create a program for homework that displays a Tic-Tac-Toe board, and when the user clicks the button it displays a random number in all of the boxes. The number 1 = "X" and 0 = "O". I created 9 labels labeled "label1, label2...etc". Once the labels are full, I need to display who won, the letter X or O. I'm using arrays for this but am kinda of lost at this point. what do I need to do to display the random numbers into the labels. Here is the code I've written for the click event handler so far.
Random rand = new Random(2);
int click;
click = rand.Next(2);
const int ROWS = 3;
const int COLS = 3;
int[,] letters = new int[ROWS,COLS];
int ROW = ROWS;
int COL = COLS;
for (int row = 0; row < ROWS; ROW ++) {
for (int col = 0; col < COLS; COL ++) {
letters[row, col] = rand.Next(2);
int X = 1;//???
int O = 0;//???
label1.Text = [ROW,COL].ToString();//???
}
}
Here an attempt at an explanation:
first, you have the data to represent your problem:
const int ROWCOUNT = 3;
const int COLCOUNT = 3;
private int[,] letters = new int[ROWCOUNT,COLCOUNT];
Random rand = new Random(DateTime.Now.Ticks);
then you want to randomly fill that data:
private void randomize()
{
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
letters[row,col] = rand.nextInt(2);
}
}
}
finally, you want to display the array somewhere (in your case labels):
//These need to be added to a GridLayoutManager
private JLabel[,] labels = new JLabel[ROWCOUNT,COLCOUNT];
private void updateView(){
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
var current = letters[row,col];
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
}
}
}
so, when the user clicks the button, you call:
randomize();
updateView();
hope it helps
from your comments, it seems setting the Label Text needs more explanation:
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
maybe, i should have written it more like this:
String textForLabel = "O"; //0 represents O, 1 represents X
//test to see, if it really is a 0, not a 1
if( current != 0 ){
//oh, it is not a zero, therefore, set
textForLabel = "X";
}
JLabel labelAtRowAndCol = labels[row,col];
labelAtRowAndCol.Text = textForLabel;
I refuse to provide you the exact answer since you learning how to dot his is the entire point of this excerise.
Before I started the game I would randomly choose the first move: X or O.
I would then do the following:
1) I would place all the Labels into a collection.
2) I would randomly choose one of the Labels within the collection and change the Text property.
3) I would then remove the same Label from the collection
4) Rinse and Repeat.
You DO NOT need a two diminsional array for this.
In order to figure out the winner...I would keep track of the moves of each player. There is only a static number of winning moves in this game. Would be a simple task to determine if there were three X's in the top row or not.
#include<iostream>
#include<iomanip>
#include<set>
using namespace std;
char s[3][3] = {{'*','*','*'},{'*','*','*'},{'*','*','*'}};
void show(char os[3][3]);
int def[9];
void changeo(int n);
void changex(int n);
int stop();
set<int> cset;
int search (int n){
}
int main(){
int n; show(s);
int ss = 2;
cout<<endl;
while (stop()){
if (ss%2==0){
cout<<"player One(O) : enter n "; cin>>n;
if (!cset.count(n) && n<10){
cset.insert(n);
changeo(n);
show(s);
ss++;
}
else{
cout<<"invalid move"<<endl;
}
}
else{
cout<<"player Two(X) : enter n "; cin>>n;
if (!cset.count(n)&& n<10){
cset.insert(n);
changex(n);
show(s);
ss++;
}
}
}
cout<<"\nyou can see the winner"<<endl;
cout<<"your moves are "<<ss;
return 0;
}
void show(char s[3][3]){
cout<< setw(7)<< "1: " <<s[0][0]<<setw(5)<<"2: " <<s[0][1]<<setw(5)<<"3: " <<s[0][2]<<endl;
cout<< setw(7)<< "4: " <<s[1][0]<<setw(5)<<"5: " <<s[1][1]<<setw(5)<<"6: " <<s[1][2]<<endl;
cout<< setw(7)<< "7: " <<s[2][0]<<setw(5)<<"8: " <<s[2][1]<<setw(5)<<"9: " <<s[2][2]<<endl;
cout<<endl;
}
void changeo(int n){
switch(n){
case 1:
s[0][0] = 'O';
break;
case 2:
s[0][1] = 'O';
break;
case 3:
s[0][2] = 'O';
break;
case 4:
s[1][0] = 'O';
break;
case 5:
s[1][1] = 'O';
break;
case 6:
s[1][2] = 'O';
break;
case 7:
s[2][0] = 'O';
break;
case 8:
s[2][1] = 'O';
break;
case 9:
s[2][2] = 'O';
break;
}
}
void changex(int n){
switch(n){
case 1:
s[0][0] = 'X';
break;
case 2:
s[0][1] = 'X';
break;
case 3:
s[0][2] = 'X';
break;
case 4:
s[1][0] = 'X';
break;
case 5:
s[1][1] = 'X';
break;
case 6:
s[1][2] = 'X';
break;
case 7:
s[2][0] = 'X';
break;
case 8:
s[2][1] = 'X';
break;
case 9:
s[2][2] = 'X';
break;
}
}
int stop(){
int m=0;
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
if(s[i][j]=='*'){
m=1;
break;
}
}
}
return m;
}