I was thinking about how to transform an Array instance into a Set, where duplicates are removed. And to do this for an Int array was fairly straightforward,
func removeDuplicates(array:[Int]) -> [Int] { var arr = array var indArr = [Int]() var tempArr = arr var i = 0 for a in enumerate(arr) { if contains(prefix(arr, a.index), a.element) { indArr.append(a.index) } i++ } var ind = 0 for i in indArr { arr.removeAtIndex(i-ind) ind++ } return arr }but I didn't want to write a new method for every type of Array. I therefore took advantage of generics to write a method that took an Array of items that adopt the Comparable protocol, because that's exactly what we're doing to find duplicates; we're comparing the values of the items to one another.
func removeDuplicates<T: Comparable>(array:[T]) -> [T] { var arr = array var indArr = [Int]() var tempArr = arr var i = 0 for a in enumerate(arr) { if contains(prefix(arr, a.index), a.element) { indArr.append(a.index) } i++ } var ind = 0 for i in indArr { arr.removeAtIndex(i-ind) ind++ } return arr }So now instead of just Int arrays we can remove duplicates from Float arrays and even Character arrays:
removeDuplicates([1,2,2,3,4,4,7,7,8,8,8,9]) removeDuplicates(["a","b","c","c"])
Going further
I know already that I can make a similar method work with a String instance, because I've already written these methods into an extension:extension String { mutating func removeAtIndex(ind:Int) { var str = prefix(self,ind) str += suffix(self,distance(self.startIndex,self.endIndex)-ind-1) self = str } func removeDuplicates() -> String { var arr = self var indArr = [Int]() var tempArr = self var i = 0 for a in self { if contains(prefix(arr, i), a) { indArr.append(i) } i++ } var ind = 0 for i in indArr { arr.removeAtIndex(i-ind) ind++ } return arr } } var str = "hello world" str.removeAtIndex(4) str.removeDuplicates()But the next challenge I've set myself is to develop an even deeper understanding of generics, to see if my current method, which is capable of taking an Array instance with items that adopt the Comparable protocol, can be extended to include String instances as well.
Comments
Post a Comment