我有一个应用需要在出现提示时播放多个视频,但我希望这些视频是随机的而不是重复的。
我目前的计划是制作一个 NSMutableDictionary,其中键是视频的编号,值只是一个基本字符串,用于告诉我它是否已播放。然后,当要播放视频时,我会随机选择一个,看是否播放过。像这样:
int randomNumber;
randomNumber = (arc4random() % 150) + 1;
if ([[videoDictionary valueForKey:[NSString stringWithFormat:@"%d", randomNumber]] isEqual:@"Played"])
{
// This video has been played before. Make another random number and try again
} else {
// This video has not been played before. Set the dictionary value to 'Played' and play the video
}
有更好的方法吗?对于 100 多个视频,当其中 90% 已经播放时,这可能会开始变得有点愚蠢。
最佳答案
创建一个字典副本到 NSMutableDictionary。
由arc4random选择,播放。
从字典中删除它。
NSInteger randomNumber=arc4random();
NSMutableDictionary *playingVideo=[NSMutableDictionary dictionaryWithDictionary:videoDictionary];
//select a video from playingVideo
NSString *key= [NSString stringWithFormat:@"%d", randomNumber];
// ....
//remove from there
[playingVideo removeObjectForKey:key];
编辑 1:
因为这是生成随机数并在字典中搜索。它可能不存在或已经被替换,甚至在 1000 次迭代中也不会生成特定数字。
所以在这种情况下你可以这样做:
NSMutableDictionary *playingVideo=[NSMutableDictionary dictionaryWithDictionary:videoDictionary];
while(playingVideo.count){
NSMutableArray *keys=[playingVideo allKeys];
NSInteger randomNumber=arc4random()%keys.count;
NSString *key=[NSString stringWithFormat:@"%d", keys[key]];
NSString *videoToPlay=playingVideo[key];
//play it
[playingVideo removeObjectForKey:key];
}
关于iphone - 我怎么能不重复地随机播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15476653/