Bronze and Silver


#1

bronze:

import Cocoa

struct Stack<Element>: SequenceType {
  var items = [Element]()
  
  mutating func push(newItem: Element) {
    items.append(newItem)
  }
  
  mutating func pop() -> Element? {
    guard !items.isEmpty else {
      return nil
    }
    return items.removeLast()
  }
  
  func map<U>(f: Element -> U) -> Stack<U> {
    var mappedItems = [U]()
    for item in items {
      mappedItems.append(f(item))
    }
    return Stack<U>(items: mappedItems)
  }
  // Bronze challenge:
  func filter(f: Element -> Bool) -> Stack<Element> {
    var filteredItems = Stack<Element>()
    // Stack is a SequenceType and we can use 'self' instead 'items'
    for item in self {
      if f(item) {
        filteredItems.push(item)
      }
    }
    return filteredItems
  }
  
  func generate() -> StackGenerator<Element> {
    return StackGenerator(stack: self)
  }
}

struct StackGenerator<T>: GeneratorType {
  
  var stack: Stack<T>
  
  mutating func next() -> T? {
    return stack.pop()
  }
}

func pushItemsOntoStack<Element, S: SequenceType where S.Generator.Element == Element>(inout stack: Stack<Element>, fromSequence sequence: S) {
  for item in sequence {
    stack.push(item)
  }
}


var myStack = Stack<Double>()
pushItemsOntoStack(&myStack, fromSequence: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])

let evensStack = myStack.filter { $0 % 2 == 0 }
// prints 2.0 4.0 6.0 8.0
for value in evensStack {
  print(value)
}

and silver:

func findAll<T: Equatable>(element: T, inArray array: [T]) -> [Int] {
  var resultArray = [Int]()
  for (index, item) in array.enumerate() {
    if item == element { resultArray.append(index) }
  }
  return resultArray
}

let intArray = [1, 2, 3, 4, 3, 2, 1]
// result: [1, 5]
let anotherIntArray = findAll(2, inArray: intArray)
// result: [0, 3, 6]
let anotherArray = findAll("a", inArray: ["a", "b", "c", "a", "b", "c", "a"])

#2

My solution to Bronze Challenge

// Bronze Challenge func filter(f: Element -> Bool) -> Stack<Element> { var filteredItems = [Element]() for item in items { if f(item) { filteredItems.append(item) } } return Stack<Element>(items: filteredItems) } // End of Bronze Challenge


#3

Bronze:

func filter(f: Element -> Bool) -> Stack<Element> {
        var filteredItems = Stack<Element>()
        for item in items {
            if f(item) {
                filteredItems.push(item)
            }
        }
        return filteredItems
    }

Silver:

func findAll<T: Equatable>(items: [T], checkItem:T) -> [Int] {
    var itemsFound = [Int]()
    for var i = 0; i < items.count; i++  {
        if items[i] == checkItem {
            itemsFound.append(i)
        }
    }
    return itemsFound
}

findAll([5,3,7,3,9], checkItem: 3)

#4

Silver Challenge:

func findAll<T: Equatable>(first: [T], _ second: T) -> [Int] { // my add for the Silver Challenge
var position = Int
var index = 0
for item in first {
if item == second {
position.append(index)
}
index += 1
}
return position
}