Calculation mode in an array (more than one Mode) - arrays

I have a problem to calculate Mode (most frequent number in an array) in swift.
For example, in this code
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)
}
return nil
}
if let result = mostFrequent(array: [2,2,2,3,4,4,4,5,6]) {
print("\(result.value) is repeated \(result.count) times")
}
Print: 2 is repeated 3 times
I can find the first most frequent number, which is 2 that repeated 3 times. But as you can see if there is another number that also repeated 3 times, i can not see it by using this function.
For example, In my array of numbers, 2 is repeated 3 times and hence is the Mode. But there is two Modes, which is 4 that also repeated 3 times. I want this function show both of modes. Could anyone help me to guide me to how to do it?

You just need to filter your results that are equal to the max count and map their keys:
func mostFrequent(array: [Int]) -> (mostFrequent: [Int], count: Int)? {
var counts: [Int: Int] = [:]
array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
if let count = counts.max(by: {$0.value < $1.value})?.value {
return (counts.compactMap { $0.value == count ? $0.key : nil }, count)
}
return nil
}
if let result = mostFrequent(array: [2, 2, 2, 3, 4, 4, 4, 5, 6]) {
print(result) // "(mostFrequent: [2, 4], count: 3)\n"
}
edit/update:
extension Sequence where Element: Hashable {
var frequency: [Element: Int] { reduce(into: [:]) { $0[$1, default: 0] += 1 } }
var mostFrequent: (mostFrequent: [Element], count: Int)? {
guard let maxCount = frequency.values.max() else { return nil }
return (frequency.compactMap { $0.value == maxCount ? $0.key : nil }, maxCount)
}
}
usage:
let array = [2,2,2,3,4,4,4,5,6]
if let mostFrequent = array.mostFrequent {
print("Most frequent", mostFrequent)
}
This will print:
Most frequent (mostFrequent: [2, 4], count: 3)

Related

Swift Array instance method drop(at: Int)

Array in Swift has several instance methods for excluding elements, such as dropFirst(), dropLast(), drop(while:), etc. What about drop(at:)?
Note: I'd use remove(at:), but the array I'm working with is a let constant.
Note: I'd use remove(at:), but the array I'm working with is a constant.
I wouldn't let that stop you:
extension Array {
func drop(at:Int) -> [Element] {
var temp = self
temp.remove(at: at)
return temp
}
}
let numbers = [1, 2, 3, 4, 5]
print(numbers.drop(at: 2)) // [1, 2, 4, 5]
You can extend RangeReplaceableCollection protocol instead of Array type, this way you can use it on Strings as well:
extension RangeReplaceableCollection {
func drop(at offset: Int) -> SubSequence {
let index = self.index(startIndex, offsetBy: offset, limitedBy: endIndex) ?? endIndex
let next = self.index(index, offsetBy: 1, limitedBy: endIndex) ?? endIndex
return self[..<index] + self[next...]
}
}
var str = "Hello, playground"
str.drop(at: 5) // "Hello playground"
let numbers = [1, 2, 3, 4, 5]
print(numbers.drop(at: 2)) // "[1, 2, 4, 5]\n"
If you would like to accept also String.Index in your method:
extension RangeReplaceableCollection {
func drop(at index: Index) -> SubSequence {
let index = self.index(startIndex, offsetBy: distance(from: startIndex, to: index), limitedBy: endIndex) ?? endIndex
let next = self.index(index, offsetBy: 1, limitedBy: endIndex) ?? endIndex
return self[..<index] + self[next...]
}
}
var str = "Hello, playground"
str.drop(at: 0) // "ello, playground"
str.drop(at: str.startIndex) // "ello, playground"
The only thing I would add to your implementation is a guard statement with a useful error message:
extension Array {
func drop(at index: Int) -> ArraySlice<Element> {
guard indices.contains(index) else {
fatalError("Index out of range")
}
return self[0..<index] + self[(index+1)..<endIndex]
}
func drop(range: CountableRange<Int>) -> ArraySlice<Element> {
guard (indices.lowerBound, range.upperBound) <= (range.lowerBound, indices.upperBound) else {
fatalError("Range is out of the indices bounds")
}
return self[0..<range.lowerBound] + self[range.upperBound..<endIndex]
}
}
let a = [1,2,3]
a.drop(at: 3) //Fatal error: Index out of range
let b = [0,1,2,3,4,5]
b.drop(range: 1..<5) //[0, 5]
return self[0..<index] + self[index+1..<endIndex]
Ugly. Why not use the tools you're given?
extension Array {
func drop(at:Int) -> ArraySlice<Element> {
return prefix(upTo: at) + suffix(from: at+1)
}
}
let arr = [1,2,3,4,5]
let slice = arr.drop(at:2) // [1,2,4,5]
EDIT It seems Apple would prefer you to say (using partial ranges)
return self[..<at] + self[(at+1)...]
but personally I think that's uglier, and after all the methods I suggested are not deprecated or anything.
How about using a Swift extension to add drop(at:) to the Array structure?
extension Array {
func drop(at index: Int) -> ArraySlice<Element> {
precondition(indices.contains(index), "Index out of range")
return self[..<index] + self[(index+1)...]
}
}
It returns a slice of the original array without the element at the specified index.
let numbers = [1, 2, 3, 4, 5]
print(numbers.drop(at: 2))
// Prints "[1, 2, 4, 5]"
Note: You may also want to add drop(at:) to ArraySlice.

