Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting unique items in array. (Swift)

How do you count the amount of unique items in an Array?

Example:

let array:Array<Int> = [1,3,2,4,6,1,3,2]

Count function: array.count will give 8

but I want to count unique items and this will give 5

like image 219
Petri Avatar asked Jan 09 '15 14:01

Petri


People also ask

How to count unique values in array Swift?

If you are interested in how many of each item you have, you can use a dictionary to count the items: var counts = [Int:Int]() for item in array { counts[item] = (counts[item] ?? 0) + 1 } print(counts) // prints "[6: 1, 2: 2, 3: 2, 1: 2, 4: 1]" print(counts. count) // prints "5" print("There are \(counts[1] ??

What is reduce in Swift?

reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.


2 Answers

As of Swift 1.2, Swift has a native Set type. Use the Set constructor to create a set from your array, and then the count property will tell you how many unique items you have:

let array = [1,3,2,4,6,1,3,2]

let set = Set(array)
print(set.count)  // prints "5"

For Swift 1.1 and earlier:

Turn your array into an NSSet:

let array = [1,3,2,4,6,1,3,2]

let set = NSSet(array: array)
println(set.count)  // prints "5"

You can read more about it here.


If you are interested in how many of each item you have, you can use a dictionary to count the items:

var counts = [Int:Int]()

for item in array {
    counts[item] = (counts[item] ?? 0) + 1
}

print(counts)        // prints "[6: 1, 2: 2, 3: 2, 1: 2, 4: 1]"
print(counts.count)  // prints "5"
print("There are \(counts[1] ?? 0) ones.")    // prints "There are 2 ones."
print("There are \(counts[7] ?? 0) sevens.")  // prints "There are 0 sevens."
like image 114
vacawama Avatar answered Oct 24 '22 09:10

vacawama


implement the function countDistinct(numbers: [Int]) to return the number of distinct elements in the array. NSSet documentation for Swift https://developer.apple.com/documentation/foundation/nsset

func countDistinct(numbers: [Int]) -> Int {
    let array:Array<Int> = numbers
    let count = NSSet(array: array).count
    return count
}

print(countDistinct(numbers: [20, 10, 10, 30, 20]))
like image 40
Kenneth Chang Avatar answered Oct 24 '22 07:10

Kenneth Chang