随机整数循环

时间:2013-11-04 13:28:16

标签: ios loops random int repeat

我正在制作播放歌曲的应用。我希望每按一个按钮播放一首随机歌曲。我目前有:

-(IBAction)currentMusic:(id)sender {
NSLog(@"Random Music");
int MusicRandom = arc4random_uniform(2);
switch (MusicRandom) {
    case 0:
        [audioPlayerN stop];
        [audioPlayer play];
        break;
    case 1:
        [audioPlayer stop];
        [audioPlayerN play];
        break;

但我已尝试过:

- (IBAction)randomMusic:(id)sender {
NSLog(@"Random Music");




NSMutableArray * numberWithSet = [[NSMutableArray alloc]initWithCapacity:3];

int randomnumber = (arc4random() % 2)+1;



while ([numberWithSet containsObject:[NSNumber numberWithInt:randomnumber]])
{
    NSLog(@"Yes, they are the same");
    randomnumber = (arc4random() % 2)+1;
}

[numberWithSet addObject:[NSNumber numberWithInt:randomnumber]];




NSLog(@"numberWithSet : %@ \n\n",numberWithSet);
switch (randomnumber) {
    case 1:
        [audioPlayerN stop];
        [audioPlayer play];
        NSLog(@"1");
        break;
    case 2:
        [audioPlayer stop];
        [audioPlayerN play];

        NSLog(@"2");
        break;
    default:
        break;

}
}

所有这些都有效,但事实是,即使我要添加更多歌曲,他们也会重复。我想要一个不会重复的随机代码。喜欢随机播放歌曲1,歌曲2,歌曲3,歌曲4和歌曲5,并且当播放所有歌曲时重新开始。像一个循环。但是我现在的代码就像是歌曲1,歌曲1,歌曲2,歌曲1,歌曲2等等......除了播放所有歌曲之外,还有什么方法可以不重复这些歌曲吗?非常感谢你。

2 个答案:

答案 0 :(得分:2)

您想要生成随机排列。

选项1

帽子提示@Alexander采用这种更简单的方法......

if(![songsToPlay count])
    [songsToPlay addObjectsFromArray:songList];

int index = arc4random_uniform([songsToPlay count]);
playSong(songsToPlay[index]);
[songsToPlay removeObjectAtIndex:index];

快速解释:

  • NSMutableArray *songsToPlay:存储此轮尚未播放的歌曲列表。内容可以是以下类型:
    • NSString,存储文件名
    • NSNumber,存储歌曲索引
  • NSArray *songList:存储您要播放的所有歌曲的列表。内容应与songsToPlay的类型相同。也可以是NSMutableArray
  • playSong(id songToPlay):停止当前所有歌曲并播放songToPlay。您需要编写此函数,因为它取决于您的实现。

选项2

使用Knuth shuffles是另一种方法:

unsigned permute(unsigned permutation[], unsigned n)
{
    unsigned i;
    for (i = 0; i < n; i++) {
        unsigned j = arc4random_uniform(i);
        permutation[i] = permutation[j];
        permutation[j] = i;
    }
}

每次想要随机播放歌曲时都要调用该函数:

int permutation[NUM_SONGS];

// I'm using a while loop just to demonstrate the idea.
// You'll need to adapt the code to track where you are
// in the permutation between button presses.
while(true) {
    for(int i = 0; i < NUM_SONGS; ++i)
        permutation[i] = i;

    permute(permutation, NUM_SONGS);

    for(int i = 0; i < NUM_SONGS; ++i) {
        int songNum = permutation[i];
        playSong(songNum);
    }
    waitForButtonPress();
}

答案 1 :(得分:1)

首先,你只听到2首歌曲,因为你的randomnumber代只限于2个值。

对于另一个问题,您可以创建一个随机放置轨道的可变数组,并删除每个播放的元素。当计数达到0时,只需按随机顺序开始播放曲目。

相关问题