Search This Blog

Showing posts with label swift4. Show all posts
Showing posts with label swift4. Show all posts

Tuesday, June 26, 2018

How to shuffle an array in Swift

Given a task - write a function for shuffle array. Let's start from simple solution. This method called Pencil and paper method

Example of function which shuffle array
import Foundation

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

func shuffle(array: [Int]) -> [Int] {
    var arrayCopy = array
    var randomArray = [Int]()
    for _ in array {
        let randomIndex = Int(arc4random_uniform(UInt32(arrayCopy.count)))
        let removedValue = arrayCopy.remove(at: randomIndex)
        randomArray.append(removedValue)
    }
    return randomArray
}

let shuffledArray = shuffle(array: array)
print(array) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(shuffledArray) //[7, 6, 9, 2, 8, 4, 3, 1, 5, 10]
Function shuffle, that provided below, works by following algorithm:
  1. Make copy of incoming array to variable arrayCopy (we will remove items from this copy)
  2. Make new empty array randomArray(we will add new values to this array)
  3. For each item in copied array
    1. Generate random index from 0 to arrayCopy length
    2. Remove item with random index from arrayCopy (when remove we can store removed item)
    3. Add removed item to randomArray
  4. Return randomArray


Making Extension for shuffle array

For more handy usage let's move this code to extension

Example of extension for shuffle array
extension Array {
    
    func shuffle() -> [Element] {
        var arrayCopy = self
        var result = [Element]()
        for _ in self {
            let randomIndex = Int(arc4random_uniform(UInt32(arrayCopy.count)))
            let removedItem = arrayCopy.remove(at: randomIndex)
            result.append(removedItem)
        }
        return result
    }
}

let array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(array2) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(array2.shuffle()) //[5, 9, 6, 10, 2, 7, 1, 3, 8, 4]

let strings = ["one", "two", "three", "four", "five"]
print(strings) //["one", "two", "three", "four", "five"]
print(strings.shuffle()) //["five", "four", "one", "three", "two"]
The algorithm remains the same. But for now, because we use extension, any array can be shuffled, as we can see above now we can shuffle array of strings too.

Mutating self extension method
We can add modified version of our extension which modify current array in-place without return new array.

Example of extension which shuffle current array in-place
extension Array {
    
    mutating func shuffleInline() {
        var result = [Element]()
        for _ in self {
            let randomIndex = Int(arc4random_uniform(UInt32(self.count)))
            let removedItem = self.remove(at: randomIndex)
            result.append(removedItem)
        }
        self = result
    }
}

var array3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(array3) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array3.shuffleInline()
print(array3) //[3, 1, 4, 6, 2, 5, 9, 10, 7, 8]

Complexity of Pencil and paper algorithm

Complexity of this algorithm will be O(nˆ2) because
  • O(n) is for one 'for loop'
  • O(n) is for removing from array


Model Shuffle Algorithm

How we can improve time complexity of shuffling? There is Modern method which allow us to get linear O(n) complexity. It is because we have only one loop over the array and swap random item on each iteration.

Example of shuffle function implemented modern algorithm 
func shuffleModern(array: [Int]) -> [Int] {
    var length = array.count
    var arrayCopy = array
    for _ in array {
        let randomIndex = Int(arc4random_uniform(UInt32(length)))
        if length - 1 != randomIndex {
            arrayCopy.swapAt(length - 1, randomIndex)
        }
        length -= 1
    }
    return arrayCopy
}

let array4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(array4) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(shuffleModern(array: array4)) //[9, 6, 7, 10, 2, 8, 1, 4, 3, 5]

Generic function
We also can make our function generic and apply it to array of any type, for example for array of strings.

Example of generic implementation
func shuffleModern<T>(array: [T]) -> [T] {
    var length = array.count
    var arrayCopy = array
    for _ in array {
        let randomIndex = Int(arc4random_uniform(UInt32(length)))
        if length - 1 != randomIndex {
            arrayCopy.swapAt(length - 1, randomIndex)
        }
        length -= 1
    }
    return arrayCopy
}

let strings2 = ["one", "two", "three", "four", "five"]
print(strings2) //["one", "two", "three", "four", "five"]
print(shuffleModern(array: strings2)) //["five", "four", "one", "three", "two"]
Also let's create two extensions as before: 1) will return new shuffled array 2) will shuffle array in-place

