Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Array Generator Java

I need to initialize an array of characters with 1000 random characters between [a,..z] and [A,..,Z].

I don’t want do this by first generating only characters between [a,..z] and then only characters in [A...Z] but treat all 52 characters equally.

I know one way to do this is to generate a random number between 0 and 51 and assign it one of the character values.

How would I approach this problem or assign values to the random numbers between 0 and 51?

like image 911
linyu21 Avatar asked Sep 10 '15 05:09

linyu21


People also ask

How do you generate a random array in Java?

In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.

How do you generate a random number from an array?

Use Math. random() function to get the random number between(0-1, 1 exclusive). Multiply it by the array length to get the numbers between(0-arrayLength).

How do you generate a random number from 1 to 6 in Java?

For example, in a dice game possible values can be between 1 to 6 only. Below is the code showing how to generate a random number between 1 and 10 inclusive. Random random = new Random(); int rand = 0; while (true){ rand = random. nextInt(11); if(rand !=


2 Answers

You have got the interesting code idea. Here might be the thought.

  1. Take all the a-z and A-Z and store them in an array[].
  2. Randomly generate a number between 1-52 (use API classes for that).
  3. You will get a number in step 2, take it as an array index and pick this index from array[] of chars.
  4. Place that picked char to your desired location/format............
  5. Process it.

Best Regards.

like image 175
Sachin Avatar answered Sep 30 '22 14:09

Sachin


Let me give you some general guidelines. The "one way to do this" you mentioned works. I recommend using a HashMap<E>. You can read more about hashmaps in the docs:

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Alternatively, you can use another array that contains a - z and A - Z and you can use the index number to refer to them. But in this case I think it makes more sense to use a HashMap<E>.

I think you know how to create a Random object. But if you don't, check out the docs:

http://docs.oracle.com/javase/7/docs/api/java/util/Random.html

So you basically use the nextInt method of the Random class to generate a random number. And you can put that random number into your HashMap or array. And then you just put that character you get into an array that stores the result of the program.

like image 21
Sweeper Avatar answered Sep 30 '22 16:09

Sweeper