'how to find duplicate values in integer array by loop in swift? [closed]
I need to know how to find duplicate values in integer array by loop method in swift? I tried to ->
func findDuplicates (array: [Int]) {
var prevItem = array[0]
for i in 0...array.count-1 {
if prevItem == array[i] {
print(i)
} else {
print("there is no any duplicates values")
}
}
}
please show my solution in this way!
Solution 1:[1]
You can use a set and every time you try to insert an element it fails it means it is a duplicate. You would need also to make sure you don't keep duplicate elements on the result:
func findDuplicates (array: [Int]) {
var set: Set<Int> = []
for i in array {
if !set.insert(i).inserted {
print("duplicate element:", i)
}
}
}
findDuplicates(array: [1,2,3,4,5,6,5,6,7,9])
This will print:
duplicate element: 5
duplicate element: 6
If you would like to return all duplicate elements of a collection you can simply use filter:
func getDuplicates(in array: [Int]) -> [Int] {
var set: Set<Int> = []
var filtered: Set<Int> = []
return array.filter { !set.insert($0).inserted && filtered.insert($0).inserted }
}
getDuplicates(in: [1,2,3,4,5,6,5,6,7,9]) // [5, 6]
extension RangeReplaceableCollection where Element: Hashable {
var duplicates: Self {
var set: Set<Element> = []
var filtered: Set<Element> = []
return filter { !set.insert($0).inserted && filtered.insert($0).inserted }
}
}
let numbers = [1,2,3,4,5,6,5,6,7,9]
numbers.duplicates // [5, 6]
let string = "1234565679"
string.duplicates // "56"
Solution 2:[2]
let list = [5,7,1,1,7,9]
var result : [Int] = []
var duplicateArr : [Int] = []
for i in 0..<list.count {
var isDuplicate = false
if duplicateArr.count == 0 {
duplicateArr.append(list[i])
}else{
print(list[i])
for j in 0..<duplicateArr.count{
if duplicateArr[j] == list[i] {
isDuplicate = true
}
}
if isDuplicate {
result.append(list[i])
}else{
duplicateArr.append(list[i])
}
}
}
print("Duplicate list -> \(result))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ShAnTh |
