计入多维数组

时间:2016-12-15 09:32:05

标签: ios objective-c

你怎么算这个阵列?

NSArray *sortThisArray = @[@{@"numbers":@[@"One",@"Two"]},
                               @{@"numbers":@[@"Two",@"One"]},
                               @{@"numbers":@[@"One",@"Two",@"Three"]},
                               @{@"numbers":@[@"One",@"Two",@"Three"]},
                               @{@"numbers":@[@"One",@"Two",@"Three",@"Four"]},
                               ];

所需的结果将是:

NSArray *sortedArray =   @[@{@"numbers":@[@"One",@"Two"],
                             @"occures":@(2)},

                             @{@"numbers":@[@"One",@"Two",@"Three"],
                             @"occures":@(2)},

                             @{@"numbers":@[@"One",@"Two",@"Three",@"Four"],
                             @"occures":@(1)},
                          ];

我已尝试使用NSCountedSetcountForObject,但结果不准确。它似乎只计算完全相同的数组。换句话说,具有@[@"Two",@"One"]的数组会被忽略,因为它不是100%等于@[@"One",@"Two"],即使它们具有相同的对象和相同的计数。

2 个答案:

答案 0 :(得分:0)

这应该有效。你必须有一个一致的方法来比较你的数组(像这个例子中的排序或通过将NSArray移动到NSSet)。

NSMutableDictionary<NSArray<NSString *> *, NSNumber *> *valueCount = [NSMutableDictionary dictionary];
for (NSDictionary<NSString *, NSArray<NSString *> *> *value in sortThisArray) {
    NSArray<NSString *> *numberStrings = [value[@"numbers"] sortedArrayUsingSelector:@selector(compare:)];
    valueCount[numberStrings] = @(valueCount[numberStrings].integerValue + 1);
}

NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:valueCount.count];
for (NSArray<NSString *> *key in valueCount) {
    [sortedArray addObject:@{@"numbers": key, @"occures": valueCount[key]}];
}

答案 1 :(得分:-1)

可能是这样的:

 //insertion sort
    #include<iostream>
    #include <ctime>
    using namespace std;
    class insertion{
    public:
        insertion(){} //constructor
        void sort(int a[], int n) { //insertion sort function
            for (int i = 1; i < n; i++) {
                int value = a[i];
                int index = i;
                while (i > 0 && a[i - 1] > value) {
                    a[index] = a[index - 1];
                    index=index-1;
                }
                a[index] = value;
            }
        }

        //display function
        void display(int a[], int n) {
            for (int i = 0; i < n; i++) {
                cout << a[i] << endl;
            }
        }
    };
    void main(){
        insertion ins;
        int a[10];
        int n = 10;
        cout << "Enter the elements:" << endl;
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        unsigned int start = clock(); //measuring time of sort from here
        cout << "waiting for keyhit";
        cin.ignore();
        ins.sort(a, n);
        ins.display(a, n);
        cout << "Time taken in millisecs: " << clock() - start; //to here
        cin.ignore();
    }

*代码未经过测试