Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the most frequent value of an array

I have an Array of numbers and I want to know which number is most frequent in this array. The array sometimes has 5-6 integers, sometimes it has 10-12, sometimes even more - also the integers in the array can be different. So I need a function which can work with different lengths and values of an array.

One example:

myArray = [0, 0, 0, 1, 1]

Another example:

myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]

Now I am searching for a function which gives out 0 (in the first example) as Integer, as it is 3 times in this array and the other integer in the array (1) is only 2 times in the array. Or for the second example it would be 4.

It seems pretty simple, but I cannot find a solution for this. Found some examples in the web, where the solution is to work with dictionaries or where the solution is simple - but I cannot use it with Swift 3 it seems...

However, I did not find a solution which works for me. Someone has an idea how to get the most frequent integer in an array of integers?

like image 661
aignetti Avatar asked Jul 16 '16 22:07

aignetti


People also ask

How do you find the most frequent value in an array?

Steps to find the most frequency value in a NumPy array:Create a NumPy array. Apply bincount() method of NumPy to get the count of occurrences of each element in the array. The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).

How do you find the most common number in an array in Python?

Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.

How do you find the second most frequent element in an array?

Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string. A simple solution is to start from the first character, count its occurrences, then second character, and so on.

How to find the most frequent element in an array?

Given an array X [] of size n, write a program to find the most frequent element in the array, i.e. the element which occurs the maximum number of times. It is assumed that at least one element is repeated. If there are multiple elements with maximum frequency, return the smallest of them.

How to find the most frequent value in a NumPy array?

To find the most frequent value in a NumPy array we can use the bincount (~) method together with argmax (~). bincounts (~) returns an array with the number of occurrences of each number in the range 0 ~ largest number in the array

What is the maximum number of times 1 appears in array?

Input : arr [] = {1, 3, 2, 1, 4, 1} Output : 1 1 appears three times in array which is maximum frequency. Input : arr [] = {10, 20, 10, 20, 30, 20, 20} Output : 20 Recommended: Please try your approach on {IDE} first, before moving on to the solution. A simple solution is to run two loops. The outer loop picks all elements one by one.

How to find the maximum number of times an element appears?

Given an array, find the most frequent element in it. If there are multiple elements that appear maximum number of times, print any one of them. Input : arr [] = {1, 3, 2, 1, 4, 1} Output : 1 1 appears three times in array which is maximum frequency.


2 Answers

You can also use the NSCountedSet, here's the code

let nums = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]
let countedSet = NSCountedSet(array: nums)
let mostFrequent = countedSet.max { countedSet.count(for: $0) < countedSet.count(for: $1) }

Thanks to @Ben Morrow for the smart suggestions in the comments below.

like image 200
Luca Angeletti Avatar answered Oct 26 '22 18:10

Luca Angeletti


let myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]

// Create dictionary to map value to count   
var counts = [Int: Int]()

// Count the values with using forEach    
myArray.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }

// Find the most frequent value and its count with max(by:)    
if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
    print("\(value) occurs \(count) times")
}

Output:

4 occurs 4 times

Here it is as a function:

func mostFrequent(array: [Int]) -> (value: Int, count: Int)? {
    var counts = [Int: Int]()

    array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }

    if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
        return (value, count)
    }

    // array was empty
    return nil
}

if let result = mostFrequent(array: [1, 3, 2, 1, 1, 4, 5]) {
    print("\(result.value) occurs \(result.count) times")    
}
1 occurs 3 times

Update for Swift 4:

Swift 4 introduces reduce(into:_:) and default values for array look ups which enable you to generate the frequencies in one efficient line. And we might as well make it generic and have it work for any type that is Hashable:

func mostFrequent<T: Hashable>(array: [T]) -> (value: T, count: Int)? {

    let counts = array.reduce(into: [:]) { $0[$1, default: 0] += 1 }

    if let (value, count) = counts.max(by: { $0.1 < $1.1 }) {
        return (value, count)
    }

    // array was empty
    return nil
}

if let result = mostFrequent(array: ["a", "b", "a", "c", "a", "b"]) {
    print("\(result.value) occurs \(result.count) times")
}
a occurs 3 times
like image 32
vacawama Avatar answered Oct 26 '22 17:10

vacawama