Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Created February 25, 2014 23:37
Show Gist options
  • Select an option

  • Save rayjcwu/9220329 to your computer and use it in GitHub Desktop.

Select an option

Save rayjcwu/9220329 to your computer and use it in GitHub Desktop.
public void method1(String filename) {
BufferedReader br = new BufferedReader(new FileReader(filename));
int lineNum = 0;
while (br.readLine() != null) {
lineNum++;
}
br.close();
br = new BufferedReader(new FileReader(filename));
int line = (int)(Math.random() * lineNum);
for (int i = 0; i < lineNum; i++) {
String l = br.readLine();
if (i == line) {
System.out.println(l);
}
}
}
public void method1(String filename) {
BufferedReader br = new BufferedReader(new FileReader(filename));
final double p = 0.5;
double q = p;
String line;
while((line = br.readLine()) != null) {
if (Math.random() < q) {
System.out.println(line);
break;
}
q *= (p / (1 - p));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment