C# - Randomizing lines of a text box [duplicate] - c#

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);

Related

resize array in for loop in c# [duplicate]

This question already has answers here:
change array size
(15 answers)
Closed 3 months ago.
I need to run this loop and add the values to the length array each time the loop iterates, so far each time i loop the temp array is cleared so the data is getting lost each iteration. I want to resize the array and add the user input to the length array each iteration.
int[] lengthArray = new int [1];
for (int i = 0; i < lengthArray.Length; i++)
{
lengthArray[i] = int.Parse(Console.ReadLine());
int[] temp = new int [lengthArray.Length + 1] ;
temp[i] = lengthArray[i];
lengthArray = temp;
}
You probably want to store your result in a List<int> instead of an array int[] .
Then you each time you want to add an element in the lengthArray you can just call the Add method.

Iterating through variable names with for loop [duplicate]

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).

How to solve argument out of range exceptions [duplicate]

This question already has answers here:
ArgumentOutOfRangeException on initialized List
(1 answer)
How to initialize a List<T> to a given size (as opposed to capacity)?
(16 answers)
Closed 4 years ago.
So I've been looking around for quite a while to try and find a solution to this.
I've been trying to make a card game and am stuck at a section in which I create a cad along with its properties. i decided to make it in the form of an array. The code looks like:
(not sure what happened with these first ones)
string[] dogs = System.IO.File.ReadAllLines(#"C:\Users\corin\Documents\C# coding\dogs.txt");
int individual = totalCards / 2;
Random r = new Random();
int Cards = totalCards / 2;
List<List<int>> playerCards = new List<List<int>>(Cards);
for (int x = 0; x < (Cards-2); x++)
{
playerCards[0].Add(Int32.Parse(dogs[x]));//Cards
playerCards[1].Add(r.Next(1, 6));//Drool
playerCards[2].Add(r.Next(1, 101));//Exercise
playerCards[3].Add(r.Next(1, 11));//Intelligence
playerCards[4].Add(r.Next(1, 11));//Friendliness
}
No errors are raised before I run the code but when I try it an Argument out of range exception occurs for the line: playerCards[0].Add(Int32.Parse(dogs[x]));
I tried removing it and the same error occured for the next line. I'm not sure what I've done wrong and have tried to find a solution for quite some time. If anyone has any tips or answers that would be great.
Thanks
try this :
string[] dogs = System.IO.File.ReadAllLines(#"C:\Users\corin\Documents\C# coding\dogs.txt");
int individual = totalCards / 2;
Random r = new Random();
int Cards = totalCards / 2;
List<List<int>> playerCards = new List<List<int>>();
//the missing piece
for (int i = 0; i < (Cards ); i++)
{
playerCards.add(new List<int>());
}
for (int x = 0; x < (Cards-2); x++)
{
playerCards[0].Add(Int32.Parse(dogs[x]));//Cards
playerCards[1].Add(r.Next(1, 6));//Drool
playerCards[2].Add(r.Next(1, 101));//Exercise
playerCards[3].Add(r.Next(1, 11));//Intelligence
playerCards[4].Add(r.Next(1, 11));//Friendliness
}
In addition to the previous answers: new List<List<int>>(Cards) doesn't do what you think it does. It sets capacity, not elementCount (or whatever it's called). When bounds are checked, elementCount is used, not capacity. capacity is useful when you have a good idea how many elements you have, to avoid reallocations and don't waste space.
So yes, before accessing by index you should add elements into the list manually.

C# - Field values of an array picking up values of a loop [duplicate]

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]);
}

How to Create a Dynamic Array? [duplicate]

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.

Categories

Resources