We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Unique random number for elements in array
I have to create an array of numbers (five element) that have to be unique
int[] numbers = new int[5];
for (int h = 0; h <= 4; h++)
{
// how to check this random number is unique
numbers[h] = (int)random(0, 7);
}
printArray(numbers);
Any clue ? Thank in advance SALUD...
Answers
Well, it works, but... can you comment your code? I prefer to understand it.
thanks in advance
SALUD...
It's a pretty small code. Could you instead pinpoint where you didn't get it? ;;)
My questions
1: numbers[i] = MIN_INT;
MIN_INT is a built constant that give you the small number -2147483648
I have comment this line numbers[i] = MIN_INT; and I think the code seem to work well, what are the use of this constant?
2: boolean contains(int n, int... nums) {…..}
WHILE reference to the variable contains, I don’t understand how you used it, also the expression (int n, int... nums) surprise me.
I have debug with some println() and I know how the code work, but not why
The Debug :
thanks a lot
SALUD...
An
int[]
array have all its slots equal to0
when instantiated. Since0
belongs to the random range, I had to give them some arbitrary value outside that picking range. Commenting out that line would put '0' out of it!"WHILE reference to the variable contains...". contains() isn't a variable, but a function! It checks whether a given number already exists in the array!
while ()
is a Java keyword which creates a loop: https://processing.org/reference/while.html . It repeats the loop as long condition istrue
.In short, it stops when function contains() return
false
, denoting the picked number wasn't yet present in the array!you can also convert your array to a Set
@dimiro, that's also a good path. However, it won't make the program any shorter, b/c it's still gotta check whether the insertion passed thru' and keep trying to pick another Integer in case of failure!
Given that the sample size is such a high proportion of the total possible values, I'd be tempted to do it this way instead:
Very nice inverted logic there, @Antony74! =D> Just make sure to use generics for Collection data structures.
Many folks here still think that we gotta use (cast) all the time due to incompetency of Processing's reference page,
that spread such Java 4 legacy bad practice for so many years! =;
Anyways, since non-regular arrays are allowed now, how about 1 w/ IntList? : (*)
https://processing.org/reference/IntList.html
See also http://forum.processing.org/two/discussion/7688/unique-random-number-for-serial-music
If you want a simple solution for java random generator, check here!
that wasn't the question.
plus this is a processing forum and processing has its own random(n, m);