Putting values of an array into text boxes using C# - c#

I've created a dimensional array using two for loops, and as each inner loop completes, I'd like those values to go into textboxes on a windows form. (I realize that the values will be overwritten each time, with just the values from the final outer loop showing at the end.)
The comments in the code show what I've been trying to get to work.
Thanks!
if (IsValidData())
{
int Columns = 5;
int Rows = Convert.ToInt32(txtNumbDrawings.Text);
int[,] ball = new int[Columns, Rows];
for (int i = 0; i < Rows; i++)
{
List<int> ballsList = new List<int>();
int[] txtBall = new int[Columns];
for (int j = 0; j < Columns; j++)
{
Random number = new Random();
ball[i, j] = number.Next(1, 70);
// prevent duplicate numbers
while (ballsList.Contains(ball[i, j] ))
{
ball[i, j] = number.Next(1, 70);
}
ballsList.Add(ball[i, j]);
/*************************************************
* how do I get the current ball value
* into a textbox on a form?
*
* textboxes are named txtBall1, txtBall2, etc...
*
* I was trying something like:
*
* TextBox[] txtBall = new TextBox[5];
* for (int i = 0; i < 5; i++)
* {
* txtBall[i + 1].Text = ball[i, j].ToString();
* }
*************************************************/
}
ballsList = null;
}
}
Windows Form Image: https://1drv.ms/u/s!Ak6hxvO3Ye6Oj5I9NQy834Yk4TRLyw?e=DniwK8

If I understand what you're trying to do, and that seems to be assigning a shuffled list of integers to one of 5 list boxes, then this should do it:
if (IsValidData())
{
Random rnd = new Random();
// (1, 69) because rnd.Next(1, 70) only produces the numbers 1 to 69
int[] shuffled_balls = Enumerable.Range(1, 69).OrderBy(x => rnd.Next()).ToArray();
ListBox[] list_boxes = new [] { lstBall1, lstBall2, lstBall3, lstBall4, lstBall5 };
for (int i = 0; i < shuffled_balls.Length; i++)
{
list_boxes[i % list_boxes.Length].Items.Add(shuffled_balls[i]);
}
}

Related

Battleship game C#

I am stuck upon a problem about namimng the colums and the lines, differently than 0 to 10. something like this picture, the lines starting from the bottom 1 to 10 and colums from A to J.
I've created a program that tells me if the ship is destroyed or not, after using 14 moves( in this image using move 5 c, in my program 5 2, counts as a hit, if all the blue squares are hit the program returns destroyed).
My problem is that i don't know why i can't user input a move like "4 a" (Input string was not in a correct format.' - after debugging). I wrote the following code:
char[,] board = new char[10, 10];
int table = 10;
int hits = 2;
int totalHits = 14;
int neededHits = 8;
for (int i = 9; i >= 0; i--)
{
string line = Console.ReadLine();
string[] boardCharacters = line.Split(' ');
for (int j = 0; j < table; j++)
{
board[i, j] = Convert.ToChar(boardCharacters[j]);
}
}
int countHits = 0;
for (int z = 0; z < totalHits; z++)
{
var ac = Console.ReadLine().Split(' ');
var c1 = int.Parse(ac[0]) - 1;
var c2 = (ac[1].ToLower()[0] - 'a');
int[] attack = new int[2];
for (int i = 0; i < hits; i++)
{
attack[i] = int.Parse(ac[i]);
}
if (board[attack[0], attack[1]] == 'x')
{
countHits++;
}
}
Console.WriteLine(countHits == neededHits ? "destroyed" : "not destroyed");
Console.ReadLine();
Your problem is in this section:
var ac = Console.ReadLine().Split(' ');
var c1 = int.Parse(ac[0]) - 1;
var c2 = (ac[1].ToLower()[0] - 'a');
int[] attack = new int[2];
// You've already parsed the two parts of the input into 'c1' and 'c2'.
// This loop is redundant, and is the cause of the problem.
for (int i = 0; i < hits; i++)
{
// When 'i' = 1, this is looking at the second part of the input ("a")
// and trying to parse it as a number. This is what causes the exception.
attack[i] = int.Parse(ac[i]);
}
I would suggest removing that loop, and populate the 'attack' array when you create it:
int[] attack = new int[] { c1, c2 };

What should I change so each line would have a different random amount of numbers?

I have written code where all lines have an equal amount of numbers. What should I change so each line would have a different random amount of numbers?
Random ran = new Random();
int x = ran.Next(2, 8);
int j = ran.Next(4, 10);
int[][] arr = new int[x][];
for (int i = 0; i < x; i++)
{
int[] sub = new int[j];
for (int y = 0; y < j; y++)
{
sub[y] = ran.Next(1, 10);
}
arr[i] = sub;
Console.WriteLine($"{string.Join(",",arr[i])}");
}
this is what I currently have.
Move the declaration and assignment to j into the loop so you'll get a new random number each time instead of only once.

For loop rows and columns of a list

I am new in C# and I have a problem with for loops in lists.
I have a list with numbers (called alpha) which go from 0 to 7.
alpha0=1
alpha1=2
alpha2=3
...
alpha7=8
Now I want to create a matrix containing all these alphas in this way and then I want to transpose it:
I've tried to write the transposed one directly but it gives me error or better I am wrong with the syntax (see last string of my code). Could somebody help me?
I called startinglist my list with alphas.
List<List<double>> arr = new List<List<double>>();
for (int col = 0; col < 8; col++)
for (int row = 0; row < 7; row++)
arr[col, row].Add(startinglist[col]);
Try below code:
var size = 8;
var alpha = Enumerable.Range(1, size).ToArray();
var matrix = new int[size, size + 1];
for (int i = 0; i < size; i++)
{
// Assign values on the diagonal.
matrix[i, i] = alpha[i];
matrix[i, i + 1] = 1 - alpha[i];
}
Try this:
var size = 8;
int[] alpha = Enumerable.Range(1, size).ToArray();
int[][] C = new int[size - 1][];
for(int i = 0 ; i < size - 1; i++)
{
C[i] = new int[size];
C[i][i] = alpha[i];
C[i][i + 1] = 1 - alpha[i + 1];
}
Edit:
Since you have alpha already defined as a list, you may use this:
Edit2:
Changed int to double:
double[][] C = new double[alpha.Count - 1][];
for(int i = 0 ; i < alpha.Count - 1; i++)
{
C[i] = new double[alpha.Count];
C[i][i] = alpha[i];
C[i][i + 1] = 1 - alpha[i + 1];
}

how to generate a random numbers...? in c#

I have a 2d arrays button [5,5] all blue color...how to randomly generate 5 red button in the array...?
int Rows = 5;
int Cols = 5;
Button[] buttons = new Button[Rows * Cols];
int index = 0;
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Cols; j++)
{
Button b = new Button();
b.Size = new Size(40, 55);
b.Location = new Point(55 + j * 45, 55 + i * 55);
b.BackColor = Color.Blue;
buttons[index++] = b;
}
}
panel1.Controls.AddRange(buttons);
As simple as this
int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
int idx = rnd.Next(Rows * Cols);
if (buttons[idx].BackColor == Color.Blue)
{
buttons[idx].BackColor = Color.Red;
cnt++;
}
}
You will use the Random class to choose an index value between 0 and 24 and use that index to select one of your blue buttons, if the selected button has a blue backcolor, change it to Red
By the way, this works because you don't really have a 2 dimension array here.
In case your array is declared as a 2 dimension array like here
Button[,] buttons = new Button[Rows, Cols];
then you need two random values at each loop, one for the row and one for the column
int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
int row = rnd.Next(Rows);
int col = rnd.Next(Cols);
if (buttons[row, col].BackColor == Color.Blue)
{
buttons[row, col].BackColor = Color.Red;
cnt++;
}
}

