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

From: Jahan Z.
Sent on: Saturday, January 26, 2013 6:07 PM
Wes,

I think casting a double to a long truncates towards 0, hence why 0 appears twice as often. A quick fix to this would make it:


public static long generateRandom(long min, long max) {
	double c = (max/2) - (min/2) + (1/2);
	double r = 2 * c * Math.random() + min;
	if(r < 0){
		return (long)(r-1)
	} else {
		return (long) r
	}
}


Jahan

-----Original Message-----
From: [address removed] [mailto:[address removed]] On Behalf Of Wesley Hall
Sent: 26 January[masked]:39
To: [address removed]
Subject: Re: [ljc] A little Friday morning challenge for the group...

Michael,

Nice :). I would have to say that all the bit shifting and binary mathematics is probably a good sign that you are smarter than I am.
Curse these inconvenient ten fingers ;).

Jahan,

Yeah, actually once I figured out the max - min problem, then the next step my mind took was to do some midpoint calculations. I put your solution into my IDE and tested it and it appears to work beautifully, the only anomaly I can see is that for a range -100 to 100, then 0 is about twice as frequent as any other given result.



On Sat, Jan 26, 2013 at 12:33 PM, Michael Rogers <[address removed]> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> 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 {
>             random.nextBytes(b);­
>             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();
>     }
> }
>
> Cheers,
> Michael
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.10 (GNU/Linux)
>
> iQEcBAEBAgAGBQJRA8es­AAoJEBEET9GfxSfM3ZoI­AIPXmuAFuU4+zzQi0mGU­d2vL
> X3d7z0fO1PsKYRLiD4wv­gtz6u8gcwfCpLLj7EXvL­R0uC4O6MbgAbQdIBzkUA­H+ly
> IkftRzwOpWwLhUnaoK01­Cqa2dzCQ+3lfWN59uz8Q­mjs6UDEW0PoedlKLlcpJ­Un66
> YrfaUoDDvzODs/jyuqwY­mC4loqDcDWI6WyE/Wpk3­D0NNDJmBG6tdqUSDkum4­DcgI
> q0QA4SUKusM0vSDhf69a­qc+yiVByZ/1robvSuTAT­5sk3fmmdF09ZH32aPpJB­36pA
> MCGDtWnFLEGjQ0pMNUUa­99PMMErQzA08ut8lscfC­W4Vz3IEzQ6pK1GOeVmcI­a68=
> =LuNA
> -----END PGP SIGNATURE-----
>
>
>
>
> --
> Please Note: If you hit "REPLY", your message will be sent to everyone 
> on this mailing list ([address removed]) 
> http://www.meetup...­
> This message was sent by Michael Rogers ([address removed]) from LJC - London Java Community.
> To learn more about Michael Rogers, visit his/her member profile: 
> http://www.meetup...­
> Set my mailing list to email me
>
> As they are sent
> http://www.meetup...­
>
> In one daily email
> http://www.meetup...­
>
> Don't send me mailing list messages
> http://www.meetup...­
> Meetup, POB 4668 #37895 NY NY USA 10163 | [address removed]
>




--
Please Note: If you hit "REPLY", your message will be sent to everyone on this mailing list ([address removed]) http://www.meetup...­
This message was sent by Wesley Hall ([address removed]) from LJC - London Java Community.
To learn more about Wesley Hall, visit his/her member profile: http://www.meetup...­
Set my mailing list to email me

As they are sent
http://www.meetup...­

In one daily email
http://www.meetup...­

Don't send me mailing list messages
http://www.meetup...­
Meetup, POB 4668 #37895 NY NY USA 10163 | [address removed]

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 12/13 Jun 14

  • SkillsMatter

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

  • 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.

  • Packt Publishing

    A publishing company specializing on specific technologies and solutions

  • 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