-1

Say I have a set [A, B, B, C, D], how would I remove just the first B?

If charToDelete = B and I do this:

SlidingWin.remove(charToDelete)

won't it remove all of the B characters?

PruitIgoe
  • 6,166
  • 16
  • 70
  • 137
  • 4
    A set is a collection of *unique* elements, it *cannot* hold the same element twice. – Martin R Oct 03 '17 at 17:31
  • Try `let set = Set(["A", "B", "B", "C", "D"]); print(set)` – Martin R Oct 03 '17 at 17:32
  • Martin R. answered my question. I thought if I had two B characters in a set they would both be deleted. So if I have a string "AACBCCAABBA" and I iterate over it, take the first four characters and place in a set (AACB), then do something with that set, then remove the first character I added (A) I don't want to remove the second A. If I understood Martin right the hash table could be like 1 A --> A and if on remove it finds the first A in the chain the process ends there. It won't remove the second A. – PruitIgoe Oct 03 '17 at 17:50
  • Whoever down voted and added the possible duplicate. I am not working with an array. It is a set. – PruitIgoe Oct 03 '17 at 17:58
  • I know that, I don't care about order. See my comment below. – PruitIgoe Oct 03 '17 at 18:01
  • That's on me, should of said one of the Bs or something like that. – PruitIgoe Oct 03 '17 at 18:04
  • That's fine. We can leave it closed. I have my answer. – PruitIgoe Oct 03 '17 at 18:06

1 Answers1

0

In Swift lingo, what you have is an array (not a set). If you want to remove the first "B" from an array, you can do this:

if let index = array.index(of:"B")
{ array.remove(at:index) } 

[EDIT] example of a functional approach for anagrams:

let set1 = "cabb"
let set2 = "cbabeijbbacbkiie"

let anagrams = zip(set2.indices,set2.indices.dropFirst(set1.count-1))
               .map{set2[$0...$1]}
               .filter{$0.sorted() == set1.sorted()}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • I'm probably not being clear. I am working with a set. To check another set. Think of looking for anagrams. I have 4 letters in one set, 16 in another. I want to see if there are any permutations of set 1 in set 2. I'm using a sliding window pattern, take first 4 of set 2, see if they match set 1, discard 1st item added from set 2, add next item, check again. – PruitIgoe Oct 03 '17 at 18:00
  • A Swift Set cannot contain any value more than once so you'll be working with the Array type. In that case, my answer should work for that specific operation. The whole anagram problem though could be solved without element removal using functional programming – Alain T. Oct 03 '17 at 18:42