【问题标题】:Random number in Objective-C [duplicate]Objective-C中的随机数[重复]
【发布时间】:2011-10-23 01:28:43
【问题描述】:

可能的重复:
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

我尝试使用它:

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;
    }
}

【问题讨论】:

  • 自己分配第一个并生成其余的随机数。不需要while循环
  • 如果预期的输出总是相同的,那么它怎么可能是随机数呢?可能是我错过了问题中的某些内容。
  • 不一样,我举个例子,第一个数字是我设置的,其他数字是方法设置的,每个数字只显示一次。
  • 看起来你基本上是在寻找一些随机的东西。请参阅shuffle 标签了解一些想法。

标签: ios objective-c random


【解决方案1】:

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

【讨论】:

  • 为什么有人会贬低这个?这是最好的答案。
  • @Alex K.:同样的事情我也想知道,因为这对我来说是个谜……谢谢你的关心。
【解决方案2】:

第一个数字由我设置,其他数字由方法设置,并且 每个数字只显示一次

看起来您正在使用洗牌算法。 NSMutableArray 上的以下类别将完成这项工作:

@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

您的要求是数组第一个位置的数字是固定的(由您给出)。然后,您可以执行以下操作:

  1. minValuemaxValue 之间的所有数字(包括firstValue 除外)填充数组。

  2. 随机排列数组。

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

产生如下代码:

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)

【讨论】:

  • 很棒的答案。非常感谢。
猜你喜欢
  • 2013-05-12
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
相关资源
最近更新 更多