0

I’m pretty new to c# and recently I’m trying out a random generator using fruits from a text file for example Apples Oranges Pears Kiwis

.. and so on. However I wasn’t able to do it as I didn’t have unixengine installed to run the random.next command. Is there another way where I can draw the input from the text file as an array then use a command to randomise the output without duplicating.

Apparently I can’t run my codes about and I’m at a lost at what to do! Sorry again! I just started c# a few weeks ago! Any help to guide me would help a lot!

Vladel
  • 230
  • 1
  • 4
  • 16
  • Possible duplicate of [Best way to randomize an array with .NET](https://stackoverflow.com/questions/108819/best-way-to-randomize-an-array-with-net) – Cubicle.Jockey Sep 20 '18 at 05:58
  • doesn't even compile.. – jegtugado Sep 20 '18 at 06:14
  • It sounds like you have completely different problems than working out a random number or choosing a random text from a text file. Why don't you start with the problem with "unixengine", what is that? You need the .NET framework or .NET Core installed in order to run .NET code, are you using C# in a non-.NET way? – Lasse V. Karlsen Sep 20 '18 at 07:06

1 Answers1

1

First read the text file as string into a string variable Code below (you need to include system.IO)

string fruits = File.ReadAllText(@"c:\fruits.txt", Encoding.UTF8);

Next Split the Text into an array of stings (assuming the fruits are separated by an space character on the text file)

string[] fruitsArray = fruits.Split(' ');

Next generate a random number from 0 to the number of fruits in Fruit Array -1 (Arrays starts with index 0)

Random rnd = new Random();
int fruitNumber = rnd.Next(0, fruitsArray.Length); // return number between 0 and (Length -1)

Now using this random number pick the fruit at the random position from the fruitsarray,

string output = fruitsArray[fruitNumber];
Erik Šťastný
  • 1,487
  • 1
  • 15
  • 41
Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45
  • 1
    Dont forget to remove it from the array after you have output it. OP has asked to "randomise the output without duplicating" – Daniel Loudon Sep 20 '18 at 07:40
  • Thanks for your input Brother! I tried the code and it totally works! I tried removing the randomised output while Using a for loop from the array but it doesn’t really work out as expected. Sorry to be a trouble but may I ask if you have any suggestions for this? – Joshua tang Sep 20 '18 at 10:23