2

Let's take for example I have this array:

let dates = ["01/02/16", "02/02/16", "03/02/16", "01/02/16", "02/02/16"]

What I like to do is store each String date in a dictionary as the key, and for each key that repeats, I like to store the index of it as an array, and associate it with the duplicate key.

For example, 01/02/16 occurs at index 0 and 3. 02/02/16 occurs at index 1 and 4.

I like to have a dictionary that is something like this:

[ "01/02/16": [0, 3], "02/02/16": [2, 4], "03/02/16": [1] ]

I know how to keep track of how many duplicate entries there are like this:

let dates = ["01/02/16", "01/02/16", "02/02/16", "03/02/16"]

var dateCounts:[String:Int] = [:]

for date in dates
{
    dateCounts[date] = (dateCounts[date] ?? 0) + 1

}

for (key, value) in dateCounts
{
    print("\(key) occurs \(value) time/s")
}

However, I'm not sure how to keep track of the duplicate indices?

1 Answer 1

3

Try with this

import UIKit

class ViewController: UIViewController {

    var duplicatedDict : [String:[Int]] = [:]
    let dates = ["01/02/16", "01/02/16", "02/02/16", "03/02/16"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        for (index,dateString) in dates.enumerated() {
            if(duplicatedDict[dateString] == nil){
                duplicatedDict[dateString] = [index]
            }else{
                duplicatedDict[dateString]?.append(index)
            }
        }

        debugPrint(duplicatedDict)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Console Log output

["02/02/16": [2], "01/02/16": [0, 1], "03/02/16": [3]]

Hope this helps

Sign up to request clarification or add additional context in comments.

6 Comments

@Reinier..another question, since a Dictionary has no sense of "order"...how can I append just the array of indices into another array that is ordered based on the ordering of the dates array?....For example something like [ [0,1], [2], [3] ] where it corresponds to the ordering originally in dates array....or even just eliminate the [ String: [Int] ] pairing all together and have just [ [Int] ]?
You can order your keys and return the values of your keys ordered, but first you need to convert to Date in order to return right order
@sorry I'm a beginner at this..I'm not sure what you mean, can you attach an example below your answer?
@Pangu You can add another question, this is better because others can post their solutions, and maybe I learn also from that
@Pangu if you post another question please let me know
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.