addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscontroller-playcrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobegmailgooglegroupshelp-with-circleimageimagesinstagramFill 1light-bulblinklocation-pinm-swarmSearchmailmessagesminusmoremuplabelShape 3 + Rectangle 1ShapeoutlookpersonJoin Group on CardStartprice-ribbonprintShapeShapeShapeShapeImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruserwarningyahoo

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

From: Michael R.
Sent on: Saturday, January 26, 2013 12:10 PM
Hash: SHA1

On 25/01/13 11:01, Wesley Hall wrote:
> Your mission, should you choose to accept it, is to write a method,
> in Java, with the following signature...
> public static long generateRandom(long min, long max) { // code
> here }

My attempt (rather heavyweight but I think it's correct):

import java.math.BigInteger;­
import java.util.Random;

public class LongRandom {

    private static final Random random = new Random();

    public static long generateRandom(long min, long max) {
        BigInteger bigMin = BigInteger.valueOf(m­in);
        BigInteger bigMax = BigInteger.valueOf(m­ax);
        BigInteger exclusive = bigMax.subtract(bigM­in);
        BigInteger inclusive = exclusive.add(BigInt­eger.ONE);
        // Work out how many bytes we need to generate
        int bits = exclusive.bitLength(­);
        int bytes = (bits % 8 == 0) ? bits / 8 : bits / 8 + 1;
        assert bytes > 0 && bytes <= 8;
        // The PRNG generates bytes, so there will be up to 7 spare bits
        int spareBits = bytes * 8 - bits;
        assert spareBits >= 0 && spareBits < 8;
        // Mask out the spare bits each time we generate bytes
        int mask = 0xff;
        for(int i = 0; i < spareBits; i++) mask ^= 1 << (7 - i);
        // Generate random bytes until we get a value in the required
        // range (unlike the modulus, this gives a uniform distribution)
        byte[] b = new byte[bytes];
        BigInteger rand;
        do {
            b[0] &= mask; // Mask out the spare bits
            rand = new BigInteger(1, b); // Positive signum
        } while(rand.max(inclu­sive).equals(rand));­
        rand = rand.add(bigMin);
        assert rand.min(bigMin).equ­als(bigMin); // rand >= min
        assert rand.max(bigMax).equ­als(bigMax); // rand <= max
        return rand.longValue();


Version: GnuPG v1.4.10 (GNU/Linux)


Our Sponsors

  • Our Blog

    Read the latest news from the LJC

  • RecWorks Ltd

    Fixing Tech Recruitment using the Power of Community

  • jClarity

    Java/JVM Performance Analysis Tools & mentoring for Java related matters

  • LJC Aggrity

    Our LJC Aggrity site contains blog posts from our members

  • LJC Book Club

    Our Book club with book reviews from our members

  • Devoxx UK

    Java Community Conference in collaboration with the LJC, 8-10th June 16

  • SkillsMatter

    "Host, help organise, promote, film many of our meetings."

  • IBM

    Build Enterprise-grade apps at start-up speed.

  • New Relic

    New Relic makes sense of billions of metrics a day in real time.

  • Hazelcast

    Hazelcast is the leader in operating in-memory computing.

  • Java.Net

    We are an official Java User Group recognised by Oracle's JUG program

  • JRebel

    Free 3 month J-Rebel license.

  • O'Reilly

    40% discount on printed books and 50% on e-books.

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