Objective-C如何在不获取重复项的情况下从NSArray中提取一些随机项? [英] Objective-C how to pull several random items out of NSArray without getting duplicates?

查看:106
本文介绍了Objective-C如何在不获取重复项的情况下从NSArray中提取一些随机项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一系列随机属性分配给我正在开发的游戏中的设备.

I have an array of random properties I would like to assign to equipment within the game I'm developing.

我在下面使用的代码返回一个NSArray.我很想知道是否有办法从该数组中获取项目索引而又不会得到重复的值.显而易见的解决方案是使用返回的数组创建一个可变数组,随机执行,删除返回的项目并循环直到收到项目数.

The code that I use below is returning an NSArray. I'm interested if there's way to get item indices from that array without getting duplicate values. The obvious solution is to create a mutable array with the returned array, do random, remove item that was returned and loop until the number of items is received.

但是是否有另一种方法可以从NSArray中获取X个随机项而不获取重复项?

//get possible enchantments
NSPredicate *p = [NSPredicate predicateWithFormat:@"type = %i AND grade >= %i", kEnchantmentArmor,armor.grade];

NSArray* possibleEnchantments = [[EquipmentGenerator allEnchantmentDictionary] objectForKey:@"enchantments"];

//get only applicable enchantments
NSArray *validEnchantments = [possibleEnchantments filteredArrayUsingPredicate:p];
NSMutableArray* mutableArray = [NSMutableArray arrayWithArray:validEnchantments];

NSDictionary* enchantment = nil;

if(mutableArray.count>0)
{
    //got enchantments, assign number and intensity based on grade
    for (int i = 0; i<3;i++)
    {
        enchantment = mutableArray[arc4random()%mutableArray.count];
        [mutableArray removeObject:enchantment];

        //create enchantment from dictionary and assign to item.
    }

}

推荐答案

您可以使用以下一种技术来对数组进行混洗:

You can shuffle the array using one of the following techniques:

改组NSMutableArray的最佳方法是什么?
不重复随机数

What's the Best Way to Shuffle an NSMutableArray?
Non repeating random numbers

然后,从数组中获取前X个元素.

Then, take the first X elements from the array.

这篇关于Objective-C如何在不获取重复项的情况下从NSArray中提取一些随机项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