首页 \ 问答 \ 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 ...

将一个字符数组转换为一个整数数组(Convert an array of chars to an array of integers)

只需将char转换为一个string : for (int i = 0; i < array.Length; i++) { sequence[i] = Convert.ToInt32(array[i].ToString()); } 但是,当然,你可以在一个linq查询中完成这一切: char[] array = {'1', '2', '3', '4'}; int[] sequence = array.Select(c => Convert.ToInt32(c.ToString())). ...

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传递到Objective-C(Pass array/object from Javascript to Objective-C)

只是想到一个工作正常的解决方法(尽管它仍然是一种解决方法 ): 在JS中: ObjC.someFunction_(JSON.stringify([1,2,3])); 在Objective-C中: - (void)someFunction:(NSString*)arrStr { NSArray* arr = [NSJSONSerialization JSONObjectWithData:[arrStr dataUsingEncoding:NSUTF8StringEncoding] ...

动态舍入Objective-C中的数字(Dynamicaly rounding numbers in Objective-C)

这是我的解决方案: int roundMostSignificant(float input) { NSNumber *number = [NSNumber numberWithFloat:input]; static NSNumberFormatter *formatter = nil; if (!formatter) { formatter = [NSNumberFormatter new]; [formatter setMin ...

什么是Objective-C相当于一个空的Swift OptionSet?(What is the Objective-C equivalent to an empty Swift OptionSet?)

创建Swift的OptionSet是为了使位掩码更加舒适。 在Swift中,你将组合值拼写成一个集合; 在Objective-C中,它是一个用位运算符构建的整数值: NSUInteger options = UIViewAnimationOptionLayoutSubviews | UIViewAnimationOptionRepeat | UIViewAnimationOptionCurveEaseOut; 因此,相当于空OptionSet的Objective-C实际上只是0。 Swift's ...

查找数组中输入数字的中位数(To find median of numbers input in an array)

您的代码中存在问题: 您将转换后的数字存储到数组的第一个元素。 i应该在while循环之外初始化。 sortednum[i] = *sort(&num[i], stringlen(numbers)); 没有意义: stringlen(numbers)用字符计算输入字符串的长度,但是这个输入字符串被strtok()截断,并且它无论如何都与sort函数无关,它需要int数组中的元素数量。 您应该将值存储在int数组的末尾,并在存储所有值后对该数组进行排序。 #define TRUE 1; 不正确: T ...

将NSArray转换为Objective-C中的NSString(Convert NSArray to NSString in Objective-C)

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""]; NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];

相关文章

更多

最新问答

更多
  • Android宽度:100%修复(网站接管问题)(Android width:100% fix (website takeover issue))
  • C ++函数/方法设计的良好实践(Good practice in C++ function/method design)
  • 计算其他表中不存在的所有记录 - SQL查询(Count all records that does not exist to other table - SQL Query)
  • 为什么我要用JPA共享ID?(Why do I get shared Ids with JPA?)
  • asp.net - 如何显示来自html格式的数据行的字段(asp.net - how to display a field from data row that is in html format)
  • 我们如何使用ActiveRecord从连接表中删除行?(How can we delete rows from a join table by using ActiveRecord?)
  • ng-class搞乱了类的顺序(ng-class messing with the order of classes)
  • oracle 12g无效数字错误(oracle 12g invalid number error)
  • 更改ng-src值onclick(Change ng-src value onclick)
  • 如何在android中自动添加自定义依赖项以创建新项目?(How to add custom dependencies automatically in android for ever a new project is created?)
  • datetime函数在PHP中(datetime function in php)
  • 在javascript中获取会话数组的值(in javascript get the value of a session array)
  • 如何在UTF8中编译LaTeX?(How can I compile LaTeX in UTF8? [closed])
  • Rspec:“array.should == another_array”,但不用担心订单(Rspec: “array.should == another_array” but without concern for order)
  • Logcat错误:无法在android片段中加载视图(Logcat error: unable to load view in android fragments)
  • JavaFX的。(JavaFX. Adding items to the list in different threads is not working)
  • 从GDATA日历资源迁移到Google Calendar Resource api(Migrate from GDATA calendar resource to Google Calendar Resource api)
  • SSRS 2008 - 以零情景处理分割(SSRS 2008 - Dealing with division by zero scenarios)
  • 我如何以编程方式添加一个listView列标题的点击事件(How can I add a listView column header a click event programmatically)
  • Wxpython:无法检索有关列表控件项XXX的信息(Wxpython: Couldn't retrieve information about list control item XXX)
  • 使用Tortoise SVN在SVN存储库中移动目录(Move Directory across SVN repository using Tortoise SVN)
  • 天蓝色服务结构集群中的web api无状态服务是否在一段时间不活动后进入休眠状态?(Do web api stateless services in azure service fabric cluster go to sleep after a period of inactivity?)
  • 我可以设置intelliJ来突出显示PHP编码风格吗?(Can I set intelliJ to highlight php coding style?)
  • 用javafx创建一个Truetype字体文件(Creating a Truetype Font file with javafx)
  • Spring ftp配置错误(Spring ftp configuration is wrong)
  • 使用gsub去除多个字符(Using gsub to strip multiple characters)
  • 续订推送证书并保持当前的App Store App正常工作(Renew Push certificate and keep current App Store App working)
  • js:ES5和ES6之间关于'this'关键字用法的一个令人困惑的观点(js: one confusing point about 'this' keyword usage between ES5 and ES6)
  • window.onload vs $(document).ready()(window.onload vs $(document).ready())
  • 在Swift中,如何声明一个符合一个或多个协议的特定类型的变量?(In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?)