-2

I have an [Int] array and I need to check for all elements, that don't have identical value with some another element. Those non- identical elements I would like to insert to a new array.

var spojeni1 = [1, 1, 2, 3, 4, 4] // Here it is values 2,3
var NewArray = [Int]()
for i in spojeni1 {
    if { // the value hasn't another identical value in the array
         NewArray.append(i)
   }
}

Hope it is clear, thank you

johny
  • 3
  • 1
  • 4
  • 3
    It's clear. Have you searched here for similar questions? It seems like there's been at least 3-5 asking something similar this year alone. –  Mar 10 '17 at 21:58
  • I haven't found exactly this problem @dfd – johny Mar 10 '17 at 22:34
  • 2
    Search. Possible words include "Swift", "array contents" identical". Here's one from "Swift identical elements" - http://stackoverflow.com/questions/29727618/find-duplicate-elements-in-array-using-swift#35387247. –  Mar 10 '17 at 22:45
  • My next search was on this site. Words were "Swift array identical remove". Here's a question with TWENTY THREE answers: http://stackoverflow.com/questions/25738817/does-there-exist-within-swifts-api-an-easy-way-to-remove-duplicate-elements-fro. –  Mar 10 '17 at 22:49
  • Read them, read them all. – Magnas Mar 10 '17 at 22:50
  • I suspect the subtlety of this question is not to remove the dupes, but to remove all instances of the items that are dupes. i.e. In the example for the question, the answer is [2, 3] and not [1, 2, 3, 4]. – ghostatron Mar 11 '17 at 01:31

2 Answers2

4

This can be done in a single line:

let numbers = [1, 1, 2, 3, 4, 4] // Here it is values 2,3

let uniques = Set(numbers).filter{ (n) in numbers.filter{$0==n}.count == 1 }

UPDATE

With Swift 4, you could also use a dictionary constructor to do it:

let uniques = Dictionary(grouping:numbers){$0}.filter{$1.count==1}.map{$0.0}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

I would make use of 2 sets:

var seenOnce: Set<Int> = []
var seenMorethanOnce: Set<Int> = []
let input = [1, 1, 2, 3, 4, 4]

for number in input
{
    if seenMorethanOnce.contains(number)
    {
        // Skip it since it's already been detected as a dupe.
    }
    else if seenOnce.contains(number)
    {
        // We saw it once, and now we have a dupe.
        seenOnce.remove(number)
        seenMorethanOnce.insert(number)
    }
    else
    {
        // First time seeing this number.
        seenOnce.insert(number)
    }
}

When that for loop finishes, the seenOnce set will have your values, and you can easily convert that to an array if you wish.

ghostatron
  • 2,620
  • 23
  • 27