lundi 20 mars 2017

How long does it take to process a big text file?

I have a big text file containing names.

The objective is to generate a random name (two random names from the file).

Considering that the file has about 8k lines, with one name per line, is it efficient processor-wise to try and get a random line from this File? Is it a long process to use, therefore inneficient on runtime?

I plan to use the following method to get the random name

 public static String choose(File f) throws FileNotFoundException
 {
 String result = null;
 Random rand = new Random();
 int n = 0;
 for(Scanner sc = new Scanner(f); sc.hasNext(); )
 {
    ++n;
    String line = sc.nextLine();
    if(rand.nextInt(n) == 0)
       result = line;         
 }

 return result;      
}

A rookie analysis of this code makes me think it runs in about O(n) time

But I'm testing it with a lower number of Strings (original file currently not done yet, around 150 names for test-purposes).

Is this an efficient way to generate the random names?

@Edit

Efficiency is important, considering that I want to generate the name on a low amount of time.




Aucun commentaire:

Enregistrer un commentaire