gpt4 book ai didi

objective-c - 从 nsarray 中获取 n 个随机对象(例如 4)

转载 作者:技术小花猫 更新时间:2023-10-29 10:44:10 25 4
gpt4 key购买 nike

我有一个很大的 NSArray 名称,我需要从该数组中随机获取 4 条记录(名称),我该怎么做?

最佳答案

#include <stdlib.h>

NSArray* names = ...;
NSMutableArray* pickedNames = [NSMutableArray new];

int remaining = 4;

if (names.count >= remaining) {
while (remaining > 0) {
id name = names[arc4random_uniform(names.count)];

if (![pickedNames containsObject:name]) {
[pickedNames addObject:name];
remaining--;
}
}
}

关于objective-c - 从 nsarray 中获取 n 个随机对象(例如 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5839881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com