Java Extract Random Values from Text File
I posted a question earlier regarding how to extract the first eight values from an external text file using Java. The text file con开发者_JAVA技巧tains the first 1000 prime numbers and I have written a method to read the data from said text file.
I would like to know how to extract eight values at random and apply the results to another method.
Something along the lines of:
read data from file;
select eight random numbers from file;
apply random numbers to method;
I am able to extract the first eight numbers (as explained by a number of answers to my previous question), however I am now looking to extract eight random values - how can I do this?
Thank you.
Another way is:
List<Long> numbers = new ArrayList<Long>();
//here you create reader from your file
while ((line = reader.readLine()) != null) {
numbers.add(Long.valueOf(number));
}
Long[] selectedNumbers = new Long[8]();
Random r = new Random();
for(int i = 0; i < selectedNumbers.length; i++){
selectedNumbers[i] = numbers.get(r.nextInt(numbers.Size()));
}
//8 random numbers are in selectedNumbers array
The advantage if this solution is that it is a little more efective then BalusC's answer. You can replace array by List
of course
Collect the numbers.
List<Long> numbers = new ArrayList<Long>();
// ...
while ((line = reader.readLine()) != null) {
numbers.add(Long.valueOf(number));
}
Shuffle the list.
Collections.shuffle(numbers);
Grab the first eight.
List<Long> eightRandomNumbers = numbers.subList(0, 8);
Pass it.
someMethod(eightRandomNumbers);
You don't need to add all the numbers to your internal list, though with 1000 numbers it doesn't essentially matter. Essentially what you do is this:
- construct an isntance of Random
- for each line in the file, calculate the percentage chance (as a double between 0 and 1) of you "needing" that number (effectively, number of items still needed divided by number of items still left in the file);
- call nextDouble() om your random instance: if that double is less than the percentage chance that you calculated, then add the number to your list;
- if you then need the selected numbers to be in random order, call Collections.shuffle() on the list of numbers you selected as indicated in some of the answers.
In case it's of any help, I've written an article on this topic before with example code: see how to pick a random sample from a list.
精彩评论