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;
}
Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
bembas
  • 762
  • 8
  • 20
  • 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. – achAmháin Sep 18 '18 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. – achAmháin Sep 18 '18 at 19:56

1 Answers1

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();
Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
  • Just like a deck of cards. – killjoy Sep 18 '18 at 19:58
  • It’s not an `array` as mentioned in the question, but have an upvote for the easy solution. – achAmháin Sep 18 '18 at 19:58
  • 1
    I'd add `return list.stream().mapToInt(Integer::intValue).toArray();` also, you could do `List list = IntStream.range(1, 1 + size).boxed().collect(Collectors.toList());` which then makes it respect `size` too. – Elliott Frisch Sep 18 '18 at 19:58
  • 3
    `List` doesn’t have a fixed size. – achAmháin Sep 18 '18 at 20:01
  • @achAmháin only partially correct. The [documentation of `List.of(...)`](https://docs.oracle.com/javase/10/docs/api/java/util/List.html#of(E...)) states that it "*Returns an unmodifiable list containing an arbitrary number of elements.*" – Turing85 Sep 18 '18 at 20:05
  • @Turing85 I was waiting for someone to correct me on a technicality :) – achAmháin Sep 18 '18 at 20:32