I am attempting to read (n) amount of random lines from a text file with about 200 entries (lines) and populate a listbox called "recSongs". I have provided some simple code which retrieves one random line from the text file, but I want retrieve n amount.
Here is my code.
var lines = File.ReadAllLines(#"file.txt");
var r = new Random();
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];
recSongs.Items.Add(line);
How about:
var lines = File.ReadAllLines("file.txt").OrderBy(x => Guid.NewGuid()).Take(n);
n will be the input , i.e no of lines you need
List <string> text = File.ReadLines("file.txt").Take(n).ToList();
Edit
If you need random lines, you could do,
string[] lines = File.ReadAllLines(#"C:\YourFile.txt");
List<string> source = new List<string>();
int n = 10;
for (int i = 0; i < n; i++)
{
source.Add(lines[new Random().Next(lines.Length)]);
}
var lines = File.ReadAllLines(#"file.txt");
var r = new Random();
var randomized = lines.OrderBy(item => r.Next()); //randomize the list
recSongs.Items.AddRange(randomized.Take(N).ToArray()); //Add N amount to listbox
This solution also avoids duplicate randoms
Probably the easiest way, though not the most memory-efficient, is to slurp the file into an in-memory collection of its lines, then Shuffle() the lines and take however many you want:
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> input)
{
var buffer = input.ToArray();
//Math.Random is OK for "everyday" randomness;
//use RNGCryptoServiceProvider if you need
//cryptographically-strong randomness
var rand = new Random();
//As the loop proceeds, the element to output will be randomly chosen
//from the elements at index i or above, which will then be swapped
//with i to get it out of the way; the yield return gives us each
//shuffled value as it is chosen, and allows the shuffling to be lazy.
for (int i = 0; i < buffer.Length; i++)
{
int j = rand.Next(i, buffer.Length);
yield return buffer[j];
//if we cared about the elements in the buffer this would be a swap,
//but we don't, so...
buffer[j] = buffer[i];
}
}
...
string[] fileLines = GetLinesFromFile(fileName); //a StreamReader makes this pretty easy
var randomLines = fileLines.Shuffle().Take(n);
Some notes:
This should work fairly well for a text file of about 200 lines; beyond a couple hundred thousand lines, you'll start having memory problems. A more scalable solution would be to shuffle an array of line numbers, then use those to seek for and read the specific lines you want, discarding all the others.
This solution produces the random lines in random order. If you want to preserve the order of the lines from the file, do the line-number variant, sorting the line numbers you select, then just keep the lines in that order after reading them out of the file.
Try this
var lines = File.ReadAllLines(#"file.txt");
var r = new Random();
int noLines = 10;// n lines
for (int i = 0; i < noLines; i++)
{
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];
recSongs.Items.Add(line);
}
You could do something like:
HashSet<int> linesHash = new HashSet<int>();
var lines = file.ReadLines();
for (int i = 0; i < numLinesToGet; i++)
{
int line=0;
do
{
line = rand.Next(0, lines.Length);
}while(linesHash.Contains(line));
linesHash.Add(line);
linesAdded.Add(lines[line]);
}
Note that if the amount of lines to get is greater than the actually number of lines my code would never end, so some checks must be done prior to execute the for loop.
This will add numLines random lines to your collection. Note that there is a chance that there will be duplicates.
var lines = File.ReadAllLines(#"file.txt");
var r = new Random();
int numLines = 5;
for (int i = 0; i < numLines; i++)
{
recSongs.Items.Add(lines[r.Next(0, lines.Length - 1)]);
}
To enforce unique items, you could do something like this:
for (int i = 0; i < numLines; i++)
{
var randomItem = string.Empty;
do
{
randomItem = lines[r.Next(0, lines.Length - 1)];
} while (recSongs.Contains(randomItem));
recSongs.Items.Add(randomItem);
}
But now note that it is possible that it will never exit. The joys of Random!
var lines = File.ReadAllLines(#"file.txt");
var random = new Random();
var lines = Enumerable.Repeat( -1, n ) // -1 is a filler and is discarded by the select.
.Select( _ => random.Next(0, lines.Length - 1 ) )
.Select( index => lines[index] );
foreach( var line in lines )
{
recSongs.Items.Add(line);
}
Related
For instance I have an array that gets filled with random numbers and am going to call this one dice.
Random rnd = new Random()
int[] dice=new int [5]
for (int i=0;i<dice.length;i++)
{
dice[i]= rnd.next(1,7)
}
Now for the sake of simplicity I wanna ask how can I find out if got a three of a kind of instance.
use a IDictionary<int,int>
var dict = new Dictionary<int,int>();
foreach (int i in dice)
if(!dict.ContainsKey(i))
dict.Add(i,1);
else dict[i]++;
(optional) you can use Linq to get the numbers that appear multiple times
var duplicates = dict.Where( x=>x.Value > 1 )
.Select(x=>x.Key)
.ToList();
// preparation (basically your code)
var rnd = new Random();
var dice = new int[5];
for (int i=0; i < dice.Length; i++)
{
dice[i]= rnd.Next(1,7);
}
// select dices, grouped by with their count
var groupedByCount = dice.GroupBy(d => d, d => 1 /* each hit counts as 1 */);
// show all dices with their count
foreach (var g in groupedByCount)
Console.WriteLine(g.Key + ": " + g.Count());
// show the dices with 3 or more
foreach (var g in groupedByCount.Where(g => g.Count() >= 3))
Console.WriteLine("3 times or more: " + g.Key);
To give a completely different approach, instead of:
Random rnd = new Random();
int[] dice=new int[5];
for (int i=0;i<dice.length;i++)
{
dice[i]= rnd.next(1,7);
}
Try this:
Random rnd = new Random();
int[] valueCount = new int[6];
for (int i=0; i<5; i++)
{
valueCount[rnd.next(0,6)]++;
}
//you have kept track of each value.
if (valueCount.Any(c => c == 3))
//3 of a kind
Of course you can combine both....
Do note that this works for a really specific rule engine, optimized for counting events.
If you really want a card/dice game, you'll need to rethink the rule engine to coupe with rules like "is it: 1,2,3,4,5,6, and in that order?".
For that, try: How to implement a rule engine?
I feel like this task should not be done this way...
My sequenceY length is not equal to number of steam numbers because you can't assign int[] length with int that have 0 as a starting value.
Therefore my sequenceY have a lot of 0 inside and I can't print the whole sequence. I even tried adding this after for loop:
sequenceY = new int[steamnumbercounter];
But it didn't work ... Why ?
My other question is how do programmers deal with sequences that have unknown length?
I managed to print only steam numbers but the task says print sequenceY not only part of it.
// 4. sequenceX[20] is made of random numbers from 1 to 30 ,
// sequenceY is made of steam numbers from sequenceX. Print sequneceY.
int[] nizx = new int[20];
int[] nizy = new int[20];
int n = 0;
int steamnumbercounter = 0;
Random rnd = new Random();
for (int i = 0; i < nizx.Length; i++)
{
nizx[i] = rnd.Next(1, 30);
if (nizx[i]%2==0)
{
nizy[n] = nizx[i];
n++;
steamnumbercounter++;
}
Console.Write("{0} , ", nizx[i]);
}
for (int i = 0; i < steamnumbercounter; i++)
{
Console.WriteLine("{0} , ",nizy[i]);
}
Partial code review along with an answer.
But it didn't work ... Why ?
That code didn't work because you're reassigning sequenceY to a completely new value.
My other question is how do programmers deal with sequences that have unknown length?
So, with that known we can do a few things here: create an array and use Array.Resize, use a List<T>, fill the initial array then swap it for one of the right size which is filled.
I'm going to assume a "steam" number is an even one.
Your naming is not good: nizx and nizy don't convey the meaning or line up with the problem.
I'm going to demonstrate the last option (since you stated that you don't know how to use many of the moderately complex parts of .NET in this class yet, which is fine): fill the initial array and swap it for a new one. This will run in O(n^2) time (sorta).
So, let's start with our source array.
int[] sequenceX = new int[20];
Next we'll define our destination array to be the same size as our source array. (This is the maximum number of values that could be stored in it, we'll shrink it later.)
int[] sequenceY = new int[sequenceX.Length];
Then we need a variable to hold how many numbers we found that meet our criteria:
int steamNumbers = 0;
And lastly, our Random.
Random random = new Random();
Then, we look through all our sequenceX as you did, but we'll update the logic a bit.
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(1, 30);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
So our code looks almost the same as yours, but we have one more thing to do: since you only want sequenceY to contain steamNumbers we have to shrink it or something.
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
Now sequenceY only has your steam numbers in it.
Final code:
int[] sequenceX = new int[20];
int[] sequenceY = new int[sequenceX.Length];
int steamNumbers = 0;
Random random = new Random();
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(1, 30);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
// Print your `sequenceY` here.
You could extract this to a method pretty easily as well:
public int[] GetSteamNumbers(int sequenceCount, int randomMinimum, int randomMaximum)
{
int[] sequenceX = new int[sequenceCount];
int[] sequenceY = new int[sequenceX.Length];
int steamNumbers = 0;
Random random = new Random();
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(randomMinimum, randomMaximum);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
return sequenceY;
}
And then call it with:
int[] steamNumbers = GetSteamNumbers(20, 1, 30);
Of course, for the more advanced users (this doesn't help you, but it may help others) we can do something as follows using LINQ:
var random = new Random();
var sequenceY = Enumerable.Range(1, 20)
.Select(x => random.Next(1, 30))
.Where(x => x % 2 == 0)
.ToArray();
Which should have the same effect. (Just demonstrating that there are still things in C# to look forward to in the future.)
Disclaimer: I wrote this entire answer outside of the IDE and without actually compiling it, I make no guarantees to the accuracy of the code but the procedure itself should be fairly straight forward.
The thing with arrays in C# is that they are of fixed size.
You'll have to iterate through and re-create it or use a IEnumerable that has dynamic sizes, such as Lists.
Solution here would be to use a List that contains your integers and then you would use nizx.Add(rnd.Next(1, 30));
Elaborating on my comment above: You can create a 'fake' list by concatenating the values you need in a string, separated by commas. The string.Split(',') will give you the resulting array that you need.
Given a string of form "a,b,c,d" string.Split(',') will create the array ["a","b,"c","d"]. The code:
{
int[] nizx = new int[20];
string numberString = string.Empty;
int n = 0;
Random rnd = new Random();
for (int i = 0; i < nizx.Length; i++)
{
nizx[i] = rnd.Next(1, 30);
if (nizx[i] % 2 == 0)
{
numberString += nizx[i] + ",";
n++;
}
}
var numberArray = numberString.Split(',');
for (int i = 0; i < n; i++)
{
Console.WriteLine("{0} , ", numberArray[i]);
}
}
I've been playing around / researching ways to randomize the order of chars in a string. I frankly just don't understand how to do it. I've searched through the C# documentation and a handful of websites. I found one particular way of randomizing the order of chars in a string but I don't understand how it works. I've also read that the Random class isn't truly random, which would explain why the results are so similar.
How exactly does the current method I'm using function (especially the OrderBy() method).
Is there a better way to do this?
Current code
string baseList = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
string[] randLists = new string[baseList.Length];
for (int i = 0; i < baseList.Length; i++)
{
randLists[i] = new string(baseList.ToCharArray().OrderBy(s => (random.Next(2) % 2) == 0).ToArray());
Console.WriteLine(randLists[i]);
}
Console.Read();
This is my attempt at randomizing but it doesn't function at all:
*string bL = "abcdefghijklmnopqrstuvwxyz";
string[] rL = new string[bL.Length];
Random randomizer = new Random();
for (int i = 0; i < bL.Length; i++)
{
rL = new string(bL.ToCharArray().OrderBy(c => (randomizer.Next(0, 25)).ToString()));
}*
Thanks in advance for any assistance. I'll continue researching in the meantime.
Although the code that you found is short, it does not make a nicely distributed shuffle of the original string: the randomizer is likely to give you the same numbers in the process of generating a shuffle, increasing a probability that the corresponding characters would remain in the same order relative to each other as in your original string.
One solution to this problem is using Fisher–Yates shuffle. It is easy to implement (you need to stay away from common implementation errors, though).
Since string is immutable, you would need to shuffle an array of characters, and then make a string from it.
To add to the suggestion of the Fisher-Yates shuffle, here's a code sample, just ignore the test assertion, just trying to debug and make sure it's random enough.
[TestMethod]
public void RandomizeText()
{
string baseList = "abcdefghijklmnopqrstuvwxyz";
char[] result = baseList.ToCharArray();
Shuffle<char>(result);
var final = string.Join("", result);
final.Should().NotMatch(baseList);
}
public void Shuffle<T>(T[] array)
{
var random = new Random();
for (int x = 0; x < 100; x++)
{
for (int i = array.Length; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
T tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
}
}
Another example...
static void Main(string[] args)
{
string baseList = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(baseList);
string shuffled = Shuffle(baseList);
Console.WriteLine(shuffled);
Console.ReadLine();
}
static Random R = new Random();
static string Shuffle(string list)
{
int index;
List<char> chars = new List<char>(list);
StringBuilder sb = new StringBuilder();
while (chars.Count > 0)
{
index = R.Next(chars.Count);
sb.Append(chars[index]);
chars.RemoveAt(index);
}
return sb.ToString();
}
I'm trying to create a method that produces 10 unique random numbers, but the numbers are not unique, I get several duplicates! How can I improve the code to work as I want?
int[] randomNumbers = new int[10];
Random random = new Random();
int index = 0;
do
{
int randomNum = random.Next(0, 10);
if (index == 0)
{
randomNumbers[0] = randomNum;
index++;
}
else
{
for (int i = 0; i < randomNumbers.Length; i++)
{
if (randomNumbers[i] == randomNum)
break;
else
{
randomNumbers[index] = randomNum;
index++;
break;
}
}
}
}
while (index <= 9);
foreach (int num in randomNumbers)
System.Console.Write(num + " ");
EDIT 2: I have corrected all errors now, but this code isn't working becuase the numbers are not unique! I have updated my code above to the latest version. I preciate some help to solve this! Thanks!
The simplest way to have this is to have an array of the numbers you want (i.e. 1-10) and use a random shuffling algorithm.
The Fisher-Yates shuffle is the easiest way to do this.
EDIT:
Here's a link to a C# implementation: http://www.dotnetperls.com/fisher-yates-shuffle
random.next(0, 10) returns a random number between 0 and 10. It can happen, that it returns the same number multiple times in a row and it is not guaranteed, that you get every number between 0 and 10 exactly one time, when you call it 10 times.
What you want is a list of numbers, every number is unique, between 0 and 9 (or 1 and 10). A possible solution to this would be something like this:
//Create the list of numbers you want
var list = new List<int>();
for(var x = 0; x < 10; x++)
{
list.Add(x);
}
var random = new Random();
//Prepare randomized list
var randomizedList = new List<int>();
while(list.Length > 0)
{
//Pick random index in the range of the ordered list
var index = random.Next(0, list.Length);
//Put the number from the random index in the randomized list
randomizedList.Add(list[index]);
//Remove the number from the original list
list.RemoveAt(index);
}
Explained in words, this is what you do:
Create the list with all the numbers, that your final list should contain
Create a second empty list.
Enter a loop. The loop continues, as long as the ordered list still has numbers in it.
Pick a random index between 0 and list.Length
Put this random number in the randomized list
Remove the item at the index position from the ordered list.
Like this you create the set of numbers you want to have in your randomized list and then always pick a random entry from the ordered list. With this technique, you can also achieve, that certain values occur multiple time in the list.
I'm not sure if my code compiles against c#, as I currently do not have visual studio running here, but I think the code should be mostly correct.
Something like this?
const int maxNumbers = 10;
List<int> numbers = new List<int>(maxNumbers);
for (int i = 0; i < maxNumbers; i++)
{
numbers.Add(i);
}
Random r = new Random();
while (numbers.Count > 0)
{
int index = r.Next(numbers.Count);
Console.Write("{0} ", numbers[index]);
numbers.RemoveAt(index);
}
Console.WriteLine();
Edit: For any random numbers:
const int maxNumbers = 10;
const int biggestNumbers = 10000;
List<int> numbers = new List<int>(maxNumbers);
Random r = new Random();
while (numbers.Count < maxNumbers)
{
int index = r.Next(biggestNumbers);
if (numbers.IndexOf(index) < 0)
{
numbers.Add(index);
Console.Write("{0} ", index);
}
}
Console.WriteLine();
I want to generate an array that has 144 number from 1->36 in random order (so each number is repeated 4 times). Can we use Enumerable.Repeat and Enumerable.Range to do that. If yes than please explain to me how?
Well, creating the sequence with all the numbers in is easy:
var items = from x in Enumerable.Range(1, 36)
from y in Enumerable.Repeat(x, 4)
select y;
Then you can just use ToArray to get it into an array and shuffle it. There are numerous questions about shuffling an array in C# on SO, such as this one. You could either use that code directly, or call ToArray and shuffle the array in place without yielding it at the end.
int[] numbers = Enumerable.Range(0, 144).Select(i => (i % 36)+1).OrderBy(g => Guid.NewGuid()).ToArray();
// Generate the list (not in random order)
var one_to_36 = Enumerable.Range(1, 36);
var lst = one_to_36.Concat(one_to_36).Concat(one_to_36).Concat(one_to_36).ToList();
// Randomize the list by swapping random elements
Random rnd = new Random();
for(int i = 0; i < lst.Count; i++)
{
int i1 = rnd.Next(lst.Count);
int i2 = rnd.Next(lst.Count);
int tmp = lst[i1];
lst[i1] = lst[i2];
lst[i2] = tmp;
}
var seq = Enumerable.Range(0, 144);
var all = seq.ToList();
var random = new Random();
var result = seq.Select(i => {
var index = random.Next()%all.Count;
var r = all[index] % 36 + 1; all.RemoveAt(index);
return r;
}).ToList();