One approach is to read all the lines and store them into a list. You know the size of the list. You pick randomly one and remove it from the list. Rinse and repeat.
The other option is to check probability as you read each line. Keep only positive results. But then you have them in the order that they appear in file.
One approach is to read all the lines and store them into a list. You know the size of the list. You pick randomly one and remove it from the list. Rinse and repeat.
That is probably the easiest way to go about solving this particular problem.
you could also store the information in a random access file, and call the information randomly from the file.
If you have access to a random-access file, you can just fseek() to any random location in the file. Read a line and throw it away. Read the next line and keep that.
Extra credit: Explain why the first line is tossed.
Actually, I'm doing this in 'C', so i couldnt be able to take line to line reading from a file (If there is a way please tell me). When I use fseek()
I would get some random char s not particular line.
I tried to do it, but I'm having problem in deleting a line.
I created a copy of original file and then I tried to delete a line after displaying it so it isn't displayed again. I used rand function to select line.
#include <iostream>
#include <fstream>
usingnamespace std;
int main(){
ofstream os("test.txt");
os << "1. Hi." << endl <<"2. By mom!" << endl << endl << "3. YES I did it." << endl << "4. I'm fine." << endl << "5. I'm writing different lines to the file, OK?";
os.close();
//making a copy of whatever has been written in test.txt
char line[100]; //assuming a line wouldn't exceed more than 100 characters.
while (!EOF){
ifstream is("test.txt");
is.getline(line,100,'\n');
is.close();
os.open("copy_of_test.txt", ios::out);
os << line << endl;
os.close();
}//Copy of test.txt has been created.
ifstream is("copy_of_test.txt");
while (is.tellg() != 0){ //loop continues untill everything from copy_of_text.txt has been removed. ***THIS LINE GIVES ERROR***
seekg(0,ios::end);
int sizeOfFile = tellg();
while ( seekg(rand()%sizeOfFile) != '\n' );
seeg(1,ios::current);
is.getline(line,100,'\n');
cout << line << endl;
//deleting that line.
is.close(); //AND I DON't KNOW HOW TO DELETE THE LINE WHICH HAS BEEN Displayed once.
}
return 0;
}
@Rehan: Your C++ code does not help the OP, who uses C.
There is no need to remove lines from a file. Just keep a list of lines that you have already used and somehow exploit of that info during the selection process.
For example, file has 10 lines. You have already used 2 and 5. Now your [0..7] roll returns 5. It is >= 2, so ++. It is >= 5, so ++. Take the original 7.