Find if sequence of elements exists in array

Is it possible to find if a sequence of elements in an array exists?
Lets take some digits from the Pi,
let piDigits=[3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6,2,6,4,3,3,8,3,2,7,9,5,0,2,8,8,4,1,9,7,1,6,9,3,9,9,3,7,5,1,0,5,8,2,0,9,7,4,9,4,4]
Now, i want to find if, 5 and 9 exist as sequence elements in the array- in this case they do, once, in positions 4 & 5.
Ideally, i wouldn't like to iterate over the array with a loop, i would like something similar to array.contains(element) .
#Bawpotter, the code snippet:
for element in piDigits{ //check every element
if element == 5 { //if element is equal with the element i want
var currentPosition = piDigits.index(of: element) //get the position of that element
if piDigits[currentPosition!+1] == 9 { //if the element at the next position is equal to the other element i want
print("true") // it prints true 7 times, instead of 1!
}
}
}
You can filter your indices where its subsequence elementsEqual is true:
extension Collection where Element: Equatable {
func firstIndex<C: Collection>(of collection: C) -> Index? where C.Element == Element {
guard !collection.isEmpty else { return nil }
let size = collection.count
return indices.dropLast(size-1).first {
self[$0..<index($0, offsetBy: size)].elementsEqual(collection)
}
}
func indices<C: Collection>(of collection: C) -> [Index] where C.Element == Element {
guard !collection.isEmpty else { return [] }
let size = collection.count
return indices.dropLast(size-1).filter {
self[$0..<index($0, offsetBy: size)].elementsEqual(collection)
}
}
func range<C: Collection>(of collection: C) -> Range<Index>? where C.Element == Element {
guard !collection.isEmpty else { return nil }
let size = collection.count
var range: Range<Index>!
guard let _ = indices.dropLast(size-1).first(where: {
range = $0..<index($0, offsetBy: size)
return self[range].elementsEqual(collection)
}) else {
return nil
}
return range
}
func ranges<C: Collection>(of collection: C) -> [Range<Index>] where C.Element == Element {
guard !collection.isEmpty else { return [] }
let size = collection.count
return indices.dropLast(size-1).compactMap {
let range = $0..<index($0, offsetBy: size)
return self[range].elementsEqual(collection) ? range : nil
}
}
}
[1, 2, 3, 1, 2].indices(of: [1,2]) // [0,3]
[1, 2, 3, 1, 2].ranges(of: [1,2]) // [[0..<2], [3..<5]]
If you only need to check if a collection contains a subsequence:
extension Collection where Element: Equatable {
func contains<C: Collection>(_ collection: C) -> Bool where C.Element == Element {
guard !collection.isEmpty else { return false }
let size = collection.count
for i in indices.dropLast(size-1) where self[i..<index(i, offsetBy: size)].elementsEqual(collection) {
return true
}
return false
}
}
[1, 2, 3].contains([1, 2]) // true
A very simple implementation using linear search:
let piDigits: [Int] = [3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6,2,6,4,3,3,8,3,2,7,9,5,0,2,8,8,4,1,9,7,1,6,9,3,9,9,3,7,5,1,0,5,8,2,0,9,7,4,9,4,4]
let searchedSequence: [Int] = [5, 9]
var index = 0
var resultIndices: [Int] = []
while index < (piDigits.count - searchedSequence.count) {
let subarray = piDigits[index ..< (index + searchedSequence.count)]
if subarray.elementsEqual(searchedSequence) {
resultIndices.append(index)
}
index += 1
}
print("Result: \(resultIndices)")
There are other variants as well, you could, for example, keep dropping the first character from piDigits during iteration and check whether piDigits start with the searchedSequence.
If performance is critical, I recommend using a string searching algorithm, e.g. Aho-Corasick (see https://en.wikipedia.org/wiki/String_searching_algorithm) which builds a state machine first for fast comparison (similar to regular expressions).
Let's see how regular expressions can be used:
let searchedSequences: [[Int]] = [[5, 9], [7], [9, 2]]
let stringDigits = piDigits.map { String($0) }.joined()
let stringSearchedSequences = searchedSequences.map { sequence in sequence.map { String($0) }.joined() }
let regularExpressionPattern = stringSearchedSequences.joined(separator: "|")
let regularExpression = try! NSRegularExpression(pattern: regularExpressionPattern, options: [])
let matches = regularExpression.matches(in: stringDigits, options: [], range: NSRange(location: 0, length: stringDigits.characters.count))
let matchedIndices = matches.map { $0.range.location }
print("Matches: \(matchedIndices)")
The downside of the approach is that it won't search overlapping ranges (e.g. "592" matches two ranges but only one is reported).
Inside the contains method iterates over the array and here you have to do the same thing. Here an example:
extension Array where Element: Equatable {
func contains(array elements: [Element]) -> Int {
guard elements.count > 0 else { return 0 }
guard count > 0 else { return -1 }
var ti = 0
for (index, element) in self.enumerated() {
ti = elements[ti] == element ? ti + 1 : 0
if ti == elements.count {
return index - elements.count + 1
}
}
return -1
}
}
And here how to use it:
let index = [1, 4, 5, 6, 6, 9, 6, 8, 10, 3, 4].contains(array: [6, 8, 10])
// index = 6
let index = [1, 4, 5, 6, 6, 9, 6, 8, 10, 3, 4].contains(array: [6, 8, 1])
// index = -1
let firstSeqNum = 5
let secondSeqNum = 9
for (index, number) in array.enumerated() {
if number == firstSeqNum && array[index+1] == secondSeqNum {
print("The sequence \(firstSeqNum), \(secondSeqNum) was found, starting at an index of \(index).")
}
}
Since there's no built-in method for this, this would be your best option.

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?
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.
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
The most frequent value is called the "mode". Here's a concise version:
let mode = myArray.reduce([Int: Int]()) {
var counts = $0
counts[$1] = ($0[$1] ?? 0) + 1
return counts
}.max { $0.1 < $1.1 }?.0
Whether that's considered "unreadable" or "elegant" depends on your feelings towards higher order functions. Nonetheless, here it is as a generic method in an extension on Array (so it'll work with any Hashable element type):
extension Array where Element: Hashable {
var mode: Element? {
return self.reduce([Element: Int]()) {
var counts = $0
counts[$1] = ($0[$1] ?? 0) + 1
return counts
}.max { $0.1 < $1.1 }?.0
}
}
Simply remove the .0 if you'd rather have a tuple that includes the count of the mode.
My take on it with Swift 5:
extension Collection {
/**
Returns the most frequent element in the collection.
*/
func mostFrequent() -> Self.Element?
where Self.Element: Hashable {
let counts = self.reduce(into: [:]) {
return $0[$1, default: 0] += 1
}
return counts.max(by: { $0.1 < $1.1 })?.key
}
}
I have tried the following code. It helps especially when the max count is applicable for 2 or more values.
var dictionary = arr.reduce(into: [:]) { counts, number in counts[number, default: 0] += 1}
var max = dictionary.values.max()!
dictionary = dictionary.filter{$0.1 == max}
mode = dictionary.keys.min()!
func mostR(num : [Int]) -> (number : Int , totalRepeated : Int)
{
var numberTofind : Int = 0
var total : Int = 0
var dic : [Int : Int] = [:]
for index in num
{
if let count = dic[index]
{
dic[index] = count + 1
}
else
{
dic[index] = 1
}
}
var high = dic.values.max()
for (index , count) in dic
{
if dic[index] == high
{
numberTofind = index
top.append(count)
total = count
}
}
return (numberTofind , total)
}
var array = [1,22,33,55,4,3,2,0,0,0,0]
var result = mostR(num : [1,22,3,2,43,2,11,0,0,0])
print("the number is (result.number) and its repeated by :(result.totalRepeated)" )
Here is an encapsulated/reusable method.
extension Array where Element: Hashable {
/// The mode will be nil when the array is empty.
var mode: Element? {
var counts: [Element: Int] = [:]
forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
print("\(value) occurs \(count) times")
return value
} else {
return nil
}
}
}
usage:
print([3, 4, 5, 6, 6].mode) // 6
Keep track of each occurrence, counting the value of each key in a dictionary. This case is exclusive for integers. Will update this method using generics.
func mostCommon(of arr: [Int]) -> Int {
var dict = [Int:Int]()
arr.forEach {
if let count = dict[$0] {
dict[$0] = count + 1
} else {
dict[$0] = 1
}
}
let max = dict.values.max()
for (_ , value) in dict {
if value == max {
return value
}
}
return -1
}

