0
So far I have this: 

func myFunc(arr: [Int]) {
    var arr2 = arr
    var count = 1
    for i in 0..<arr.count {
        for j in i + 1..<arr2.count {
            if arr2[i] == arr2[j] {
                count += 1
                arr2.remove(at: j)
            }

        }
       print("\(arr2[i])-\(count)")
        count = 1
    }
}
myFunc(arr: [5,6,5])

I want it to print (5 - 2) (6 - 1) I am getting a fatal error every time I want to remove the repeated element, can you explain why and how to solve this problem?

  • Do you need the order? Like "5-2" first because it was first in the array? Else, you might be interested in `NSCountedSet` which is exactly for that. – Larme Jul 24 '20 at 07:35

1 Answers1

0

I will solve this problem by creating hash table or dictionary with keys of type the same as array elements and integers as values. This structure will store values from array. Walking through array you can:

  1. Add element to dictionary is if it not already exists with value as "key" and 1 as "value".
  2. If element already exists - increment "value" by one of element "Key| == element. After walking whole array you will have dictionary with unique elements as dictionary keys and number of repetitions as values