waqas
waqas

Reputation: 1125

generate short random number in java?

I want to generate a random number of type short exactly like there is a function for integer type called Random.nextInt(134116). How can I achieve it?

Upvotes: 17

Views: 16008

Answers (6)

Kirill I.
Kirill I.

Reputation: 47

If we take a look how nextInt is realisized:

public open fun nextInt(): Int = nextBits(32).

we can make something like:

fun nextShort(): Short = nextBits(16).toShort()

Upvotes: 0

luketorjussen
luketorjussen

Reputation: 3264

There is no Random.nextShort() method, so you could use

short s = (short) Random.nextInt(Short.MAX_VALUE + 1);

The +1 is because the method returns a number up to the number specified (exclusive). See here

This will generate numbers from 0 to Short.MAX_VALUE inclusive (negative numbers were not requested by the OP)

Upvotes: 26

Peter Lawrey
Peter Lawrey

Reputation: 533530

The most efficient solution which can produce all possible short values is to do either.

short s = (short) random.nextInt(1 << 16); // any short
short s = (short) random.nextInt(1 << 15); // any non-negative short

or even faster

class MyRandom extends Random {
    public short nextShort() {
        return (short) next(16); // give me just 16 bits.
    }
    public short nextNonNegativeShort() {
        return (short) next(15); // give me just 15 bits.
    }
}

short s = myRandom.nextShort();

Upvotes: 14

assylias
assylias

Reputation: 328629

How about short s = (short) Random.nextInt();? Note that the resulting distribution might have a bias. The Java Language Specification guarantees that this will not result in an Exception, the int will be truncated to fit in a short.

EDIT

Actually doing a quick test, the resulting distribution seems to be uniformly distributed too.

Upvotes: 6

Tudor
Tudor

Reputation: 62439

Simply generate an int like:

 short s = (short)Random.nextInt(Short.MAX_VALUE);

The generated int will be in the value space of short, so it can be cast without data loss.

Upvotes: 3

Skippy Fastol
Skippy Fastol

Reputation: 1775

Java shorts are included in the -32 768 → +32 767 interval.

why wouldn't you perform a

Random.nextInt(65536) - 32768

and cast the result into a short variable ?

Upvotes: 11

Related Questions