how can i save the number that user enter in textbox in a 2 dimension array?
for example:
i have this numbers in textbox:45,78
and now i want to save 45,32 like this: array[0,0]=45 and array[0,1]=78
how can i do that?thanks,so much
edited:
oh,when i entered 1,2,3,4,5,6,7,8,9 in textbox and it takes [2,2]=56
private void button10_Click(object sender, EventArgs e)
{
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox9.Text.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i % (matrixDimention + 1), i % (matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
string a=intValues[2,2].ToString();
MessageBox.Show(a);
}
when i take:
string a=intValues[2,1].ToString();
it shows 0
Have a look at using String.Split Method (Char[]) and Convert.ToInt32 Method (String)
Something like
string textBox = "45,78";
int[,] values = new int[1,2];
string[] textBoxSplit = textBox.Split(',');
values[0, 0] = Convert.ToInt32(textBoxSplit[0]);
values[0, 1] = Convert.ToInt32(textBoxSplit[1]);
EDIT
Example using List and Linq
string textBox = "45,78,1,2,3,4,5,6,7,8,9,10,11,12";
List<int> list = new List<int>(textBox.Split(',').Select(x => Convert.ToInt32(x)));
EDIT 2
Longwinded example using List and foreach
string textBox = "45,78,1,2,3,4,5,6,7,8,9,10,11,12";
List<int> list2 = new List<int>();
string[] splitVals = textBox.Split(',');
foreach (string splitVal in splitVals)
list2.Add(Convert.ToInt32(splitVal));
EDIT
Enter the matrix
string textBox = "1,2,3,4,5,6,7,8,9";
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i/(matrixDimention + 1), i%(matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
EDIT
Follow the white rabbit
string textBox = "1,2,3,4,5,6,7,8,9";
int matrixDimention = 2;
int[,] intValues = new int[matrixDimention + 1, matrixDimention + 1];
string[] splitValues = textBox.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i/(matrixDimention + 1), i%(matrixDimention + 1)] = Convert.ToInt32(splitValues[i]);
string displayString = "";
for (int inner = 0; inner < intValues.GetLength(0); inner ++)
{
for (int outer = 0; outer < intValues.GetLength(1); outer++)
displayString += String.Format("{0}\t", intValues[inner, outer]);
displayString += Environment.NewLine;
}
MessageBox.Show(displayString);
try this assuming array is a string array
str[] input = textBox.Text.Split(',');
if(input.Length > 1)
{
arr[0,0] = input[0];
arr[0,1]= input[1];
}
Related
How can I bubble sort a 2D string array by their lenght? In the array's zeroth column there are random generated messages and in the first column there are random generated priorities.
string[,] array = new string[50, 2];
Random r = new Random();
int number = 0;
int space = 0;
double fontossag = 0;
for (int i = 0; i < 50; i++)
{
string message = "";
int hossz = r.Next(10,51);
for (int h = 0; h < hossz; h++)
{
number = r.Next(0,101);
space = r.Next(0, 101);
if (number<=50)
{
message += (char)r.Next(97,122);
}
else if(number >= 50)
{
message += (char)r.Next(65, 90);
}
if (space<=10)
{
message += " ";
}
}
for (int f = 0; f < 50; f++)
{
fontossag = r.NextDouble() * (10.0);
}
array[i, 0] += message;
array[i, 1] += fontossag;
}
I want to sort the array by the random generated messages length.
This is my method to Bubble sort on the first column length:
public static string[,] BubbleSortStringByLength(string[,] array)
{
int num = array.GetLength(0);
for (int i = 0; i < num - 1; i++)
{
for (int j = 0; j < num - i - 1; j++)
{
if (array[j, 0].Length > array[j + 1, 0].Length)
{
// swap first column
string tmp = array[j, 0];
array[j, 0] = array[j + 1, 0];
array[j + 1, 0] = tmp;
// swap second column
tmp = array[j, 1];
array[j, 1] = array[j + 1, 1];
array[j + 1, 1] = tmp;
}
}
}
return array;
}
You can download the Visual Studio solution on GitHub
So you want to compare lengths of 1st columns and swap rows to ensure descending priority:
for (bool hasWork = true; hasWork;) {
hasWork = false;
for (int row = 0; row < array.GetLength(0) - 1; ++row) {
int priority1 = array[row, 0]?.Length ?? -1;
int priority2 = array[row + 1, 0]?.Length ?? -1;
// if we have wrong order...
if (priority1 < priority2) {
// we should keep on working to sort the array
hasWork = true;
// and swap incorrect rows
for (int column = 0; column < array.GetLength(1); ++column)
(array[row, column], array[row + 1, column]) =
(array[row + 1, column], array[row, column]);
}
}
}
Please, fiddle yourself
I have a List of 9 integers and I want to print all elements from the list as a matrix 3,3. And I have to avoid unnecessary white space on the end of every line.
Is it possible to use String.Join ?
Thanks.
Here's my code:
int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[][] matrix = new int[input[0]][];
for (int i = 0; i < input[0]; i++)
{
int[] line = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
matrix[i] = line;
}
List<int> arr = new List<int>(9);
List<int> arr1 = new List<int>(9);
arr = Enumerable.Repeat(0, 9).ToList();
//for (int i = 0; i < 9 ; i++) sum[i%3, i/3] = 0;
for (int row = 0; row < input[0] - 2; row++)
{
for (int col = 0; col < input[1] - 2; col++)
{
arr1.Add(matrix[row][col]);
arr1.Add(matrix[row][col + 1]);
arr1.Add(matrix[row][col + 2]);
arr1.Add(matrix[row + 1][col]);
arr1.Add(matrix[row + 1][col + 1]);
arr1.Add(matrix[row + 1][col + 2]);
arr1.Add(matrix[row + 2][col]);
arr1.Add(matrix[row + 2][col + 1]);
arr1.Add(matrix[row + 2][col + 2]);
if (arr1.Sum() > arr.Sum())
{
arr = arr1.Select(a => a).ToList();
}
arr1.Clear();
}
}
Console.WriteLine($"Sum = {arr.Sum()} ");
// print the list as a matrix
This is how I would print it using String.Join:
List<int> asd = new List<int> {1,2,3,4,5,6,7,8,9};
for (int i = 0; i < asd.Count; i +=3)
{
Console.WriteLine(string.Join(" ",asd.Skip(i).Take(3)));
}
Explanation: Walk in steps of 3. Skip the amount of numbers equal to the stepsize and take 3 to combine a row of the matrix.
You should reconsider the accepted answer because the performance is poorly with many items.
It may be irrelevant for your current count of items but still hear my warning.
I ran the following code snippet:
var sb = new StringBuilder();
for (int i = 0; i < asd.Count; i +=3)
sb.AppendLine(string.Join(" ", asd.Skip(i).Take(3)));
Console.WriteLine(sb.ToString());
used a StringBuilder to remove the time relevant Console.WriteLine(); for every item in the loop.
This approach takes 756,115ms to complete, with 1,000,000 items.
Created the asd list like this:
var asd = Enumerable.Range(0, 1000000).ToList();
Every other answer given so far will perform way better.
The reason why the accepted solution performs this poorly is because of the .Skip() that is getting called inside the loop, it doesn't actually skip and go directly to this Position instead it again and again loops the list till it reaches this point.
My solution would be:
Console.WriteLine(string.Concat(asd.Select((x, i) => (i + 1) % 3 != 0 ? x + " " : x + Environment.NewLine)));
Which executes the same task in 8,610ms
For completness:
Wojtek's solution takes: 7,932ms
Nirmal Subedi' solution takes: 8,088ms
Note:
Changed it so that it uses a StringBuilder to build the string and only output the string once to the console, instead of calling Console.WriteLine() in a loop
Here my complete test routine:
var asd = Enumerable.Range(0, 1000000).ToList();
var sw1 = new Stopwatch();
sw1.Start();
Console.WriteLine(string.Concat(asd.Select((x, i) => (i + 1) % 3 != 0 ? x + " " : x + Environment.NewLine)));
sw1.Stop();
var sw2 = new Stopwatch();
sw2.Start();
var sb1 = new StringBuilder();
for (int i = 0; i < asd.Count; i += 3)
sb1.AppendLine(string.Join(" ", asd.Skip(i).Take(3)));
Console.WriteLine(sb1.ToString());
sw2.Stop();
var sw3 = new Stopwatch();
sw3.Start();
var sb2 = new StringBuilder();
int counter = 0;
string output = "";
foreach (int value in asd)
{
counter++;
if (counter % 3 == 0)
{
output += value;
sb2.AppendLine(output);
output = string.Empty;
}
else
output += value + " ";
}
Console.WriteLine(sb2.ToString());
sw3.Stop();
var sw4 = new Stopwatch();
sw4.Start();
var sb3 = new StringBuilder();
for (int i = 0; i <asd.Count / 3; i++)
{
int index = i * 3;
sb3.AppendFormat("{0} {1} {2}", asd[index], asd[index + 1], asd[index + 2]);
sb3.AppendLine();
}
Console.WriteLine(sb3.ToString());
sw4.Stop();
Console.WriteLine("MySolution: " + sw1.ElapsedMilliseconds);
Console.WriteLine("Mong Zhu's Solution: " + sw2.ElapsedMilliseconds);
Console.WriteLine("Wojtek's Solution: " + sw3.ElapsedMilliseconds);
Console.WriteLine("Nirmal Subedi's Solution: " + sw4.ElapsedMilliseconds);
Console.ReadKey();
Now You have your code pasted. Anyway, I created the sample to print the 3x3 matrix.
class Program
{
static void Main(string[] args)
{
StringBuilder stringBuilder = new StringBuilder();
List<int> numbers = new List<int>() {1,2,3,4,5,6,7,8,9 };
for (int i = 0; i <3; i++)
{
int index = i * 3;
stringBuilder.AppendFormat("{0}{1}{2}", numbers[index], numbers[index + 1], numbers[index + 2]);
stringBuilder.AppendLine();
}
Console.Write(stringBuilder.ToString());
Console.ReadLine();
}
}
Is that what you meant?
string output = string.Empty;
List<int> myList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int counter = 0;
foreach (int value in myList)
{
output += value.ToString();
counter++;
if (counter % 3 == 0)
{
Console.WriteLine(output);
output = string.Empty;
}
}
How do I get all alpha-number combo's in a given alpha-number combo range using c#?
For getting all numbers in a range I'll do something like below
int x = 10;
int y = 15;
int z=y-x+1;
var range =Enumerable.Range(x,z);
foreach (var element in range)
{
Console.WriteLine(element.ToString()+"-->"+x.ToString()+"-"+y.ToString());
}
Console.ReadLine();
But when the value of x is like 1x and y is like 2b how do I get the range of strings like below?
1x
1y
1z
2a
2b
First, parse the string to get the numerical value and the character. Then, loop for each number from the start to the end. Inside, loop for each character in the alphabet from the start to the current end.
Here you go:
string x = "1x";
string y = "2b";
char startCharacter = x.Substring(x.Length-1)[0];
char endCharacter = y.Substring(y.Length-1)[0];
int startNumber = int.Parse(x.Substring(0, x.Length - 1));
int endNumber = int.Parse(y.Substring(0, y.Length - 1));
var range = new List<string>();
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i = startNumber; i <= endNumber; ++i) {
int currentCharEnd = (i == endNumber) ? alphabet.IndexOf(endCharacter) : alphabet.Length - 1;
for(int j = alphabet.IndexOf(startCharacter); j <= currentCharEnd; ++j) {
range.Add(i.ToString() + alphabet[j]);
}
startCharacter = 'a';
}
// range is now { "1x", "1y", "1z", "2a", "2b" }
You can start by doing this, and extend it to achieve your task fully.
string[] abc = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
string x = "1g";
string y = "2b";
string strx = Regex.Match(x, #"\d+").Value;
string stra = Regex.Match(x, #"[a-z]+").Value;
int intx = Int32.Parse(strx);
string stry = Regex.Match(y, #"\d+").Value;
string strb = Regex.Match(x, #"[a-z]+").Value;
int inty = Int32.Parse(stry);
Console.WriteLine(strx);
Console.WriteLine(stra);
Console.WriteLine("----");
int len = inty - intx + 1;
List<string> xycombinations = new List<string>();
string[] ycombinations = new string[] { };
if (len >= 0)
{
int starting = 0;
while (abc[starting] != stra)
{
starting = starting + 1;
}
while (starting < abc.Length)
{
xycombinations.Add(intx.ToString() + abc[starting]);
starting = starting + 1;
}
for (int i = 0; i < xycombinations.Count; i++)
{
Console.WriteLine(xycombinations[i]);
}
}
Console.ReadLine();
It only makes the combination of string x till the end, for instance string x is "1g", so this code makes combinations 1g, 1h, 1i, ij. Similarly you can make combinations of string y by extending. Hope it helps you.
I'm using C# and Microsoft Visual Studio. I'm able to display my array through this code:
private void btnDisplay_Click(object sender, EventArgs e)
{
double[,] initialArray = new double[3, 4] { { 5, 1, 9, 3 }, { 7, 8, 6, 4 }, { 2, 4, 9, 5 } };
string rowOfInts = "";
string columnsAndRow = "";
for (int r = 0; r < initialArray.GetLength(0); r++)
{
string tempString = "";
for (int c = 0; c < initialArray.GetLength(1); c++)
{
rowOfInts = tempString + " " + initialArray[r, c];
tempString = rowOfInts;
}
columnsAndRow = columnsAndRow + rowOfInts + "\n";
lblDisplay.Text = Convert.ToString(columnsAndRow);
}
// displays Display = new displays(initialArray, rowOfInts, columnsAndRow);
if (chkRowTotals.Checked == true)
{
for (int r = 0; r < initialArray.GetLength(0); r++)
{
int intTotal = 0;
string tempString = "";
for (int c = 0; c <initialArray.GetLength(1); c++)
{
rowOfInts = tempString + " " + initialArray[r, c];
tempString = rowOfInts;
}
columnsAndRow = columnsAndRow + rowOfInts;
intTotal += Convert.ToInt32(columnsAndRow);
lblDisplay.Text = Convert.ToString(intTotal);
}
}
}
but I don't know how to add the numbers by rows. Is there any way that I can total the numbers in my array by row and then display them in my label (lblDisplay)?
edit: I don't want the entire array added up- just the rows. So, the output would be 18, 25, and 20.
There are many things wrong in your code, to be completely honest. I will just put what I think is the solution you are looking for:
private void Button_Click(object sender, RoutedEventArgs e)
{
double[,] initialArray = new double[3, 4] { { 5, 1, 9, 3 }, { 7, 8, 6, 4 }, { 2, 4, 9, 5 } };
string rowOfInts = "";
string columnsAndRow = "";
for (int r = 0; r < initialArray.GetLength(0); r++)
{
string tempString = "";
double inttotal = 0;
for (int c = 0; c < initialArray.GetLength(1); c++)
{
rowOfInts = tempString + " " + initialArray[r, c];
tempString = rowOfInts;
inttotal += initialArray[r, c];
}
columnsAndRow = columnsAndRow + rowOfInts + " row total of = " + inttotal.ToString() + "\n";
}
txtbx.Text = Convert.ToString(columnsAndRow);
}
Something to the effect of:
const int numRows = 3;
const int numColumns = 4;
double[,] initialArray = new double[numRows, numColumns] { { 5, 1, 9, 3 }, { 7, 8, 6, 4 }, { 2, 4, 9, 5 } };
double[] rowTotal = new double[numRows];
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numColumns; j++)
{
rowTotal[i] += initialArray[i, j];
}
Console.WriteLine("Current row total: {0}", rowTotal[i]);
}
Try this:
var initialArray = new double[3, 4] { { 5, 1, 9, 3 }, { 7, 8, 6, 4 }, { 2, 4, 9, 5 } };
// List that will hold the sum of each row
List<double> rowSums = new List<double>();
for (int i = 0; i < initialArray.GetLength(0); i++)
{
// accumulator
double rowSum = 0;
for (int j = 0; j < initialArray.GetLength(1); j++)
{
rowSum += initialArray[i, j];
}
// add the row sum to our list
rowSums.Add(rowSum);
}
// will put "18, 25, 20" in your label's Text
lblDisplay.Text = string.Join(", ", rowSums);
You should consider using a flattening your array as it has better performance.
You can use the following Linq:
var numberOfRows = initialArray.GetLength(0);
var numberOfColumns = initialArray.GetLength(1);
var sumOfRows = Enumerable
.Range(0, numberOfRows)
.Select(r => Enumerable.Range(0, numberOfColumns).
Aggregate(0d, (a, i) => a += initialArray[r, i]));
lblDisplay.Text = string.Join(", ", sumOfRows);
However, it might be a lot easier to use a Jagged array instead. The Linq expression would be a lot easier.
I have 2 dynamic textboxes which stores users input in the form of an array Int32[] iA1 = new Int32[3];
and also have a combo box, which has mathematical operator.
My question is how to get the following output when user fills the number of rows and column dynamically at run time and make an appropriate selection from the combo box.
Thanks in advanceenter image description here
string output = "";
Int32[] array = new Int32[3] { 25, 4, 1 };
int rows = array[0];
int cols = array[1];
int op = array[2];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int value = 0;
string opStr = "";
if (op == 1) // +
{
opStr = "+";
value = r + c;
}
else if (op == 2) // -
{
opStr = "-";
value = r - c;
}
else if (op == 3) // *
{
opStr = "*";
value = r * c;
}
// ...
output += string.Format("{0} {1} {2} = {3}\t", r, opStr, c, value);
}
output += System.Environment.NewLine;
}
System.Console.Write(output);
System.Diagnostics.Debug.Write(output);
textarea.Text = output;
Here is a small console app which does what you want:
class Program
{
static void Main(string[] args)
{
var firstNumber = 24;
var secondNumber = 4;
var op = "+";
var result = new List<List<string>>();
for (int i = 0; i <= firstNumber; i++)
{
var list = new List<string>();
for (int j = 0; j < secondNumber; j++)
{
list.Add(i.ToString());
list.Add(op);
list.Add(j.ToString());
list.Add("=");
list.Add((i + j).ToString());
}
result.Add(list);
}
foreach (var item in result)
{
Console.WriteLine(string.Join(" ", item));
}
Console.ReadLine();
}
}
You need to take the numbers and the operator from your textboxes.