Search This Blog

Monday, July 2, 2018

iOS Swift. How to calculate the mean and median of an array

Theory

Given an unsorted array on integer elements. Calculate mean and median for this array.
Let's define what is a mean and what is median.

Mean of an array = (sum of all elements) / (number of elements)

For correctly calculate median of the array we need to sort array first.
Median of a sorted array  depends on count of elements in array: even or odd.
  • If count of elements is odd then median is middle element.
  • If count of elements is event then median is average of middle two elements. 

Calculate Mean of the array

Calculate mean of the array is pretty easy task. We just cum all elements of array and then divide this sum by count of elements. One thing to notice, for calculating sum of elements we can use reduce function.
func calculateMean(array: [Int]) -> Double {
    
    // Calculate sum ot items with reduce function
    let sum = array.reduce(0, { a, b in
        return a + b
    })
    
    let mean = Double(sum) / Double(array.count)
    return Double(mean)
}

calculateMean(array: [1, 4, 5, 6, 7, 12, 14, 18, 19, 20, 22, 24])
// 12.66666666666667
For more handy usage we can create extension with calculated property mean.

Extension for Array Type 
extension Array where Element == Int {
    
    var mean: Double {
        let sum = self.reduce(0, { a, b in
            return a + b
        })
        
        let mean = Double(sum) / Double(self.count)
        return Double(mean)
    }
}

[1, 4, 5, 6, 7, 12, 14, 18, 19, 20, 22, 24].mean
// 12.66666666666667

Calculate Median of the array

For calculate median of the array we need to sort array first. Then, calculate the median value,  depending on whether the number is even or odd.
func calculateMedian(array: [Int]) -> Double {
    // Array should be sorted
    let sorted = array.sorted()
    let length = array.count
    
    // handle when count of items is even
    if (length % 2 == 0) {
        return (Double(sorted[length / 2 - 1]) + Double(sorted[length / 2])) / 2.0
    }
    
    // handle when count of items is odd
    return Double(sorted[length / 2])
}

calculateMedian(array: [1, 2, 3, 4, 5, 6, 7, 8, 9]) // 5
// odd numbers of items, so median = 5

calculateMedian(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // 5.5
// even numbers of items, so median = (5 + 6) / 2 = 5.5
For more handy usage we can create extension with calculated property median.

Extension for Array Type
extension Array where Element == Int {
    
    var median: Double {
        let sorted = self.sorted()
        let length = self.count
        
        if (length % 2 == 0) {
            return (Double(sorted[length / 2 - 1]) + Double(sorted[length / 2])) / 2.0
        }
        
        return Double(sorted[length / 2])
    }
}

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].median // 5.5
[1, 2, 3, 4, 5, 6, 7, 8, 9].median // 5

Source Code

Source code for this post could be found here on GitHub.

4 comments:

  1. Your article is one of its kind which explained every bit of Custom Build Website. looking for further valuable articles from you

    ReplyDelete
  2. I've read your post thank you for sharing this post. It is very informative post. keep sharing waiting for another.
    -Custom Web Design

    ReplyDelete
  3. Thank you very much for bringing this to my attention. Your blog is chock-full of useful information. I'd have no idea unless I read that. I'll return for more excellent content. Best wishes and best of success to you. Best Custom Websites

    ReplyDelete
  4. Thank you for writing this quality informational content.Your writing technique is impressive and enjoyable to read. I'll come back for more fantastic material.
    Best wishes, and good luck.
    Custom Build Website

    ReplyDelete