AnUnnoticedPotato AnUnnoticedPotato - 1 year ago 84
Java Question

Random number generation and Arrays

I've been creating a random element generator of my first text adventure game, to be more specific, this:

Random Generation = new Random();
List<Integer> interact = new ArrayList<Integer>();
for (int generator = Generation.nextInt(5) + 3; generator > 0; generator--) {

Here, generator defines the amount of elements, and interact its a list that contains random numbers which represent different interactive objects, the thing is, i need elements don't repeat, I've seen some previous questions, but i don't think they apply to my case, at least completely.

I was thinking in a
int a = Generation.nextInt(3); if (a != interact[]) {interact.add(a)} else {generator++};
but I don't know how to set an
in comparing arrays.

Also, as an extra (not my main question, so if it isn't possible i don't care too much) Can you set which elements can be repeated and which not, in a single generator? Or maybe a better random one, for this specific case? Thanks for reading to here.

Edit: Thanks a lot to everyone!
Edit2: sorry if i repeated question, can some one pass me a link of the original one?

Answer Source

IIRC your requirements are:

  • Game must have an "element list" of size 3 <= numberOfItems <= 8. Where numberOfItems must be randomized each time.
  • The "element list" must contain exactly numberOfItems random integers between 0 and 10.

How about this?

    Random generator = new Random();
    Set<Integer> interact = new HashSet<Integer>();
    int numberOfItems = generator.nextInt(5) + 3;
    while (interact.size() < numberOfItems) {

It will keep adding distinct elements to interact until it reaches the designated capacity numberOfItems.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download