Java Reference
In-Depth Information
final int PRIMESREQUIRED = 10;
ByteBuffer buf = ByteBuffer.allocate(8*PRIMESREQUIRED);
long[] primes = new long[PRIMESREQUIRED];
int index = 0; // Position for a prime in the file
try {
// Count of primes in the file
final int PRIMECOUNT = (int)inChannel.size()/8;
// Read the number of random primes required
for(int i = 0 ; i<PRIMESREQUIRED ; i++) {
index = 8*(int)(PRIMECOUNT*Math.random());
inChannel.read(buf, index); // Read the value
buf.flip();
primes[i] = buf.getLong(); // Save it in the array
buf.clear();
}
// Output the selection of random primes 5 to a line in field width of 12
StringBuffer str = null;
for(int i = 0 ; i<PRIMESREQUIRED ; i++) {
str = new StringBuffer(" ").append(primes[i]);
System.out.print((i%5 == 0 ? "\n" : "")
+ str.substring(str.length()-12, str.length()));
}
inFile.close(); // Close the file and the channel
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
When I ran this, I got the output:
359 107 383 109 7
173 443 337 17 113
You should get something similar, but not the same since the random number generator is seeded using
the current clock time.
How It Works
We access a random prime in the file by generating a random position in the file with the expression
8*(int)(PRIMECOUNT*Math.random() ). The value of index is a pseudo-random integer that can
be from 0 to the number of primes in the file minus one, multiplied by 8 since each prime occupies
eight bytes. Since buf has a capacity of 8 bytes, only one prime will be read each time. We store a
randomly selected prime in each element of the primes array. Finally we output the primes five to a line
in a field width of 12 characters.
Search WWH ::




Custom Search