0

I need to generate an random array from a bigger array of int without repetition and in a range of numbers.

For e.g I have an array a[] with 1-200 int , What i need is random number array from all 200 int but of size 15.How could I implement this?

2 Answers 2

3

Fisher-Yates shuffle. In particular, shuffle just the first 15 elements and select them.

Sign up to request clarification or add additional context in comments.

5 Comments

In particular, shuffle just the first 15 elements and select them. - sorry, but I didn't really get this part. Can you elaborate please?
+1 The shuffle selects a random element for each cell in turn. Since you only need 15 you can stop once you have done the 15th cell.
There should be no dupes though.
aioobe, their initial array contains no duplicates as far as I understood the question.
Note: Unless modifying the algorithm to work on new arrays (usually it's in-situ), this will modify the initial array of numbers which may or may not be a problem.
2
Random rnd = new Random();

int[] a = new int[200];
for (int i = 0; i < a.length; i++)
    a[i] = i;

int[] r = new int[15];
for (int i = 0; i < r.length; i++) {
    int j = rnd.nextInt(a.length - i);
    r[i] = a[j];
    a[j] = a[a.length - i - 1];
}

That should do it. Random grab something from a. Once you've grabbed it, replace it with the "last" value of a. The "last" value is easily derived from a.length and i.

1 Comment

No prob. Remember, this modifies a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.