I have made a little java program. An integer will be input and then random numbers will be printed to the console till we found that integer input. The code will cheat a bit since it will know how many digits the input number has.
Random numbers will be used and what I want do is I want exclude every random number that had been used. But I have no idea how it could be done. Well I have one idea but it would be a cheap bypass I don't like. It would be by start at 0 and always increase it by 1 value till we find the input.
Could this (exclude used random number) be done in java?
I imagine we could make a list so every used number will be in that list. In every loop access the list to check if number is unused. But this is just imagination, would it really be possible in java?
import java.util.Scanner;
import java.util.Random;
public class Backtracker{
public static void main(String[]args){
int counter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter integer here: ");
int x = input.nextInt();
Random rand = new Random();
int a = rand.nextInt(100)+0;
int b = rand.nextInt(1000)+100;
int c = rand.nextInt(10000)+1000;
int d = rand.nextInt(100000)+10000;
int e = rand.nextInt(1000000)+10000;
int f = rand.nextInt(10000000)+1000000;
int g = rand.nextInt(100000000)+10000000;
if(x<=100){
while(x != a){
a = rand.nextInt(100)+0;
System.out.println(a);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=1000){
while(x != b){
b = rand.nextInt(1000)+100;
System.out.println(b);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=10000){
while(x != c){
c = rand.nextInt(10000)+1000;
System.out.println(c);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=100000){
while(x != d){
d = rand.nextInt(100000)+10000;
System.out.println(d);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=1000000){
while(x != e){
e = rand.nextInt(1000000)+100000;
System.out.println(e);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=10000000){
while(x != f){
f = rand.nextInt(10000000)+1000000;
System.out.println(f);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=100000000){
while(x != g){
g = rand.nextInt(100000000)+10000000;
System.out.println(g);
counter++;
}
System.out.println("Tries: "+counter);
}
}
}
Aucun commentaire:
Enregistrer un commentaire