This question already has answers here:
Dynamic array in C#
(9 answers)
Closed 7 years ago.
static void Main(string[] args)
{
int numberOfTheWords = 1;
string[] words = new string[numberOfTheWords];
Console.WriteLine("You can exit from program by writing EXIT ");
Console.WriteLine("Enter the word: ");
for(int i = 0; i < numberOfTheWords; i++)
{
words[i] = Console.ReadLine();
if (words[i] == "EXIT")
break;
else
numberOfTheWords++;
}
}
Guys I am trying to expand the lengt of the array but "numberOfTheWords" variable is in the "for loop' scope" so it does not effect the global "numberOfTheWord" variable and i cannot expand the array length. What I am trying to achieve is to make dynamic array. I do not want to declare the length of the array. When the user input a word, the length of the array will be increased automatically. Can you help me about how to do this?
This can be easily done with a List.
Example:
List<string> words = new List<string>();
...
words.Add(Console.ReadLine());
Lists are dynamically expanding and you don't have to manage the size of the list on your own. The .NET Framework does that for you. You can also insert an item anywhere in the middle or delete one from any index.
You just need to use List:
var words = new List<string>();
An array does not dynamically resize. A List does. With it, we do not need to manage the size on our own. This type is ideal for linear collections not accessed by keys.
Related
This question already has answers here:
Variables in a loop
(9 answers)
Loop through object variables with different number on the name [duplicate]
(5 answers)
Iteration with variable name [duplicate]
(1 answer)
Closed 2 years ago.
I am trying to use a for loop to iterate through a series of variable names each ending in a number from 1 to 10. I have seen a few other answers to this question but have been unable to make any work for my specific situation. My code is as follows:
string cat2Pos0 = cat2[0];
int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count();
List<int> indexOfPos0 = new List<int>();
bool check = cat2.Contains(cat2Pos0);
int index = 0;
if (check == true)
{
for (int i = 0; i < numOfPos0; i++)
{
index = cat2.FindIndex(x => x == cat2Pos0);
indexOfPos0.Add(cat2.IndexOf(cat2Pos0));
}
}
else if (cat2Pos0 == "-")
{
numOfPos0 = 17;
}
I need to loop through 10 variables names cat1 - cat10. In the code: whenever there is the phrase "cat" I need to be able to adjust it depending on a for loop e.g. cat1 or cat5:
string cat3pos0 = cat3[0];
or:
index = cat3.FindIndex(x => x == cat3Pos0);
Unfortuantely, I am unable to simply write out each variation individually as that would use up almost 3700 lines of code and I was hoping that there would be a better way of achieveing this.
Many thanks, all help is greatly appreciated,
Josh
See here how to use reflection for this. (something like this.GetType().GetField("cat" + i.ToString());.)
But I would really suggest changing your variables to one array of 10 variables. So cat will be an array of arrays (since your cat's seem to be arrays).
This question already has answers here:
How to get first N elements of a list in C#?
(7 answers)
How do I clone a range of array elements to a new array?
(26 answers)
Closed 5 years ago.
I'm training C# on a simple card game. I have methods that shuffle and deals the cards. I have a random deck that is well generated.
Is it possible to set an array for the player1 cards, picking up the first ten values of the array.
Here is a part of my code :
currentCard = 0;
public Card DealCard()
{
if (currentCard < deck.Length)
return deck[currentCard++];
else
return null;
}
I want to pick up for example ten first values of
deck[currentCard++]
Any suggestions will be appreciated, thanks for your help !
You mean you want to pull the first 10 enties into another array? Something like;
var player1Cards = deck.Take(10);
or
List<int> player1Cards = new List<int>();
for (int i = 0; i < 10; i++){
player1Cards.Add(deck[i]);
}
I'm new to programming and I have decided to give myself a challenge by creating a random word generator based on user input.
I'm trying to put the user's words inside of an array and then display a random word from the the array. When I run the program I am able to enter up to four words and then I receive an error: "Array index is out of range."
Is there a limit to how many times I can resize an array?
using System;
namespace RandomWordGenerator
{
class MainClass
{
public static void Main (string[] args)
{
Random r = new Random ();
string[] words = new string[1];
Console.WriteLine ("Enter words for the random word generator. ");
int a = 0;
while(!(Console.ReadLine().Equals("END"))){
words[a] = Console.ReadLine();
a++;
Array.Resize(ref words, a);
}
Console.WriteLine ();
Console.WriteLine (words[r.Next (a)]);
}
}
}
Arrays in c# are immutable, which is to say they cannot be changed after creating them.
What you want is a List<string>, which can be resized at will.
class MainClass
{
public static void Main (string[] args)
{
Random r = new Random ();
List<string> words = new List<string>();
Console.WriteLine ("Enter words for the random word generator. ");
int a = 0;
while(!(Console.ReadLine().Equals("END"))){
words.Add(Console.ReadLine());
}
Console.WriteLine ();
Console.WriteLine (words[r.Next(words.Count)]);
}
}
Array.Resize is actually not named very well, since it does something different than actual resizing. From the MSDN documents:
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
The List<> class is designed for a dynamically sized collection, and in many cases is a better choice than a raw array.
The reason you're seeing an IndexOutOfRangeException is because you're trying to access an array with an index outside of its current range:
int a = 0;
while(!(Console.ReadLine().Equals("END")))
{
words[a] = Console.ReadLine();
a++;
Array.Resize(ref words, a);
}
After the first iteration, you're trying to access words[a] where a = 1, but the array index is zero based, hence you're trying to access words[1] where the array only has 1 element located at the words[0] index, because you allocated a new array with Array.Resize, passing a (1) as its size. That is why you're seeing the exception.
A problem to your solution is as #rossipedia stated. Simply use a List<T>.
The suggestions about using List are all good and valid, but direct answer to your specific question is following -
Array.Resize(ref words, a);
should be changed to -
Array.Resize(ref words, a + 1);
Reason - You start with a=0;, set words[0] to value read, set a=1, and then ask runtime to resize your array from size 1 to 1.. rest follows.
This question already has answers here:
Randomize a List<T>
(28 answers)
Closed 8 years ago.
Say i have a text box with the following content:
Word
Entry
List
Sentry
Each on their own line. How can i randomize them, to appear something like this(on button click):
Entry
List
Sentry
Word
Or any random combination. Now note, i have something like 100,000 separate lines for some of the files i import. I need the to be randomized on button click. Thanks!
What im going to do is have 2 multi-line text boxes next to each other, the user can randomize each list, then a separate button will combine both lists into one file, delimited by a colon(:). Thanks a ton!
Instead of "Randomize", think "Shuffle":
void Shuffle<T>(IList<T> items)
{
// creating a new object here for demo purposes
// Really, the same object should be re-used across method calls
var random = new Random();
for (int i = items.Count; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
T tmp = items[j];
items[j] = items[i - 1];
items[i - 1] = tmp;
}
}
The Windows Forms textbox has a helpful Lines property to make this easy to use:
string[] lines = MyTextBox.Lines;
Shuffle(lines);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to resize multidimensional (2D) array in C#?
I have 2D array : myarray[5,6];
And my array is already full. But still, i want to add some more elements in it.
So , how to extend the size of an array?
OR
how to declare dynamic 2D array? (Sorry for asking silly question :P)
What you want is a List of Lists.
List<List<int>> data = new List<List<int>>();
for(int i = 0; i < rowsToAdd; i++)
{
List<int> newRow = new List<int>();
for(int j = 0; j < columnsToAdd; j++)
{
newRow.Add(j);
}
data.Add(newRow);
}
Then to add a new row:
List<int> nextRow = new List<int>(){0,1,2,3};
data.Add(nextRow);
You can use Array.Resize():
var arr = new int[10];
Array.Resize(ref arr, arr.Length * 2); // doubles the array size
Update
Sorry, I just missed 2D:
Take a look at this question.
I fear you are asking for the solution of the wrong problem.
You should not (in most cases) resize your array by hand. Use and generic list (or a generic list of generic lists) as already suggested here
Please, read this rant: Arrays considered somewhat harmful
Consider using generic lists as already suggested by others.
You have to create a new array if you need to extend the size. If you look at the right side, you can see an answer.