[关闭]
@fiy-fish 2015-07-15T20:16:33.000000Z 字数 1116 阅读 1440

day05-03-数组乱序

Objective-c


  1. // day05-03-数组乱序
  2. //
  3. // Created by Aaron on 15/7/7.
  4. // Copyright (c) 2015年 Aaron. All rights reserved.
  5. //
  6. #import <Foundation/Foundation.h>
  7. //0 1 2 3 4
  8. //1 2 3 4
  9. #if 0
  10. int main(int argc, const char * argv[]) {
  11. @autoreleasepool {
  12. NSArray *array = @[@1,@2,@3,@4,@5,@6,@7,@8];
  13. NSMutableArray *array1 = [NSMutableArray arrayWithArray:array];
  14. NSMutableArray *array2 = [NSMutableArray array];
  15. //控制随机的次数
  16. for(int i = 0; i < [array count]; i++)
  17. {
  18. //根据array1来随下标
  19. NSInteger index = arc4random_uniform((int)[array1 count]);
  20. //随出来的对象添加到array2里
  21. [array2 addObject:array1[index]];
  22. [array1 removeObjectAtIndex:index];
  23. }
  24. NSLog(@"%@",array2);
  25. }
  26. return 0;
  27. }
  28. #endif
  29. //1 2 3 4 5
  30. #if 0
  31. int main()
  32. {
  33. NSMutableArray *array = [NSMutableArray arrayWithArray:@[@1,@2,@3,@4,@5]];
  34. //控制随机的对象和哪一个元素交换
  35. for(int i = 0; i < [array count]; i++)
  36. {
  37. NSInteger index = arc4random_uniform((int)[array count]-i)+i;
  38. [array exchangeObjectAtIndex:i withObjectAtIndex:index];
  39. }
  40. NSLog(@"%@",array);
  41. }
  42. #endif
  43. #if 0
  44. int main()
  45. {
  46. NSMutableArray *array = [NSMutableArray arrayWithArray:@[@1,@2,@3,@4,@5]];
  47. for(int i = 0; i < [array count]-1; i++)
  48. {
  49. for(int j = i+1; j < [array count]; j++)
  50. {
  51. if(arc4random_uniform(2))
  52. {
  53. [array exchangeObjectAtIndex:i withObjectAtIndex:j];
  54. }
  55. }
  56. }
  57. NSLog(@"%@",array);
  58. }
  59. #endif
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注