Example of extension with modern shuffle algorithm (Immutable and In-place)
extension Array {
    
    func shuffleModern() -> [Element] {
        var arrayCopy = self
        var length = arrayCopy.count
        for _ in arrayCopy {
            let randomIndex = Int(arc4random_uniform(UInt32(length)))
            if length - 1 != randomIndex {
                arrayCopy.swapAt(length - 1, randomIndex)
            }
            length -= 1
        }
        return arrayCopy
    }
    
    mutating func shuffleModernInline() {
        var length = self.count
        for _ in self {
            let randomIndex = Int(arc4random_uniform(UInt32(length)))
            if length - 1 != randomIndex {
                swapAt(length - 1, randomIndex)
            }
            length -= 1
        }
    }
}

var array5 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(array5) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(array5.shuffleModern()) // [2, 6, 10, 5, 4, 7, 3, 8, 9, 1]
array5.shuffleModernInline()
print(array5) // [10, 6, 2, 3, 1, 8, 5, 4, 7, 9]


Source Code

Source code for this post could be found here on GitHub

Monday, June 25, 2018

Swift Defer Statement

defer keyword is used for declaring a block of code that will wait and will be executed just before exit from current scope (function, closure, loop, etc. ).  The block of code inside defer statement is guaranteed to be executed regardless of how we exit from current scope: normally, from a guard, or because of error.

Simple example
func testDefer1() {
    defer {
        print("Defer step 3")
    }
    print("Normal step 1")
    print("Normal step 2")
}

testDefer1()

//Normal step 1
//Normal step 2
//Defer step 3

defer scope


As mentioned before, defer statement will be executed before exit from current scope. So, if scope that contains defer statement is inside other scope, than defer will be executed on exit from inner scope.

defer scope example
func testDefer2() {
    print("Normal step 1")
    customFunc()
    print("Normal step 2")
}

func customFunc() {
    print("Custom step 1")
    print("Custom step 2")
    defer {
        print("Custom defer step 3")
    }
}

testDefer2()

//Normal step 1
//Custom step 1
//Custom step 2
//Custom defer step 3
//Normal step 2

As we can see here:
  1. Firstly will be printed strings from begin of outer scope
  2. Secondly will be printed strings from inner scope
  3. Thirdly will be printed strings from defer that in inner scope (just before exit from inner scope)
  4. Fourthly will be printed strings from end of outer scope

defer inside for loop


If we will use defer inside, for example, 'for loop', defer statement will be executed before end of each iteration of the loop.

Example of usage defer inside for loop
func testDefer3() {
    for i in 1...5 {
        print("Normal step iteration begins \(i)")
        defer {
            print("Defer step \(i)")
        }
        print("Normal step iteration ends \(i)")
    }
}

testDefer3()

//Normal step iteration begins 1
//Normal step iteration ends 1
//Defer step 1
//Normal step iteration begins 2
//Normal step iteration ends 2
//Defer step 2
//Normal step iteration begins 3
//Normal step iteration ends 3
//Defer step 3
//Normal step iteration begins 4
//Normal step iteration ends 4
//Defer step 4
//Normal step iteration begins 5
//Normal step iteration ends 5
//Defer step 5

Multiple defer statements


If there are multiple defer statements inside scope they will be executed in reverse order. Their execution will follow LIFO pattern - Last In First Out.

Multiple defer example
func testMultipleDefer() {
    print("Normal step 1")
    defer {
        print("Defer step 1")
    }
    defer {
        print("Defer step 2")
    }
    defer {
        print("Defer step 3")
    }
    print("Normal step 2")
}

testMultipleDefer()

//Normal step 1
//Normal step 2
//Defer step 3
//Defer step 2
//Defer step 1

As you can see, order of execution is reversed to order of adding to scope.


defer limitations


There are some limitations for using defer statement. You cannot exit from body of defer statement with following things:
  1. call return
  2. call break
  3. throw an error


Where we can use defer in Real Life Applications


The defer statement can be very useful when we want to clean up before exit from scope (for example, close connections to database or file, release unneeded resources), even if an error is thrown. For example, when we work with file and open a file to write to, we will want to make sure that we close opened file, even if there is an error happened while we work with file. 

