-5

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

编辑

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

4

2 回答 2

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 个数组中随机拆分

希望我正确解释了您的问题,根本没有测试过代码,理论上应该可以工作

于 2013-03-13T12:39:54.290 回答
1

假设您的原始数组有偶数个 Elemnet:

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);

愿这对你有所帮助。

于 2013-03-13T13:20:17.083 回答