addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscontroller-playcredit-cardcrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobe--smallglobegmailgooglegroupshelp-with-circleimageimagesinstagramFill 1languagelaunch-new-window--smalllight-bulblinklocation-pinlockm-swarmSearchmailmessagesminusmobilemoremuplabelShape 3 + Rectangle 1ShapeoutlookpersonJoin Group on CardStartprice-ribbonprintShapeShapeShapeShapeImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruserwarningyahoo

Re: [ljc] A little Friday morning challenge for the group...

From: Tom H.
Sent on: Friday, January 25, 2013 6:37 PM
n 25/01/2013, Wesley Hall <[address removed]> wrote:
> public static long generateRandom(long min, long max) {
>    // code here
> }

Off the top of my head (don't have a Java compiler on my machine).

    // Doing this properly, right?
    private static final ThreadLocal<Rando­m> rng = new ThreadLocal<Rando­m>() {
        @Override protected Random initialValue() {
            return new SecureRandom();
        }
    }

    public static long generateRandom(long min, long max) {
        // ...special case handling here...
        final Random g = rng.get();
        long value;
        do {
            value = g.nextLong();
        } while (!(min <= value && value <= max));
        return value;
    }

You may want to optimise for small ranges (copying code from
nextInt(int)) as it may take some time to complete.

Tom

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy