Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find biggest array from a multi dimensional array by count in Swift

I has a multi dimensional array. It can have more than one array in itself. Sometimes maybe 5 or 6. Now I want to get the largest array from my multi dimensional array by using array size. I don't know how to achieve this. Hence i'm posting here. Thanks in advance.

For example:

[["a", "b", "c"], ["d", "e", "f", "g", "h", "i", "j"]]

like image 317
Praveen Kumar Avatar asked Oct 14 '25 12:10

Praveen Kumar


1 Answers

If you are looking for the longest subarray within the given array then you can simply use max(by:) with a comparison using the array count:

let a = [["a", "b", "c"], ["d", "e", "f", "g", "h", "i", "j"], ["k"]]

let longestSubArray = a.max(by: { $0.count < $1.count })!

print(longestSubArray)
// ["d", "e", "f", "g", "h", "i", "j"]

Here I have assumed that a is not empty, otherwise max(by:) will return nil. If that can happen, use optional binding:

if let longestSubArray = a.max(by: { $0.count < $1.count }) {
    print(longestSubArray)
} else {
    print("a is empty")
}

Remark: Array is a RandomAccessCollection and therefore getting its count is a O(1) operation.

If you need both the longest element and its index in the containing array then you can apply the above to a.enumerated():

if let (idx, longest) = a.enumerated().max(by: { $0.element.count < $1.element.count }) {
    print("longest subarray", longest)
    print("at index", idx)
}

If there is more than one subarray with the maximal length then the above solutions will return one of them. @dfri's answer shows how to get all subarrays with the maximal length.

like image 51
Martin R Avatar answered Oct 17 '25 03:10

Martin R