// Bronze Challenge
struct Stack<Element>: Sequence {
...
func filter(f: (Element) -> Bool) -> Stack<Element> {
var filteredItems = [Element]()
for item in items where f(item) {
filteredItems.append(item)
}
return Stack<Element>(items: filteredItems)
}
}
print(myStack)
let evenStack = myStack.filter(f: { $0 % 2 == 0})
print(evenStack)
Output
Stack<Int>(items: [10, 20, 30, 1, 2, 3, 3, 2, 1])
Stack<Int>(items: [10, 20, 30, 2, 2])
// Silver Challenge
func findAll<T: Equatable>(_ array: [T], _ element: T) -> [Int] {
var positions = [Int]()
for (index, item) in array.enumerated() where item == element {
positions.append(index)
}
return positions
}
print(findAll([5,3,7,3,9], 3))
print(findAll(["you","are","as","good","as","you","think"], "as"))
Output
[1, 3]
[2, 4]
// Gold Challenge (indexes)
func findAllIndexesInCollection<T: Equatable, U: Collection>(_ collection: U, _ element: T) -> [Int] where U.Element == T {
var indexes = [Int]()
for (index, item) in collection.enumerated() where item == element {
indexes.append(index)
}
return indexes
}
print(findAllIndexesInCollection([5,3,7,3,9], 3))
print(findAllIndexesInCollection(["you","are","as","good","as","you","think"], "as"))
print(findAllIndexesInCollection(Set(["you","are","as","good","as","you","think"]), "as")) // Sets are unordered collections
Output
[1, 3]
[2, 4]
[1]
// Gold Challenge (items)
func findAllItemsInCollection<T: Equatable, U: Collection>(_ collection: U, _ element: T) -> [U.Element] where U.Element == T {
var items = [U.Element]()
for item in collection where item == element {
items.append(item)
}
return items
}
print(findAllItemsInCollection([5,3,7,3,9], 3))
print(findAllItemsInCollection(["you","are","as","good","as","you","think"], "as"))
print(findAllItemsInCollection(Set(["you","are","as","good","as","you","think"]), "as"))
Output
[3, 3]
["as", "as"]
["as"]