1

I want to generate in java an array with random numbers from 1 to 10 but I need the array to have at least one of each 10 numbers.

wrong: array = {1,2,3,1,3,2,4,5}

correct: array = {1,2,4,3,6,8,7,9,5,10...}

The array can have size bigger than 10 but the 0 to 10 numbers must exist in the array.

My code for generating the array so far:

public int[] fillarray(int size, int Reel[]) {

    for (int i = 0; i < size; i++) {
        Reel[i] = (int) (Math.random() * symbols);
    }

    System.out.println(Arrays.toString(Reel));

    return Reel;
}
2
  • You’ll need to keep track of the numbers as you go along and mark them off once there and only return once all are there. Commented Sep 18, 2018 at 19:55
  • You’ll also probably not be able to set the size doing it this way, so arrays are probably not your friend. Perhaps consider a List or one of its implementations. And Reel should be reel, i.e. lower case. Commented Sep 18, 2018 at 19:56

1 Answer 1

10

You can use a List and Collections.shuffle:

List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
Collections.shuffle(list);

And, following @Elliott's helpful advice, you can convert a list to array:

int[] result = list.stream().mapToInt(Integer::intValue).toArray();
Sign up to request clarification or add additional context in comments.

6 Comments

Just like a deck of cards.
It’s not an array as mentioned in the question, but have an upvote for the easy solution.
I'd add return list.stream().mapToInt(Integer::intValue).toArray(); also, you could do List<Integer> list = IntStream.range(1, 1 + size).boxed().collect(Collectors.toList()); which then makes it respect size too.
List doesn’t have a fixed size.
@achAmháin only partially correct. The documentation of List.of(...) states that it "Returns an unmodifiable list containing an arbitrary number of elements."
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.