Matt
Matt

Reputation: 61

If statements to find duplicate values?

Ok lets say I have a list which generates values randomly and sometimes it generates the same value twice.

For example generated int value:

1, 1, 2, 3, 4

Then I have a method called duplicateTracker() and its job is to find duplicates within the list.

I have an idea that it should be done using if else statements. So if it detects duplicate numbers its then true, else false.

How do I do this?

Upvotes: 0

Views: 1394

Answers (2)

user7014451
user7014451

Reputation:

Given this function:

func checkForDups(_ arr1:[Int], _ arr2:[Int]) -> Bool {
    let arrChecked = Set(arr1).subtracting(Set(arr2))
    if Set(arr1).count != arrChecked.count {
        return true
    }
    return false
}

Here's code that works:

let arr1:[Int] = [1,1,2,3,4,5]
let arr2:[Int] = [1,10,20]
let arr3:[Int] = [10,20,30]
print(checkForDups(arr1, arr2))  // prints true
print(checkForDups(arr1, arr3))  // prints false

Upvotes: 0

dfrib
dfrib

Reputation: 73186

This makes use of Foundation methods but given your use case, you might want to consider making us of an NSCountedSet to keep track of your generated numbers. E.g.

let numbersGenerator = AnyIterator { return 1 + arc4random_uniform(10) }
var numbersBag = NSCountedSet()

for num in (0...15).flatMap({ _ in numbersGenerator.next()}) {
    print(num, terminator: " ")
    numbersBag.add(num)
} /* 1 3 2 2 10 1 10 7 10 6 8 3 8 10 7 4 */
print()

numbersBag.forEach { print($0, numbersBag.count(for: $0)) }
/* 1 2
   2 2
   3 2
   4 1
   6 1
   7 2
   8 2
   10 4 */

Since NSCountedSet conforms to Sequence, you can easily extract any "duplicate diagnostics" that you wish using e.g. filter:

print("Numbers with duplicates: ", numbersBag.filter { numbersBag.count(for: $0) > 1 })
// Numbers with duplicates: [1, 2, 3, 7, 8, 10]

Upvotes: 1

Related Questions