How can I interleave two arrays?

If I have two arrays e.g
let one = [1,3,5]
let two = [2,4,6]
I would like to merge/interleave the arrays in the following pattern [one[0], two[0], one[1], two[1] etc....]
//prints [1,2,3,4,5,6]
let comibned = mergeFunction(one, two)
print(combined)
What would be a good way to implement the combining function?
func mergeFunction(one: [T], _ two: [T]) -> [T] {
var mergedArray = [T]()
//What goes here
return mergedArray
}
If both arrays have the same length then this is a possible solution:
let one = [1,3,5]
let two = [2,4,6]
let merged = zip(one, two).flatMap { [$0, $1] }
print(merged) // [1, 2, 3, 4, 5, 6]
Here zip() enumerates the arrays in parallel and returns a sequence
of pairs (2-element tuples) with one element from each array. flatMap() creates a 2-element array from each pair and concatenates the result.
If the arrays can have different length then you append the
extra elements of the longer array to the result:
func mergeFunction<T>(one: [T], _ two: [T]) -> [T] {
let commonLength = min(one.count, two.count)
return zip(one, two).flatMap { [$0, $1] }
+ one.suffixFrom(commonLength)
+ two.suffixFrom(commonLength)
}
Update for Swift 3:
func mergeFunction<T>(_ one: [T], _ two: [T]) -> [T] {
let commonLength = min(one.count, two.count)
return zip(one, two).flatMap { [$0, $1] }
+ one.suffix(from: commonLength)
+ two.suffix(from: commonLength)
}
If you're just looking to interleave two arrays, you could just do something like:
let maxIndex = max(one.count, two.count)
var mergedArray = Array<T>()
for index in 0..<maxIndex {
if index < one.count { mergedArray.append(one[index]) }
if index < two.count { mergedArray.append(two[index]) }
}
return mergedArray
With Swift 5, you can use one of the following Playground sample codes in order to solve your problem.
#1. Using zip(_:_:) function and Collection's flatMap(_:) method
let one = [1, 3, 5, 7]
let two = [2, 4, 6]
let array = zip(one, two).flatMap({ [$0, $1] })
print(array) // print: [1, 2, 3, 4, 5, 6]
Apple states:
If the two sequences passed to zip(_:_:) are different lengths, the resulting sequence is the same length as the shorter sequence.
#2. Using an object that conforms to Sequence and IteratorProtocol protocols
struct InterleavedSequence<T>: Sequence, IteratorProtocol {
private let firstArray: [T]
private let secondArray: [T]
private let thresholdIndex: Int
private var index = 0
private var toggle = false
init(firstArray: [T], secondArray: [T]) {
self.firstArray = firstArray
self.secondArray = secondArray
self.thresholdIndex = Swift.min(firstArray.endIndex, secondArray.endIndex)
}
mutating func next() -> T? {
guard index < thresholdIndex else { return nil }
defer {
if toggle {
index += 1
}
toggle.toggle()
}
return !toggle ? firstArray[index] : secondArray[index]
}
}
let one = [1, 3, 5, 7]
let two = [2, 4, 6]
let sequence = InterleavedSequence(firstArray: one, secondArray: two)
let array = Array(sequence)
print(array) // print: [1, 2, 3, 4, 5, 6]
/// Alternates between the elements of two sequences.
/// - Parameter keepSuffix:
/// When `true`, and the sequences have different lengths,
/// the suffix of `interleaved` will be the suffix of the longer sequence.
func interleaved<Sequence: Swift.Sequence>(
with sequence: Sequence,
keepingLongerSuffix keepSuffix: Bool = false
) -> AnySequence<Element>
where Sequence.Element == Element {
keepSuffix
? .init { () -> AnyIterator<Element> in
var iterators = (
AnyIterator( self.makeIterator() ),
AnyIterator( sequence.makeIterator() )
)
return .init {
defer { iterators = (iterators.1, iterators.0) }
return iterators.0.next() ?? iterators.1.next()
}
}
: .init(
zip(self, sequence).lazy.flatMap { [$0, $1] }
)
}
let oddsTo7 = stride(from: 1, to: 7, by: 2)
let evensThrough10 = stride(from: 2, through: 10, by: 2)
let oneThrough6 = Array(1...6)
XCTAssertEqual(
Array( oddsTo7.interleaved(with: evensThrough10) ),
oneThrough6
)
XCTAssertEqual(
Array(
oddsTo7.interleaved(with: evensThrough10, keepingLongerSuffix: true)
),
oneThrough6 + [8, 10]
)

