首页 \ 问答 \ Objective-C - 将数组数组转换为数字顺序的数组(Objective-C – Transform an array of numbers to arrays with numbers in sequence)

Objective-C - 将数组数组转换为数字顺序的数组(Objective-C – Transform an array of numbers to arrays with numbers in sequence)

有没有一种简单的方法可以将数字数组转换为数字顺序的数组?

NSArray *numbers = @[@1,@2,@5,@3];

// Transformed arrays
//NSArray *numbersInSequence = @[@1,@2,@3];
//NSArray *numbersInSequence2 = @[@5];

编辑:

我在Richard的答案中修改了代码以使其工作。

NSArray *arraysBySplittingNumbersInOrder(NSArray *input) {

// sort 'input'
input = [input sortedArrayUsingSelector:@selector(compare:)];

NSMutableArray *results = [NSMutableArray array];

if (input.count) {

    int start = 0;
    int last = INT_MIN;

    for (int i = 0; i < input.count; i++) {

        BOOL lastItem = i == input.count - 1;

        // The first item of the array
        if (i == 0) {

            if (lastItem) {
                [results addObject:input];
                break;
            }

            last = [input[i] intValue];
            continue;
        }

        int cur = [input[i] intValue];

        if (cur != last + 1) {

            // pull out the next array
            [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];

            start = i;
        }

        // The last item of the array
        if (lastItem) {

            [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start + 1)]];            
        }

        last = cur;
    }
}

return results;
}

Is there an easy way to transform an array of numbers to an arrays with the numbers in sequence?

NSArray *numbers = @[@1,@2,@5,@3];

// Transformed arrays
//NSArray *numbersInSequence = @[@1,@2,@3];
//NSArray *numbersInSequence2 = @[@5];

EDIT:

I modified the code in Richard's answer to get it to work.

NSArray *arraysBySplittingNumbersInOrder(NSArray *input) {

// sort 'input'
input = [input sortedArrayUsingSelector:@selector(compare:)];

NSMutableArray *results = [NSMutableArray array];

if (input.count) {

    int start = 0;
    int last = INT_MIN;

    for (int i = 0; i < input.count; i++) {

        BOOL lastItem = i == input.count - 1;

        // The first item of the array
        if (i == 0) {

            if (lastItem) {
                [results addObject:input];
                break;
            }

            last = [input[i] intValue];
            continue;
        }

        int cur = [input[i] intValue];

        if (cur != last + 1) {

            // pull out the next array
            [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];

            start = i;
        }

        // The last item of the array
        if (lastItem) {

            [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start + 1)]];            
        }

        last = cur;
    }
}

return results;
}

原文:https://stackoverflow.com/questions/13584596
更新时间:2019-06-21 03:06

最满意答案

这是一个相当简单的解决方案:

