1. Member
Join Date
Nov 2010
Location
Turkey
Posts
6
Rep Power
0

Java Math.random help:S

int generate = 1000 + (int)(Math.random()*9000);

we can produce 4 digit number with this code between 1000 to 10000; but I want to make every digit different from each other. (e.g in 1959, 9 is used twice)

2. You could generate 4 different single digits from 0-9, check to make sure they're unique, and combine them.

3. Member
Join Date
Nov 2010
Location
Turkey
Posts
6
Rep Power
0
okey, it's true. Then,For making different digit, I should control every digit in while and then generate the other digit, is it true?

4. What happened when you tried that?

You could also store the numbers in an array (or a List, or a Set) to check against when generating the next number.

Or you could do it the brute force way: if you generate enough random numbers, eventually you'll end up with one that has all unique digits. Not pretty, but it would work.

5. Member
Join Date
Nov 2010
Location
Turkey
Posts
6
Rep Power
0
I control them in "while", It is running (not generating same digits)and I have to store them to use in the end of the program. I think it can be with array, but I don't know using it:S

6. Member
Join Date
Nov 2010
Location
Turkey
Posts
6
Rep Power
0
Thanks for your helps KevinWorkman :)

7. No problem. Does that mean you solved it? You might consider posting your solution so people with the same problem in the future will be able to learn from it.

8. Member
Join Date
Nov 2010
Location
Turkey
Posts
6
Rep Power
0
After I wrote the code, I will post it :)

9. Member
Join Date
Nov 2010
Location
Turkey
Posts
6
Rep Power
0
public class GenerateDifferentFourDigitNumber{
public static void main(String[]args){
int a, b, c, d;
a = (int)(Math.random()*9+1); // a is between 1-9 inclusive
do{
b = (int)(Math.random()*10);
}while(a==b); // b is between 0-9, inclusive, and different than a

do{
c = (int)(Math.random()*10);
}while(c==b||c==a); // c is between 0-9, inclusive, and different than (a and b)

do{
d = (int)(Math.random()*10);
}while(d==a||d==b||d==c||d==0); // d is between 0-9, inclusive, and different than (a and b and c)

int result = d*1000+c*100+b*10+a; // compute the number.

System.out.println(result); // print the number to screen
}
}

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•