count numbers in array and order them by count in swift

Is there a easy way to sort an array by the count of numbers? And if a number have the same count put the highest number first.
[2,8,2,6,1,8,2,6,6]
to
[6,6,6,2,2,2,8,8,1]
What you are looking for is a way to get the frequencies of values.
As long as the values are Hashable this function will work:
It extends all sequence types where the Element is Hashable, so an array of Int will work.
extension SequenceType where Generator.Element : Hashable {
func frequencies() -> [Generator.Element:Int] {
var results : [Generator.Element:Int] = [:]
for element in self {
results[element] = (results[element] ?? 0) + 1
}
return results
}
}
Then you can do this:
let alpha = [2,8,2,6,1,8,2,6,6]
let sorted = alpha.frequencies().sort {
if $0.1 > $1.1 { // if the frequency is higher, return true
return true
} else if $0.1 == $1.1 { // if the frequency is equal
return $0.0 > $1.0 // return value is higher
} else {
return false // else return false
}
}
Even better, you can now create another extension to sequence types.
Now they need to conform to Comparable as well as Hashable
extension SequenceType where Generator.Element : protocol<Hashable,Comparable> {
func sortByFrequency() -> [Generator.Element] {
// the same sort function as before
let sorted = self.frequencies().sort {
if $0.1 > $1.1 {
return true
} else if $0.1 == $1.1 {
return $0.0 > $1.0
} else {
return false
}
}
// this is to convert back from the dictionary to an array
var sortedValues : [Generator.Element] = []
sorted.forEach { // for each time the value was found
for _ in 0..<$0.1 {
sortedValues.append($0.0) // append
}
}
return sortedValues
}
}
Your final usage of all this will look like this :
let sorted = alpha.sortByFrequency() // [6, 6, 6, 2, 2, 2, 8, 8, 1]
Super clean :)
If you prefer a function closer to sort itself you can also use this :
extension SequenceType where Generator.Element : Hashable {
func sortedFrequency(#noescape isOrderedBefore: ((Self.Generator.Element,Int), (Self.Generator.Element,Int)) -> Bool) -> [Generator.Element] {
let sorted = self.frequencies().sort {
return isOrderedBefore($0,$1) // this uses the closure to sort
}
var sortedValues : [Generator.Element] = []
sorted.forEach {
for _ in 0..<$0.1 {
sortedValues.append($0.0)
}
}
return sortedValues
}
}
The extension above converts the array to a frequency dictionary internally and just asks you to input a closure that returns a Bool. Then you can apply different sorting depending on your needs.
Because you pass the closure with the sorting logic to this function the Elements of the SequenceType no longer need to be comparable.
Cheat sheet for all the shorthand:
$0 // first element
$1 // second element
$0.0 // value of first element
$0.1 // frequency of first element
Sorting :
let sortedB = alpha.sortedFrequency {
if $0.1 > $1.1 {
return true
} else if $0.1 == $1.1 {
return $0.0 > $1.0
} else {
return false
}
} // [6, 6, 6, 2, 2, 2, 8, 8, 1]
I'm not sure if this is the most efficient way to do it, but I think it is fairly elegant:
extension Array where Element: Equatable {
func subArrays() -> [[Element]] {
if self.isEmpty {
return [[]]
} else {
let slice = self.filter { $0 == self[0] }
let rest = self.filter { $0 != self[0] }
return rest.isEmpty
? [slice]
: [slice] + rest.subArrays()
}
}
func sortByFrequency(secondarySort: ((Element, Element) -> Bool)? = nil) -> [Element] {
return self.subArrays()
.sort { secondarySort?($0[0], $1[0]) ?? false }
.sort { $0.count > $1.count }
.flatMap { $0 }
}
}
let nums = [2,8,2,6,1,8,2,6,6]
print(nums.sortByFrequency(>)) // [6, 6, 6, 2, 2, 2, 8, 8, 1]
The function subArrays just breaks the array down into an array of sub-arrays for each value in the original array - i.e., you'd get [[2,2,2],[8,8],[6,6,6],[1]] for the input that you provided.
sortByFrequency sorts the output of subArrays and then flatMaps to get the answer.
EDIT: I modified sortByFrequency to add the optional secondarySearch parameter. That allows you to control how you want items that occur at the same frequency to be sorted. Or, just accept the default nil and they won't be sorted by anything other than frequency.
Also, I modified the extension to indicate that Element only needs to conform to Equatable, not Comparable.
//: Playground - noun: a place where people can play
import UIKit
var arr1 = [2,8,2,6,1,8,2,6,6]
var arr2 = [6,6,6,2,2,2,8,8,1]
var counting = [Int: Int]()
// fill counting dictionary
for num in arr1 {
if counting[num] != nil {
counting[num]!++
} else {
counting[num] = 1
}
}
// [6: 3, 2: 3, 8: 2, 1: 1]
print(counting)
func order(i1: Int, i2: Int) -> Bool {
let count1 = counting[i1]
let count2 = counting[i2]
// if counting is the same: compare which number is greater
if count1 == count2 {
return i1 > i2
} else {
return count1 > count2
}
}
// [6, 6, 6, 2, 2, 2, 8, 8, 1]
print(arr1.sort(order))
print(arr2)
Using grouping in Dictionary:
var entries = [1,2,3,3,1,3,5,6,3,4,1,5,5,5,5]
extension Sequence where Element : Hashable {
func byFrequency() -> [Element] {
Dictionary(grouping: self, by: {$0}).sorted{ (a, b) in
a.value.count > b.value.count
}.map { $0.key}
}
}
print(entries.byFrequency().first)
Prints 5

Resources