NSArray *arraysBySplittingNumbersInOrder(NSArray *input)
{
    // sort 'input'
    input = [input sortedArrayUsingSelector:@selector(compare:)];

    NSMutableArray *results = [NSMutableArray array];

    if (input.count)
    {
        int start = 0;
        int last = INT_MIN;

        for (int i = 0; i <= input.count; i++)
        {
            if (i == 0)
            {
                last = [input[i] intValue];
                continue;
            }
            if (i == input.count)
            {
                if (i != start + 1)
                {
                    [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
                    continue;
                }
            }

            int cur = [input[i] intValue];

            if (cur != last + 1)
            {
                // pull out the next array
                [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
                start = i;
            }

            last = cur;
        }
    }

    return results;
}

int main()
{
    NSArray *input = @[ @1, @3, @4, @7, @8, @12, @13, @14 ];

    NSLog(@"%@", input);
    NSLog(@"%@", arraysBySplittingNumbersInOrder(input));
}

输出:

2012-11-27 07:55:04.609 TestProj[35890:303] (
    1,
    3,
    4,
    7,
    8,
    12,
    13,
    14
)
2012-11-27 07:55:04.611 TestProj[35890:303] (
        (
        1
    ),
        (
        3,
        4
    ),
        (
        7,
        8
    ),
        (
        12,
        13,
        14
    )
)

Here's a rather simple solution:

NSArray *arraysBySplittingNumbersInOrder(NSArray *input)
{
    // sort 'input'
    input = [input sortedArrayUsingSelector:@selector(compare:)];

    NSMutableArray *results = [NSMutableArray array];

    if (input.count)
    {
        int start = 0;
        int last = INT_MIN;

        for (int i = 0; i <= input.count; i++)
        {
            if (i == 0)
            {
                last = [input[i] intValue];
                continue;
            }
            if (i == input.count)
            {
                if (i != start + 1)
                {
                    [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
                    continue;
                }
            }

            int cur = [input[i] intValue];

            if (cur != last + 1)
            {
                // pull out the next array
                [results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
                start = i;
            }

            last = cur;
        }
    }

    return results;
}

int main()
{
    NSArray *input = @[ @1, @3, @4, @7, @8, @12, @13, @14 ];

    NSLog(@"%@", input);
    NSLog(@"%@", arraysBySplittingNumbersInOrder(input));
}

Output:

2012-11-27 07:55:04.609 TestProj[35890:303] (
    1,
    3,
    4,
    7,
    8,
    12,
    13,
    14
)
2012-11-27 07:55:04.611 TestProj[35890:303] (
        (
        1
    ),
        (
        3,
        4
    ),
        (
        7,
        8
    ),
        (
        12,
        13,
        14
    )
)
2012-11-27

相关问答

更多

在Objective-C中舍入数字(Rounding numbers in Objective-C)

感谢大家的指针,我已经设法提出了一个解决方案: float roundedValue = round(2.0f * number) / 2.0f; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setMaximumFractionDigits:1]; [formatter setRoundingMode: NSNumberFormatterRoundDown]; NSString *numb ...

将快速变量参数暴露给Objective-C(Expose swift variadic parameter to Objective-C)

您可以将C中的可变参数函数桥接到Swift,而不是另一个方向。 请参阅将Swift与Cocoa和Objective-C一起使用:与C API交互:Variadic函数以获取更多信息。 但这并不难以手工实施。 只需创建方法的数组版本并将所有可变形式传递给它。 Swift中的第一个: public class Test: NSObject { convenience public init(buttons: String...) { self.init(buttonArray

使用函数式编程将嵌套的字符串数组转换为嵌套的双精度数组(Convert nested array of strings into nested array of doubles using functional programming)

让我们尝试解决问题。 Array有一个map()方法 /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T] 它通过转换每个元素和flatMap()方法创建一个新数组 /// Returns an

Objective-C中的Int数组(Int arrays in Objective-C)

memcpy(b, a, sizeof(int) * 4); memcpy(b, a, sizeof(int) * 4);

将项目从objective-c转换为swift后,无法同时满足约束条件(Unable to simultaneously satisfy constraints after transform project from objective-c to swift)

Rob Mayoff先生是对的:我的Swift项目与Objective-C项目有不同的约束。 :-( Mr. Rob Mayoff was right: my Swift project has different constraints than my Objective-C project. :-(

订购数组中的数字(Ordering numbers in an array)

您可以使用modulo( % )运算符来获取正确的索引: for (i = 0; i < 10; i++){ B[ (i + n) % 10 ] = A[i]; } 我直接使用了10 。 通常,如果数组的大小小于数组的大小,则应使用sizeof(B)或数组中的实际元素数。 You can use modulo (%) operator to get the correct indexing: for (i = 0; i < 10; i++){ B[ (i

Objective-C:查找字符串中的数字(Objective-C: Find numbers in string)

以下是基于NSScanner的解决方案: // Input NSString *originalString = @"This is my string. #1234"; // Intermediate NSString *numberString; NSScanner *scanner = [NSScanner scannerWithString:originalString]; NSCharacterSet *numbers = [NSCharacterSet characterSetWi ...

来自数字字符串的Javascript数组(Javascript array from string of numbers)

通过在字符串上调用split()来创建数组: var visList = '1234,5678,9' var visListArray = visList.split(","); 您不能替换看起来像实际代码的代码的字符串。 虽然这可行: var visListArray = new Array(1234,5678,9); 你的不是因为字符串不被Array构造函数解释为3个逗号分隔的参数,它被解释为一个字符串。 编辑:请注意,在字符串上调用split()一个字符串数组。 如果需要数组数组,

相关文章

更多

最新问答

更多
  • 使用javascript为用户延迟加载内容的更好方法是什么?(What is a better way to lazy load content for users with javascript?)
  • 如何修复无法将类型的值...转换为预期的参数类型inout _(How to fix Cannot convert value of type … to expected argument type inout _)
  • 从哪里开始解析JSON?(Where to start with parsing JSON?)
  • Mail.php不适用于.htaccess(Mail.php doesn't work with .htaccess)
  • 使用htaccess设置子域(Setting subdomains using htaccess)
  • mod_pagespeed和java应用服务器(mod_pagespeed and java app servers)
  • Win32:如何崩溃?(Win32: How to crash?)
  • FFmpeg中RGB到YUV转换的错误(Error in RGB to YUV conversion in FFmpeg)
  • 如何在Android中首次打开应用时创建弹出窗口?(How to create pop-up when first open app in Android?)
  • 通过动态传递表名和列名来反转COLUMN DATA(Reversing COLUMN DATA by dynamically passing table name and Column Name)
  • 如何计算C#中ICollection中有多少元素?(How can I count how many elements are in an ICollection in C#)
  • 从pg-promise查询中获得结果(get result out of a pg-promise query)
  • 使用管理器注册一个类,然后调用子类重写方法(Register a class with a manager, then call the sub classes overridden methods)
  • 传递&在查询字符串中(Passing & in query string)
  • 谷歌浏览器打印预览不会第一次加载页面(google chrome print preview does not load the page the first time)
  • FsLexYacc:Tests / MiniProject“在.fsproj中导入错误”(FsLexYacc : Tests/MiniProject “incorrect Import in .fsproj”)
  • 创建一个模型方法,计算用户的帖子并在rspec(Rails)中测试?(Create a model method that counts a user's posts and test in rspec (Rails)?)
  • 记录线程的奇怪行为(Strange behaviour of logging thread)
  • 移动数组中的索引(Moving indices in an array)
  • MVC 5 - > MVC 5.1迁移。(MVC 5 -> MVC 5.1 Migration. Intellisense issues)
  • 使用函数在z3中创建列表(Creating List in z3 using function)
  • 如何进行html随机重定向(How to make a html random redirect)
  • 角度js:使用角度过滤器分割日期,月份和时间(Angular js: spliting date,month and time using angular filter)
  • 将所有模块导入一个文件夹,并按其属性之一使用它们(Import all modules in one folder and use them by one of its attributes)
  • 只需要在git的当前分支上获得合并列表(Just get list of merge happened on my current branch in git)
  • React-Native导入库并在多个组件中可用(React-Native import a library and make available in multiple components)
  • 如何使用jQuery为固定(偏移)位置设置div动画?(How to animate div for a fixed (offset) position using jQuery?)
  • operator ==和vector confusion(operator== and vector confusion)
  • 如何获取所选图像映射alt值?(How to get selected image map alt value?)
  • 在角度,如何使用取消用户事件的美元间隔,如页面更改?(In angular, how to use cancel an $interval on user events, like page change?)