Example of usage defer statement when working with file
func writeToFile(filename: String, text: String) throws {
    if let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        
        let path = directory.appendingPathComponent(filename).absoluteString
        
        guard let file = FileHandle(forUpdatingAtPath: path) else {
            print("File open failed")
            throw FileError.fileNotFound(reason: "File not found")
        }
        
        defer {
            print("Close file...")
            file.closeFile()
        }
        
        let fileURL = directory.appendingPathComponent(filename)
        
        do {
            try text.write(to: fileURL, atomically: false, encoding: .utf8)
        }
        catch {
            throw FileError.cannotWriteToFile(reason: "Cannot write to file")
        }
    }
}
In code snippet above, we close file before exit from function. And we close file in defer statement to make sure that we close file at any case, even if error was being thrown.


Source Code


Source code for this article could be found here on GitHub

Wednesday, May 23, 2018

Stack and Queue in Swift. Generic Implementation

I already described Stack and Queue data structures and how to implement them in Swift in my previous post about stack and queue. There I used class (reference type) for implementing stack and queue, also I used them for resolve task for define that string is palindrome.

Now let's update our implementation, for now let's use struct (value type) because it is always preferable to use struct(value type) if it no need for class features (like inheritance for example).

Non generic implementation (only for Int type)


Stack Implementation
// LIFO - Last In First Out
struct Stack {
    
    var array: [Int] = []
    
    var isEmpty: Bool {
        return array.isEmpty
    }
    
    // add new element to the stack
    mutating func push(_ element: Int) {
        array.append(element)
    }
    
    // get the last element from the stack and remove it form stack
    mutating func pop() -> Int? {
        if !isEmpty {
            let value = array.removeLast()
            return value
        }
        return nil
    }
    
    // get the head of stack - the last element
    mutating func peek() -> Int? {
        if !isEmpty {
            let value = array.last
            return value
        }
        return nil
    }
}

Queue Implementation
// FIFO - First In First Out
struct Queue {
    
    var array: [Int] = []
    
    var isEmpty: Bool {
        return array.isEmpty
    }
    
    // add new element to queue
    mutating func enqueue(_ element: Int) {
        array.append(element)
    }
    
    // get the first element and remove it from queue
    mutating func dequeue() -> Int? {
        if !isEmpty {
            let value = array.removeFirst()
            return value
        }
        return nil
    }
    
    // get the head of queue - the first element
    mutating func peek() -> Int? {
        if !isEmpty {
            let value = array.first
            return value
        }
        return nil
    }
}

Here example of adding randomly generated integer number to stack and queue.
var stack = Stack()
var queue = Queue()
    
let randomNumer = Int(arc4random_uniform(100))
stack.push(randomNumer)
queue.enqueue(randomNumer)

Generic Implementation


But it is always useful to write universal solutions for our tasks. So let's implement generic versions of stack and queue.

Stack Implementation
// LIFO - Last In First Out
struct Stack<T> {
    
    var array: [T] = []
    
    var isEmpty: Bool {
        return array.isEmpty
    }
    
    // add new element to the stack
    mutating func push(_ element: T) {
        array.append(element)
    }
    
    // get the last element from the stack and remove it form stack
    mutating func pop() -> T? {
        if !isEmpty {
            let value = array.popLast()
            return value
        }
        return nil
    }
    
    // get the head of stack - the last element
    func peek() -> T? {
        if !isEmpty {
            let value = array.last
            return value
        }
        return nil
    }
    
}

Queue Implementation
// FIFO - First In First Out
struct Queue<T> {
    
    var array: [T] = []
    
    var isEmpty: Bool {
        return array.isEmpty
    }
    
    // add new element to queue
    mutating func enqueue(_ element: T) {
        array.append(element)
    }
    
    // get the first element and remove it from queue
    mutating func dequeue() -> T? {
        if !array.isEmpty {
            let value = array.removeFirst()
            return value
        }
        return nil
    }
    
    // get the head of queue - the first element
    mutating func peek() -> T? {
        if !array.isEmpty {
            let value = array.first
            return value
        }
        return nil
    }
    
}

