the first number is set by me and the other numbers by the method ,and
every number is shown only one time
It looks like you are after a shuffling algorithm. The following category on NSMutableArray
will do the job:
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
@implementation NSMutableArray (Shuffling)
- (void)shuffle
{
// Fisher–Yates shuffle (modern algorithm)
// To shuffle an array a of n elements (indexes 0..n-1):
// for i from n − 1 downto 1 do
// j <-- random integer with 0 <= j <= i
// exchange a[j] and a[i]
// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
for (int i = [self count] - 1; i >= 1; i--) {
int j = arc4random() % (i + 1);
[self exchangeObjectAtIndex:j withObjectAtIndex:i];
}
}
@end
Your requirement is that the number in the first position of the array is fixed (given by you). Then, you can do something like this:
Populate the array with all numbers between minValue
and maxValue
(both included) except for firstValue
.
Shuffle the array.
Insert firstValue
at the first position in the array.
Resulting in the following code:
NSInteger minValue = 5;
NSInteger maxValue = 10;
NSInteger firstValue = 9;
// minValue <= firstValue <= maxValue
// populate the array with all numbers between minValue
// and maxValue (both included) except for firstValue
NSMutableArray *ary = [NSMutableArray array];
for (int i = minValue; i < firstValue; i++) {
[ary addObject:[NSNumber numberWithInt:i]];
}
for (int i = firstValue + 1; i <= maxValue; i++) {
[ary addObject:[NSNumber numberWithInt:i]];
}
// --> (5,6,7,8,10)
// shuffle the array using the category method above
[ary shuffle];
// insert firstValue at the first position in the array
[ary insertObject:[NSNumber numberWithInt:firstValue] atIndex:0];
// --> (9,x,x,x,x,x)