Reputation: 1125
I want to enter a letter or number and generate a random output (letter or number). And output should also be always same for same input. Can someone please guide me that how can I generate this random output with this specific range.
Upvotes: 0
Views: 311
Reputation: 11236
If I have understood you correct, maybe this is want you are trying to do.
import java.util.Random;
class t
{
public static void main(String[] args)
{
Random rand = new Random(100);
char[] alpha = new char[26]; //to store alpahbets
int[] rlist = new int[26]; //to store random numbers
for (int j = 0; j<26; j++)
{
alpha[j] = (char)(j+97);
rlist[j] = rand.nextInt(10);
System.out.println(rlist[j]);
}
//input
char input = 'a';
//output
int loc = (int)input-97;
System.out.println(alpha[rlist[loc]]);
}
}
You could very well use a hashtable.
Upvotes: 0
Reputation: 46963
First of all I will make the case of String input equivalent to the one with integer: the simplest way I can think of is to use str.hashCode()
every object in Java defines this method and it is very easy way to generate an integer from any kind of input.
So now lets assume you have to generate random string based on a single given integer `seed. You can do that:
public String generateString(int seed) {
Random rnd = new Random(12);
int len = 10 + rnd.nextInt() % 20; // achieving random string length in [10, 30)
StringBuilder sb = new StringBuilder(); // here we will build the string
for (int i = 0; i < len; i++) {
sb.append(32 + (char) rnd.nextInt() % 94); // displayable ASCIs are between 32 and 127
}
return sb.toString();
}
Upvotes: 2
Reputation: 859
The point of random output is "randomness" , if you want a method that generates the same output for the same input , then it is not random at all.
If you just want a method that does input -> (do stuff here) -> output Where for any input 'i' , the output 'o' is fixed like , if you give 1 as an input you always get 247 (or any other number) then just make up any mathematical formula (eg. (sin(x) * 73)/43 or tan(x) if you don't want the output to repeat ) where 'x' is your input , this will generate a 'seemingly' unrelated output for any input , which will always be fixed for any given number.
Upvotes: 1