从数组中读取随机值 [英] Reading random values from an array

查看:72
本文介绍了从数组中读取随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含14个字符串的数组.我想向用户显示这14个字符串中的每一个,而不重复.我得到的最接近的结果是创建一个整数数组并将其值改组,然后使用int数组中的数字之一作为索引从字符串数组中读取:

I have an array with a 14 strings. I want to display each of these 14 strings to the user without duplicates. The closest I got was creating an array of integers and shuffling their values, and then reading from the array of strings using one of the numbers from the int array as the index:

    //appDelegate.randomRiddles is an array of integers that has integer values randomly
     appDelegate.randomRiddlesCounter++;
     NSNumber *index=[appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
     int i = [index intValue];
     while(i>[appDelegate.currentRiddlesContent count]){
        appDelegate.randomRiddlesCounter++;
        index=[appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
        i = [index intValue];
                    }
hintText.text = [[appDelegate.currentRiddlesContent objectAtIndex:i] objectForKey:@"hint"];
questionText.text = [[appDelegate.currentRiddlesContent objectAtIndex:i] objectForKey:@"question"];

但是我的方式导致崩溃和重复.哦,每当我从字符串数组中读取一个值时,该字符串就会从数组中删除,从而使其计数减少1.因此,这会使操作变得有些复杂.

But my way is causing crashing and duplicates. Oh and each time I read a value from the strings array, that string is removed from the array making its count decrease by 1. So that complicates this a little bit.

推荐答案

像这样获取数组中的元素:

Get the elements in your array like this:

int position = arc4random() % ([myArray count]);

这样,即使计数减少一,也可以,因为在没有其他可能的值之前,您仍将获得有效的下一个头寸值.

This way even though count decreases by one, that is ok, as you will still get a valid next position value till there aren't any more posible values.

这篇关于从数组中读取随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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