如何将列表随机排序为两个列表

时间:2013-03-13 12:30:35

标签: objective-c random

我有一个数组,我想随机将数组中的项目放入两个具有相同大小的列表中我想将这些项目放入两个数组但不确定这是否是最好的主意。除了把它放在数组中,我如何编写for stament或while循环来从数组中获取所有对象并将其放在两个数组或列表中。

修改

我希望将主列表分成两个列表。将一个列表中的项目减半,另一个列表中的项目减半,我希望选择是随机的

2 个答案:

答案 0 :(得分:2)

NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:originalArray copyItems:TRUE];

NSMutableArray *list1 = [[NSMutableArray alloc] init];
NSMutableArray *list2 = [[NSMutableArray alloc] init];
while(temp.count > 0){

    int index1 = arc4random_uniform(temp.count);
    [list1 addObject:[temp objectAtIndex:index1]];
    [temp removeObjectAtIndex:index1];

    if(temp.count != 0){
      int index2 = arc4random_uniform(temp.count);
      [list2 addObject:[temp objectAtIndex:index2]];
      [temp removeObjectAtIndex:index2];
    }
}

现在你将留下2个数组(list1和list2),内容在2个数组上随机分割

希望我正确地解释了你的问题,根本没有对代码进行过测试,应该在理论上工作

答案 1 :(得分:1)

假设您的原始数组具有偶数个元素:

NSMutableArray *list1 = [[NSMutableArray alloc] init];
NSMutableArray *list2 = [[NSMutableArray alloc] init];
NSMutableArray *originalArray = [[NSMutableArray alloc] initWithObjects:@"ssjsf1",@"ssjsf2",@"ssj3sf",@"ssj4sf",@"ss5jsf",@"ssj6sf",@"ssj7sf",@"ssj8sf",@"ssj9sf",@"s10sjsf",@"ss11jsf",@"ss12jsf",@"ss12jsf",@"ss12jsf",nil];
NSMutableArray *temp = [[NSMutableArray alloc] init];
int i =0;
for (i = 0; [temp count] < [originalArray count] ; i++){
    int r = arc4random_uniform([originalArray count]);
    if(!([temp containsObject:[NSNumber numberWithInt:r]]))
    {
        [temp addObject:[NSNumber numberWithInt:r]];
        [list1 addObject:[originalArray objectAtIndex:r]];
         if([originalArray count] % 2 == 0)
        {
            if([list1 count] > ([originalArray count]/2) )
            {
                [list1 removeObjectAtIndex:r];
                [temp removeObject:[NSNumber numberWithInt:r]];
            }
        }
        if([originalArray count] % 2 != 0)
            if([list1 count] > ([originalArray count]/2 + 1) )
            {
                [list1 removeObjectAtIndex:r];
                [temp removeObject:[NSNumber numberWithInt:r]];
            }
    }
    r = arc4random_uniform([originalArray count]);
    if(!([temp containsObject:[NSNumber numberWithInt:r]]))
    {
        [temp addObject:[NSNumber numberWithInt:r]];
        [list2 addObject:[originalArray objectAtIndex:r]];

       if([originalArray count] % 2 == 0)
        {
            if([list2 count] > ([originalArray count]/2) )
            {
                [list1 removeObjectAtIndex:r];
                [temp removeObject:[NSNumber numberWithInt:r]];
            }
        }
        if([originalArray count] % 2 != 0)
            if([list2 count] > ([originalArray count]/2) )
            {
                [list2 removeObjectAtIndex:r];
                [temp removeObject:[NSNumber numberWithInt:r]];
            }
    }
}


 NSLog(@"List1 -- %@ \n List 2 --- %@",list1, list2);

愿这对你有所帮助。