Reputation: 177
I have code that randomly generates a binary number from 000 to 111 but I'm having trouble having it create a number from 000 to just 110. I know that I can somehow rerun the code everything it comes out with 111 but I can't seem to figure out the way to have it do that.
public String binNumber() {
StringBuilder storage = new StringBuilder();
int i = 0;
while (i < 3) {
int binny = this.giveMeBinary();
storage.append(String.valueOf(binny));
i++;
}
return storage.toString();
}
public int giveMeBinary() {
Random rg = new Random();
int bin = rg.nextInt(2);
return bin;
}
Upvotes: 0
Views: 12100
Reputation: 564
I created a method which can return a random binary number below 128 (value 128 can be alter in the code)-
public static void RandomBinary(int len){
if(len<128) {
Random random = new Random();
boolean res;
String randomBinary = "";
for (int i = 0; i < len - 1; i++) {
res = random.nextBoolean();
if (res)
randomBinary = randomBinary.concat("1");
else
randomBinary = randomBinary.concat("0");
}
System.out.print(randomBinary);
}else {
System.out.print("KeyGen maximum length allowed is 128. Please enter value below 128");
}
}
Upvotes: 0
Reputation: 2644
If you want to re-roll, try this:
String num = "";
while (true)
{
num = binNumber();
if (!num.equals("111"))
{
break;
}
}
return num;
Upvotes: 1
Reputation: 38852
Something like:
Random random = new Random();
int nextNumber = random.nextInt( 7 );
System.out.println( Integer.toBinaryString( nextNumber ) );
Remember your numbers you create in a computer are always in binary. You just need to print it out differently. So even though you've given it a decimal number that number is converted by the compiler to binary. 7 == 0x111 when its compiled.
Upvotes: 1
Reputation: 14478
The better way to do this is to generate a random number from 0 to 6 inclusive, and then convert to a string
public String binNumber() {
Random rg = new Random();
int n = rg.nextInt(7);
return Integer.toBinaryString(n);
}
Upvotes: 8
Reputation: 5433
"Rerolling" if you get 111 is definitely a bad idea; that's potentially an algorithm with infinite running time, although in practice it would do quite well.
Why work in base 2? Work in base 10, easily get a random number between 0 and 6, and then translate back to binary.
Upvotes: 3