Subarrays from a 2D multdimensional array

I've run into a stall trying to put together some code to average out 10x10 subarrays of a 2D multidimensional array.
Given a multidimensional array
var myArray = new byte[100, 100];
How should I go about creating 100 subarrays of 100 bytes (10x10) each.
Here are some examples of the value indexes the subarrays from the multidimensional would contain.
[x1,y1,x2,y2]
Subarray1[0,0][9,9]
Subarray2[10,10][19,19]
Subarray3[20,20][29,29]
Given these subarrays, I would then need to average the subarray values to create a byte[10,10] from the original byte[100,100].
I realize this is not unbelievably difficult, but after spending 4 days debugging very low-level code and now getting stuck on this would appreciate some fresh eyes.
Use this as a reference. I used ints just for ease of use. Code is untested. but the idea is there.
var rowSize = 100;
var colSize = 100;
var arr = new int[rowSize, colSize];
var r = new Random();
for (int i = 0; i < rowSize; i++)
for (int j = 0; j < colSize; j++)
arr[i, j] = r.Next(20);
for (var subcol = 0; subcol < colSize / 10; subcol++)
{
for (var subrow = 0; subrow < colSize/10; subrow++)
{
var startX = subcol*10;
var startY = subrow*10;
var avg = 0;
for (var x=0; x<10; x++)
for (var y = 0; y < 10; y++)
avg += arr[startX + x, startY + y];
avg /= 10*10;
Console.WriteLine(avg);
}
}
It looks like you're new to SO. Next time try to post your attempt at the problem; it's better to fix your code.
The only challenge is figuring out the function, that given the subarray index we're trying to populate, would give you the correct row and column indexes in your original 100x100 array; the rest would just be a matter of copying the values:
// psuedocode
// given a subarrayIndex of 0 to 99, these will calculate the correct indices
rowIndexIn100x100Array = (subarrayIndex / 10) * 10 + subArrayRowIndexToPopulate;
colIndexIn100x100Array = (subarrayIndex % 10) * 10 + subArrayColIndexToPopulate;
I'll leave it as an exercise to you to deduce why the above functions correctly calculate the indices.
With the above, we can easily map the values:
var subArrays = new List<byte[,]>();
for (int subarrayIndex = 0; subarrayIndex < 100; subarrayIndex++)
{
var subarray = new byte[10, 10];
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
int rowIndexIn100x100Array = (subarrayIndex / 10) * 10 + i;
int colIndexIn100x100Array = (subarrayIndex % 10) * 10 + j;
subarray[i, j] = originalArray[rowIndexIn100x100Array, colIndexIn100x100Array];
}
subArrays.Add(subarray);
}
Once we have the 10x10 arrays, calculating the average would be trivial using LINQ:
var averages = new byte[10, 10];
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
averages[i, j] = (byte)subArrays[(i * 10) + j].Cast<byte>().Average(b => b);
}
Fiddle.

Categories

Resources