zoukankan      html  css  js  c++  java
  • 两种快速打乱NSMutableArray的方法

    1。利用交换

    //  NSMutableArray_Shuffling.h

    #if TARGET_OS_IPHONE
    #import <UIKit/UIKit.h>
    #else
    #include <Cocoa/Cocoa.h>
    #endif

    // This category enhances NSMutableArray by providing
    // methods to randomly shuffle the elements.
    @interface NSMutableArray (Shuffling)
    - (void)shuffle;
    @end


    //  NSMutableArray_Shuffling.m

    #import "NSMutableArray_Shuffling.h"

    @implementation NSMutableArray (Shuffling)

    - (void)shuffle
    {
       
    NSUInteger count = [self count];
       
    for (NSUInteger i = 0; i < count; ++i) {
           
    // Select a random element between i and end of array to swap with.
           
    int nElements = count - i;
           
    int n = (random() % nElements) + i;
           
    [self exchangeObjectAtIndex:i withObjectAtIndex:n];
       
    }
    }

    @end

    2。利用排序
    int randomSort(id obj1, id obj2, void *context ) {
           
    // returns random number -1 0 1
       
    return (random()%3 - 1);    
    }

    - (void)shuffle {
           
    // call custom sort function
       
    [puzzles sortUsingFunction:randomSort context:nil];

       
    // show in log how is our array sorted
           
    int i = 0;
       
    for (Puzzle * puzzle in puzzles) {
           
    NSLog(@" #%d has index %d", i, puzzle.index);
            i
    ++;
       
    }
    }

    log output:

     #0 has index #6
     
    #1 has index #3
     
    #2 has index #9
     
    #3 has index #15
     
    #4 has index #8
     
    #5 has index #0
     
    #6 has index #1
     
    #7 has index #4
     
    #8 has index #7
     
    #9 has index #12
     
    #10 has index #14
     
    #11 has index #16
     
    #12 has index #17
     
    #13 has index #10
     
    #14 has index #11
     
    #15 has index #13
     
    #16 has index #5
     
    #17 has index #2

    you may as well compare obj1 with obj2 and decide what you want to return possible values are:

    • NSOrderedAscending = -1
    • NSOrderedSame = 0
    • NSOrderedDescending = 1

  • 相关阅读:
    spring(2)
    Android之滑动按钮实现Demo
    spring(1)
    spring(4)
    Android之ImageSwitch控件
    使用非阻塞ServerSocketChannel、SocketChannel代替ServerSocket和Socket
    Android之界面刷新(invalidate和postInvalidate使用)
    Android之改变控件的背景及形态
    Android之获得内存剩余大小与总大小
    OpenCV中矩阵的归一化
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/2458484.html
Copyright © 2011-2022 走看看