关于ios:Objective-C中的随机数

Random number in Objective-C

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicates:
Generating random numbers in Objective-C
iOS Random Numbers in a range
Generate non-repeating, no sequential numbers

我正在寻找一种方法,在两个数字之间给我随机数,第一个数字是我在两个数字之间选择的数字。

例如,如果我把这个随机函数5,10和9作为第一个数字,那么它会给我:9,10,7,6,5,8

我试着用它:

1
2
3
4
5
6
7
8
NSUInteger count = [array count];
for (NSUInteger i = 1; i < count; ++i) {
        int nElements = count - i;
    int n = (random() % nElements) + i;
    while (n==`firstnumber`) {
        n = (random() % nElements) + i;
    }
}


int r = arc4random() % 9 + 5会给你5到13之间的数字,包括这两个数字。


the first number is set by me and the other numbers by the method ,and
every number is shown only one time

看起来你在处理一个混乱的算法。NSMutableArray上的以下类别将完成此项工作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@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

您的要求是数组第一个位置的数字是固定的(由您给定)。然后,您可以这样做:

  • minValuemaxValue之间的所有数字填充数组(都包括在内),firstValue除外。

  • 随机播放阵列。

  • 在数组的第一个位置插入firstValue

  • 产生以下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    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)