I have a set of thirty numbers in a DB which are all in one cell, separated by spaces. I am evaluating them as such:
<%# Eval("winning_numbers").ToString().Split(' ')[0]%>
<%# Eval("winning_numbers").ToString().Split(' ')[1]%>
<%# Eval("winning_numbers").ToString().Split(' ')[2]%>
And so forth, up to thirty (29). This displays them all in a row. The numbers are random up to 75, like in a bingo game. What I would like to be able to do is to display them in a table, where if the number is between 01 and 15, it displays in the first row, 16-30 = second row, and so forth. Where I'm stuck mentally is that there aren't a finite amount of numbers in each tier - it is totally random. How can I do what I'm looking for?
You are looking for two-dimensional arrays, check this out:
Multidimensional Arrays (C# Programming Guide) # MSDN
If you have all of them items inside of a list then you can iterate through the list using a for loop
for(int I = 0; I < numlist.Count; I++)
{
//Inside the for loop we can check the number, and see what column it will fit into.
if(1 <= I <= 15)
{
//The code to put the item into the respective list.
}
if(16 <= I <= 30)
{
//The code to put the item into the respective list.
}
etc...
}
Related
I'm trying to make a program that reads a file with 50 random words, it stores the words with 3 letters or less in a list called SmallWords and the words with 4 letters or more in a list called LargeWords. I'm using Windows Forms and I have a ListView control with 2 columns... 'Small Words' and 'Large Words'. It seems obvious that what I want to do is just put the words in its corresponding column. The thing is that the file doesn't have like 25 small and 25 large words, you know? Maybe it has 30 small words and 20 large words, so when I do this loop to add items to the ListView, it throws this exception:
ArgumentOutOfRangeException.
This is my code
var MaxNum = Math.Max(SmallWords.Count, LargeWords.Count);
for (var index = 0; index < MaxNum; index++)
{
ListViewItem item = new ListViewItem(SmallWords[index]);
item.SubItems.Add(LargeWords[index]);
listView1.Items.Add(item);
}
The exception is thrown at this line item.SubItems.Add(LargeWords[index]);
Is there a way to handle this? Or like another way to add the items to the columns? I know it works because if change Math.Max(...); to Math.Min(...) it adds the words but just the 20 large words and 20 small words, I'm going to be missing 10 small words in the SmallWords column.
Thanks
You have two arrays with different lengths and try to loop through and access up the the max of both arrays. That's never going to work. Once you hit the limit of the smaller array, you'll get the out of range exception.
Two options to fix depend on what you want to do. You can loop through to the max of the smaller array, or you can skip the part that deals with the smaller array once you hit its max.
var MaxNum = Math.Min(SmallWords.Count, LargeWords.Count);
// ^--- Changed Max to Min
for (var index = 0; index < MaxNum; index++)
{
ListViewItem item = new ListViewItem(SmallWords[index]);
item.SubItems.Add(LargeWords[index]);
listView1.Items.Add(item);
}
I think you should look at this problem in a different way. Basically you are adding a large word at i index to a small word at the same index. Which means that you have to have a SmallWord to add a LargeWord as a subitem. Forget finding the min or max, just loop through the count of SmallWords and only add the LargeWords if the index is in range:
for (var index = 0; index < SmallWords.Length; index++)
{
ListViewItem item = new ListViewItem(SmallWords[index]);
if(index < LargeWords.Length)
{
item.SubItems.Add(LargeWords[index]);
}
listView1.Items.Add(item);
}
This question already has answers here:
Sorting an array related to another array
(4 answers)
Sorting two arrays (values,keys), then sorting the keys
(5 answers)
Closed 5 years ago.
This is my first post on stackoverflow, so forgive any formatting mistakes.
I have a project named BOGOTotal - basically, its job is to take a decimal array of prices, sort them in ascending order, and then determine which prices will be bought and which prices will be free. Anyways, that's just a bit of backstory, but I need something more specific.
I've got two arrays - one of the prices, and one of the quantities of those prices. For example, in my Items array (should have been named "prices"), Items[0] is set to 2.20m, and my Quantities array, Quantites[0] is set to 5. Meaning I have five of the same item that are priced at $2.20.
//create items array
decimal[] Items = new decimal[5];
Items[0] = 2.20m;
Items[1] = 1.50m;
Items[2] = 8.40m;
Items[3] = 4.60m;
Items[4] = 3.75m;
//create quantity array
int[] Quantity = new int[Items.Length];
Quantity[0] = 5;
Quantity[1] = 2;
Quantity[2] = 1;
Quantity[3] = 3;
Quantity[4] = 6;
I then had to sort the Items array in ascending order.
Array.Sort(Items);
However, when I sorted my Items array, the relation of each item to its quantity is now lost, because Items[0] and Quantity[0] no longer are related. Now, instead of Items[0] = 2.20m, it has become Items[0] = 1.50m. Now, I have 5 items that are $1.50 instead of $2.20.
Here's where I had my idea - I would go ahead and calculate the prices of the old arrays by creating a firstPrices array, putting them in a for loop, and saying
decimal[] firstPrices = new decimal[Items.Length];
//calculate prices before sorting - will match back up afterward
for (int i = 0; i < Items.Length; i++)
{
firstPrices[i] = Items[i] * Convert.ToDecimal(Quantity[i]);
}
Here comes the hard part: I'm trying to re-align (for lack of a better word) each quantity to its Item - meaning I'm trying to make the item that is $2.20 match back up with its correct quantity (being 5). However, I'm having a hard time doing this. I tried a nested for loop within another for loop that tested each quantity by multiplying it by the current Item and then comparing it to that spot in firstPrices:
//i would be newItems
//j would be quantity
for (int i = 0; i < Items.Length; i++)
{
for (int j = 0; j < Items.Length; j++)
{
if (Items[i] * Quantity[j] == firstPrices[i])
{
Quantity[i] = Quantity[j];
break;
}
}
}
When it found a match, I set it to break out of the nested loop and increment "i", which goes to the next item in the Items array. Is there something I'm doing wrong here?
You got two seperate arrays that are related, wich is not a good thing. Make a Struct, Class or Tupel containing both values. Optionally also a custom comparer. Make a array of that type.
Then it would be as simple as calling Array.Sort().
In caess where there is no single order (sometimes you want to sort by prices times quantity. Sometimes single item price), Array.Sort() has overrides that allow you to specify the comparer to be used.
You could also go for Linq, if you have experience with it. But getting both values into one type is a requirement. And the perfect time to learn that.
I have a string that contains: "# of rows, # of columns, Row'X'Col'X'=Serial#, ...
How do I create a DataGrid table with the number of rows and columns defined, and then place the serial #s into the grid.
Examples:
2,1,R1C1=111,R2C1=112,
2,2,R1C1=211,R1C2=212,R2C1=213,R2C2=214,
thanks
Below is code that does what you are asking; however I must point out some problems with this approach. First, getting the total rows and cols from the first two elements in order to create your table is risky. If that data is wrong, this code will most likely crash or possibly omit data. Example if the input is: 2,2,RXCX=.., RXCX=.., RXCX=.., RXCX=..,RXCX=, RXCX=… This line will only get the first 4 values.
Worse… this will crash… if the input is 2,2,RXCX=.., RXCX=.. Then it will crash when you try to access the 4th element in the splitArray because there isn’t a 4th element. Either way is not good.
My point is to be safe… it would be a better approach to see how much data is actually there before you create the grid. You could get how many items there are with StringArray.Length minus the first two elements. These elements will define the dimensions and allow you to check their validity. This will make sure your loops won’t go out of bounds because the supplied data was wrong. It seems redundant and error prone to supply the dimension values when you can get that info from the data itself.
I still am not 100% sure what you want to accomplish here. It looks like a search of some form. This is what I am picturing…
Looking at your (previous) screen shots it appears to me that after you type into the Serial # text box and click the “Search Txt Files” button it will search for data that came from the input string i.e. “PLX51…” and then have the grid display the “filtered” results that match (or are LIKE) what’s in the Serial # textbox. If this is true, I would ignore the RXCX vales and put the data in a single column. Then wire up an OnKeyPress event for the text box to filter the grid whenever the user types into the Serial # text box.
Otherwise I am lost as to why you would need to create the data in the fashion described. Just because the input has unnecessary data… doesn’t mean you have to use it. Just a thought.
string inputString = "2,2,R1C1=211,R1C2=212,R2C1=213,R2C2=214";
string[] splitArray = inputString.Split(',');
int totalRows = int.Parse(splitArray[0]);
int totalCols = int.Parse(splitArray[1]);
int itemIndex = 2;
// add the columns
for (int i = 0; i < totalCols; i++)
{
dataGridView1.Columns.Add("Col", "Col");
}
// add the rows
dataGridView1.Rows.Add(totalRows);
for (int i = 0; i < totalRows; i++)
{
for (int j = 0; j < totalCols; j++)
{
dataGridView1.Rows[i].Cells[j].Value = splitArray[itemIndex];
itemIndex++;
}
}
I am facing a very difficult situation, suppose I have a array of dynamic numbers. The condition is the array may contain 10 numbers to 20 numbers. It can contain 10, 12, 14, ... to 20 integers. Now based on the ArrayList.Count(), I am going to choose 3(if array contains 10 integers) to 6 (if array contain 20 integers) numbers out of this array, and add those numbers. say that number is "X".
Now I have to check if there exist any three integers in the list whose sum is equal to X, if its equal, then again I have to repeat the same procedure until I find a unique sum from the list.
So how can I do it? The best part is all the numbers in the array is unique, there is no repeat of the numbers in the array.
First Idea
I though of one idea, for 3 numbers, Suppose I generate a unique number.
foreach (var i in List) // values of i = 1, 5, 8 (Assume)
{
sum += listOfUniqueIntegers[i];
}
// Fix the first element as List[i]
for (int i = 0; i < List.Count()-2; i++)
{
// Fix the second element as List[j]
for (int j = i+1; j < List.Count()-1; j++)
{
// Now look for the third number
for (int k = j+1; k < List.Count(); k++)
{
if (List[i] + List[j] + List[k] == sum)
{
// Here I will again create one more unique value
// and assign it to sum and repeat i = 0, j = 0, k = 0;
}
}
}
}
But the problem with this approach is its time complexity os n^3 so if I have to generate a sum from 6 numbers when List size is 20, it will be n^6, which is not expected.
Second idea
I though I can sort the List, but then what logic shall I use to choose 3 integers so that it's sum is unique in the List.
Lets say I sort the list and choose three smallest number or choose from the sorted list 3rd 3+1=4 th and 3+2=5th element, and sum=List[3]+List[4]+List[5];
this is also not expected, any pattern to choose three numbers is not suggested. It should be randomly chosen and the sum should be unique.
So I am not getting any idea to generate a optimal solution for this.
Can anybody please help me.
Just use the 3 largest numbers.
i am developing a mine sweeper game in c# of dimension (8 x 8).The difficulty levels increase/decrease the number of mines on the grid.
I use a random class (with min,max set;) to generate a random cell number.The problem i am facing is ,the random object keeps repeating the same number.I tried to resolve this issue by maintaining a local list where i store the generated unique random numbers.The next time i call Next(), i would check it against the local list ,to see if its already present.If the number is already present i would keep calling Next() until i get a new number which is unique and not present in the list.But this doesnt look in itself a good solution as sometimes it takes painful amount of time to generate a new list.
Any suggestions on this please
Even if you use the same random number generator, repeating values are possible.
One way to avoid this would be to generate a list of possible values and using the random number generated to access a value in this list (using as indice) and reducing this list, as you find places to put mines to.
For 8 X 8 example, you have 64 possible places
List<int> possibleValues = new List<int>();
for (int i = 0; i < 64; i++)
{
possibleValues[i] = i;
}
List<int> result = new List<int>();
Random r = new Random();
int numberOfMines = 50; //say you want to put 50 mines there
for (int i = 0; i < numberOfMines; i++)
{
int indice = r.Next(possibleValues.Count);
int value = possibleValues[indice];
possibleValues.Remove(value);
result.Add(value);
}
It looks like you want a shuffle based on a fixed number of cells (8,8), e.g. a Fisher-Yates shuffle. This would guarantee that any coordinate only appears exactly once (as opposed to repeatedly using Random.Next() where you can draw the same number many times), and the order of appearance of coordinates is randomized.
Initialize an array that contains all the coordinates of your cells, shuffle the array and maintain an index of the next "random" cell, return the cell at the offset of the index and increase the index.
First calculate the number of mines, and empty fields.
Random rand=new Random();
int mines=GetMinesFromDifficulty(...);
int empty=TotalFields-mines;
Then for each field:
for(int y=0;y<height;y++)
for(int x=0;y<height;y++)
{
if(random.Next(mines+empty) < mines))
{
field[x,y]=Mine;
mines--;
}
else
{
field[x,y]=Empty;
empty--;
}
}
Instead of picking slots where the mines should be, loop through the slots and calculate the probability that there should be a mine there. The implementation for this becomes very simple, as you just need a single loop:
bool[] mines = new bool[64];
int cnt = 12;
Random rnd = new Random();
for (int i = 0; i < mines.Length; i++) {
if (rnd.Next(mines.Length - i) < cnt) {
mines[i] = true;
cnt--;
}
}
(Room for improvement: You can exit out of the loop when cnt reaches zero, if you don't need to initialise all slots.)
If your grid is 8x8, and you want to randomly choose an unused cell instead of pulling random numbers until you hit an unused one, then keep track of the number of unused cells. Say 8 have been used, leaving 55 unused. Then generate a random number between 0 and 54. You would then have to count through, and find the nth empty cell.
It would probably be easier to think of the problem in a more linear way. Instead of say a 2D array... Squares[8][8] think of it as a single dimension array Squares[64].
At this point you generate a number between 0-63 for your random mine placement. If say the value is 10 you could store for later to offset subsequent numbers. You can reduce your range now from 0-62, if you pulled out the value 16 you would want to add +1 for each value you'd already pulled out underneath it (so actually use 17 in this case, but square 10 has been excluded from our set).
Without seeing any code it's kind of hard to get the gist of things, but from what I can tell you have the following:
A multi-dimensional array [8][8] for the grid layout of the game, you're now trying to randomly place mines?
You'll need to keep one instance of Random for generating the numbers, else you will get the same number over and over again. Something like this
private readonly Random randomNumber = new Random();
for(int i = 0; i < 10; i++)
{
Console.WriteLine(this.randomNumber.Next(1, 10));
}
This will then generate 10 random numbers, each one different.