SouvikMaji
SouvikMaji

Reputation: 1145

pick a random line from text file

I have a text file containing some lines of text, separated by commas like this:

"Every strike brings me closer to the next home run. –Babe Ruth",
"It is hard to fail but it is worse never to have tried to succeed.-Theodore Roosevelt",
"People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily. - ZigZiglar"

Now my aim is to read from this file, pick a random line, and print it in the console. New lines may also be added by the user. Now, what are the methods i should use to read from the file and without storing each line in a Array of string(then picking a random line would be easy, but will cost memory), how can i pick a random line, from the text?

Upvotes: 1

Views: 248

Answers (1)

peter.petrov
peter.petrov

Reputation: 39457

If you don't want to keep these sentences in memory, then you have to know at each moment of time the count of all lines in the file - say N. Then do this: generate a random number k such that 1 <= k <= N, open your file, and read line by line until you reach line k. Now read line k and return it to the user. So the answer is: you have to read your file sequentially.

Upvotes: 2

Related Questions