Int数组的数组。仅按顺序存储重复项 [英] Arrays of Int arrays. Storing duplicates in order only

查看:77
本文介绍了Int数组的数组。仅按顺序存储重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存储一个Int数组的数组以用于有序重复(位于Array中)。

I need to store an array of Int array for ordered duplicates (which are in a Array).

示例:


  • 给出数组:

    mainArray = [7、7、3、2、2、1、1、7、5、5]

  • Given array:
    mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

现在我需要创建一个二维数组int Array。

示例:

Now i need to create a 2D array of int Array.
Example:

Array [][] = [
               [7, 7], 
               [3], 
               [2, 2, 2], 
               [1], 
               [7],
               [5, 5]
             ]

此处我拥有的是:

for var i = 0; i < val.count; i++ {
    var columnArray = Array<Int>()
    for var j in 0...9 {
        if oldNum == val[j]{
            columnArray.append(val[j])
        }
        else {
            array.append(columnArray);
            //j += 1
            break;
        }
        oldNum = val[j];
        j += 1
    }
}


推荐答案

您可以使用 reduce 方法。

let result = numbers.reduce([[Int]]()) { (var result, num) -> [[Int]] in
    if var lastSequence = result.last where lastSequence.first == num {
        result[result.count-1].append(num)
    } else {
        result.append([num])
    }
    return result
}



减少工作如何?



减少确实将闭包中的逻辑应用于空的2D整数数组( [[Int]] )和数字的第一个Elm。

How does the reduce work?

reduce does apply the logic in the closure to an empty 2D array of integers ([[Int]]) and the first elm of numbers.

然后将其再次应用于上一次迭代的结果和第二个整数数组...等等。

Then it is applied again to the result of the previous iteration and the second array of integers... and so on.

if 确实检查最后一个数组中的数字是否添加到结果中等于当前检查的整数。如果是这样,则将整数添加到该数组。

The if does check whether the number in the last array added to the result is equals to the integer currently examined. If so that integer is added to that array.

否则,将仅包含新整数的新数组添加到结果中。

Otherwise a new array containing only the new integer is added to the result.

[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]

这篇关于Int数组的数组。仅按顺序存储重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