# [HELP] (int)(Math.random()*9)

Page 1 of 1

## 6 Replies - 861 Views - Last Post: 09 March 2013 - 05:07 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=314806&amp;s=e3937f3d1451cc2d498711f11574a1ff&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 glr

Reputation: -2
• Posts: 20
• Joined: 20-February 13

# [HELP] (int)(Math.random()*9)

Posted 08 March 2013 - 06:25 PM

```number=(int)(Math.random()*9)
```

I know that statement generates random numbers from 0-9. But what if I want to generate starring from 2-9, instead of starting from 0?
Is This A Good Question/Topic? 0

## Replies To: [HELP] (int)(Math.random()*9)

### #2 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12278
• Posts: 45,364
• Joined: 27-December 08

## Re: [HELP] (int)(Math.random()*9)

Posted 08 March 2013 - 06:51 PM

Generate integers from 0-7 and then add 2 to the result.

### #3 burakaltr

• D.I.C Regular

Reputation: 91
• Posts: 280
• Joined: 07-November 10

## Re: [HELP] (int)(Math.random()*9)

Posted 08 March 2013 - 07:01 PM

Or generate (int) Math.random( )*10

And take those in range 2-9 with an if statement

Do generation recursively

This post has been edited by burakaltr: 08 March 2013 - 07:06 PM

### #4 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12278
• Posts: 45,364
• Joined: 27-December 08

## Re: [HELP] (int)(Math.random()*9)

Posted 08 March 2013 - 07:09 PM

This is a highly inefficient approach. Why bother with the extra calculations at all and use recursion, which is expensive to begin with, when it isn't necessary?

### #5 farrell2k

• D.I.C Lover

Reputation: 874
• Posts: 2,706
• Joined: 29-July 11

## Re: [HELP] (int)(Math.random()*9)

Posted 08 March 2013 - 07:53 PM

I hate using Math.random(). Math.random() uses the Random() class internally anyway, so use that. It's nicer to look at.

Apache has a MathUtils library with a class that will let you generate random numbers within a specified range, much like you can do with c#.

I don't know why I replied. I added nothing to this topic...

### #6 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: [HELP] (int)(Math.random()*9)

Posted 08 March 2013 - 08:47 PM

Random numbers are calculatedd base on integer calculation
Math.random() creates a static Random object anyhow

So if you need a random integer just create a Random object and call its nextInt() method

2-9

n = ran.nextInt(8) + 2 so may be a rule

betwen x-y

n = ran.nextInt(y-x+1) + x

### #7 g00se

• D.I.C Lover

Reputation: 3536
• Posts: 16,027
• Joined: 20-September 08

## Re: [HELP] (int)(Math.random()*9)

Posted 09 March 2013 - 05:07 AM