Now we can easily use stack for any type we need. For Integer:
var stack = Stack<Int>()
var queue = Queue<Int>()
    
let randomNumer = Int(arc4random_uniform(100))
stack.push(randomNumer)
queue.enqueue(randomNumer)

Or for String
var stack = Stack<String>()
var queue = Queue<String>()

Or even for Any, in this case we can add to stack and queue String and Integer both.
var stack = Stack<Any>()
var queue = Queue<Any>()

Demo Application


Stack and Queue before the values are obtained from them


Stack and Queue after the values are obtained from them


Source Code

Source code for demo app can be found on GitHub: Stack vs Queue Demo App

Sunday, May 20, 2018

Stack and Queue in Swift. Palindrome Test App


Theory of Stack and Queue


Stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the stacks following operations are allowed: push the item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. push adds an item to the top of the stack, pop removes the item from the top.

Queue is a container of objects that are inserted and removed according to the first-in first-out (FIFO) principle. New additions to a line made to the back of the queue, while removal (or serving) happens in the front. In the queue following operations are allowed enqueue and dequeue. Enqueue means to insert an item into the back of the queue, dequeue means removing the front item.

Definitions getting from https://www.cs.cmu.edu





Task 

Determine that a given string is a palindrome. A palindrome is a phrase which reads the same backward and forward.

Algorithm

Version 1

  1. First loop. For each character symbol of string add to queue and to stack.
  2. Second loop. From 0 to N - 1 (where N = length of string) get symbol  from queue and from stack (when queue we get symbol from begin, when stack we get symbol from end) and compare them. Because if any pair is not equals then it is not palindrome.


Version 2
We can improve this algorithm. Not check the whole word but only half of it, because it will be enough for determine palindrome.

Implementation


Queue Implementation
import Foundation

// FIFO - First In First Out
class Queue {
    var arr: [Character]
    
    init() {
        self.arr = [Character]()
    }
    
    // add new element to queue
    func enqueue(ch: Character) -> Void {
        self.arr.append(ch)
    }
    
    // get the head of queue - the first element
    func peek() -> Character? {
        return self.arr.first
    }
    
    // get the first element and remove it from queue
    func dequeue() -> Character {
        return self.arr.removeFirst()
    }
}

Stack Implementation
import Foundation

// LIFO - Last In First Out
class Stack {
    var arr: [Character]
    
    init() {
        self.arr = [Character]()
    }
    
    // get the head of stack - the last element
    func peek() -> Character? {
        return self.arr.last
    }
    
    // get the last element from the stack and remove it form stack
    func pop() -> Character {
        return self.arr.removeLast()
    }
    
    // add new element to the stack
    func push(ch: Character) -> Void {
       self.arr.append(ch)
    }
    
}

Checking for Palindrome
@IBAction func checkButtonTapped(_ sender: UIButton) {
    if let str = textField.text, str.count > 0 {
        let count = str.count
        var isPalindrome = true
        let queue = Queue()
        let stack = Stack()
        for ch in str {
            queue.enqueue(ch)
            stack.push(ch)
        }
        for _ in 0...(count - 1) {
            if queue.dequeue() != stack.pop() {
                isPalindrome = false
                break
            }
        }
            
        if isPalindrome {
            resultLabel.text = "Palindrome Found!"
        } else {
            resultLabel.text = "NOT Palindrome!"
        }
    } else {
        resultLabel.text = "Empty String"
    }
}

Checking for Palindrome(Improved - Check only half of word)
@IBAction func checkButtonTapped(_ sender: UIButton) {
    if let str = textField.text, str.count > 0 {
        let count = str.count
        var isPalindrome = true
        let queue = Queue()
        let stack = Stack()
        for ch in str {
            queue.enqueue(ch)
            stack.push(ch)
        }
        for _ in 0...(count / 2) {
            if queue.dequeue() != stack.pop() {
                isPalindrome = false
                break
            }
        }
            
        if isPalindrome {
            resultLabel.text = "Palindrome Found!"
        } else {
            resultLabel.text = "NOT Palindrome!"
        }
    } else {
        resultLabel.text = "Empty String"
    }
}

Results


Results - Not Palindrome



Results - Palindrome


Source Code


Source code for this demo project can be found here: PalindromeTest