Category: Algorithms

December 6th, 2017 by admin

If an array contains numbers such as integers or decimal numbers, it’s fairly simple to write a function that adds all the elements of an array using a for-in loop. For example, assume you have an array of integers like this:

var transactions = [3, 56, 1, 20, 38, 7]

Now to add all these integers in the array together, start by assuming the total value is 0. Then keep adding each array item until you get a total. A for-in loop might look like this:

var myTotal = 0
for i in transactions {
    myTotal = myTotal + i
}

This for-in loop is straightforward, but Swift offers a method for manipulating arrays called reduce. The reduce method lets you define an initial value and a closure, which is essentially the guts of a function written in condensed form. As an alternative to adding array items using a for-in loop, you could just use a closure like this:

var transactions = [3, 56, 1, 20, 38, 7]

var total: Int {
    return transactions.reduce(0, {x, y in x + y})
}

This defines an Int variable called “Total” that uses the reduce array method to calculate a value. In this case, the initial value is 0. Then it takes one value in the array (x) and adds it with the next value in the array (y). This gives us the exact same result as the for-in loop.

The for-in loop is obviously clearer and easier to understand. The reduce method with a closure is more elegant but harder to understand. Since closures can look so odd, it’s probably best to add comments that explain how they work and even write short code that duplicates what the closure does. This will help others better understand what the closure does and how it works.

To read more about the reduce method for arrays, click here.

 

Posted in Algorithms

December 4th, 2017 by admin

When working with angles, most people are comfortable measuring angles using degrees, but many of Apple’s frameworks expect radians. To convert degrees to radians (or vice versa), you could write your own conversion functions, but there’s no reason to do so since Apple’s GLKit framework includes such conversion functions.

All you have to do is import the GLKit into your project to gain access to its conversion functions. Then define degrees or radians as a Float data type.

To convert degrees into radians, use the GLKMathDegreesToRadians function.

To convert radians into degrees, use the GLKMathRadiansToDegrees function like this:

import GLKit

let degrees: Float = 360

let radians = GLKMathDegreesToRadians(degrees)
let newDegrees = GLKMathRadiansToDegrees(radians)

The above code will convert 360 degrees into 6.283185 radians and then convert 6.283185 radians back to 360 degrees.

Posted in Algorithms

November 29th, 2017 by admin

On many Apple products when you type in a password incorrectly, the text field appears to “shake” back and forth as if telling you, “Nope. You entered a password incorrectly.” To create this shaking effect on a text field, you need to create an extension.

Extensions let you define new methods for manipulating an object. Since a text field is an object, created from the UITextField class, it’s possible to extend this UiTextField class with a custom shaking function.

To see how this works, create a Single View App iOS project and add a text field and a button on the user interface. Create an IBOutlet for the text field like this:

@IBOutlet weak var textField: UITextField!

Then create an IBAction method for the button like this:

    @IBAction func checkPassword(_ sender: UIButton) {
        if textField.text == password {
            textField.text = "ACCESS GRANTED"
        } else {
            textField.shake()
        }
    }

This simple project works by displaying a text field and a button. If you type a password correctly in the text field, then the text field displays the text “ACCESS GRANTED”. However, if you type an incorrect password, then the text field runs a shake function. To create this shake function, you need to create an extension at the bottom of the ViewController.swift file past the last curly bracket like this:

extension UITextField {
    func shake() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.05
        animation.repeatCount = 5
        animation.autoreverses = true
        animation.fromValue = CGPoint(x: self.center.x - 4.0, y: self.center.y)
        animation.toValue = CGPoint(x: self.center.x + 4.0, y: self.center.y)
        layer.add(animation, forKey: "position")
    }
}

This shake function defines an animation that lasts 0.05 seconds, repeats itself 5 times, and moves the text field 4.0 pixels to the left and 4.0 pixels to the right, which creates the “shaking” visual effect.

Your complete ViewController.swift file should look like this:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    let password = "password"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func checkPassword(_ sender: UIButton) {
        if textField.text == password {
            textField.text = "ACCESS GRANTED"
        } else {
            textField.shake()
        }
    }
    
}

extension UITextField {
    func shake() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.05
        animation.repeatCount = 5
        animation.autoreverses = true
        animation.fromValue = CGPoint(x: self.center.x - 4.0, y: self.center.y)
        animation.toValue = CGPoint(x: self.center.x + 4.0, y: self.center.y)
        layer.add(animation, forKey: "position")
    }
}

When you run this app in the Simulator, type the word “password” in the text field and you’ll see the words “ACCESS GRANTED” in the text field. If you type anything other than “password” in the text field, the text field will shake back and forth.

By using extensions, you’ve extended the text field to make the shake() method available to the text field. Any time you want to modify a user interface item, use an extension to modify that object’s behavior.

Posted in Algorithms, User Interface

November 13th, 2017 by admin

With most older programming languages, printing data of different types can be a nuisance since you typically have to convert everything into a string. Swift avoids this hassle by simply letting you identify data to print or store into a string using the \() symbols such as:

let number = 1.2547032

let myString = "\(number)"
print (myString)

The above code simply stores a decimal number (1.2547032) into a variable that stores Double data types. (The Double data type is assumed by Swift.) Then rather than convert that Double variable into a string, Swift just lets you store that data as a string using the \() symbols.

If you try the above code in a Swift playground, you’ll find that the print statement simply prints the string “1.2547032”.

When printing or converting decimal values into strings, you might not want to display all the decimal values. A simple way to define exactly how many values after the decimal value to display is to use a format specifier.

If you’re familiar with the C programming language, you may already know that you use a % followed by a decimal point, and then the number of decimal places you want to display, followed by the “f” letter that stands for floating point like this:

let number = 1.2547032

let modifiedNumber = String(format: "%.2f", number)
print(modifiedNumber)

This code simply turns the number 1.2547032 into a string with two decimal places or 1.25. Then it prints the string “1.25”.

By using a format specifier to print or convert decimal values to a string, you can show as many decimal places as you wish such as two or three.

Posted in Algorithms

July 30th, 2017 by admin

Apple recently added machine learning features in a framework called Core ML. The idea is that you can take machine learning models and plug them into any Xcode project to instantly add machine learning capabilities to your apps. While this is exciting since this makes adding artificial intelligence (AI) to any app quick and easy, it’s not without its drawbacks.

First, let’s talk about the drawback of machine learning in general. In the book “Weapons of Math Destruction,” author Cathy O’Neil explains the inherent limitations of machine learning. Someone must first create an algorithm and then that algorithm is only as good as the data that it trains on. Feed the algorithms he wrong or misleading data and it can’t help but reach incorrect conclusions.

For example, Microsoft once created an AI chat bot that could learn from comments people submitted. So people started submitting racist comments so the AI chat bot would repeat nonsense about the Holocaust never happening and blaming Jews, blacks, and Mexicans for the problems in the world. That example simply shows if you train a machine learning model with bad data, you get back bad results.

Second, machine learning only works when the machine learning model can learn and improve its decisions. Without feedback, the machine learning model has no idea whether it’s coming up with the right conclusions or not. Those twin problems are what Cathy O’Neil highlights in “Weapons of Math Destruction.”

One example she gives is how many school districts are using computer algorithms to determine the “best” teachers. To do this, the programmers who created the algorithm can’t take into account all possible factors so they choose the ones they think (rightly or wrongly) that matter most in evaluating a teacher.

This caused the algorithm to rate one teacher as a 6 (on a scale of 1 to 100) one year, and then rate that same teacher a 96 the following year. How can a teacher go from a dismal 6 rating to an excellent 96 rating in one year? It’s because the first year, the teacher taught advanced students so their test scores were high to begin with, and remained high by the end of the year so they showed no improvement. the algorithm incorrectly assumed that no improvement in test scores meant that the teacher wasn’t any good.

The following year, that same teacher taught ordinary students and their test scores went up, so the algorithm assumed that the teacher did a good job. By not taking all factors into account and even worse, not accepting any feedback for modifying the machine learning model, this algorithm for evaluating teachers generates false and misleading results. yet because a computer generates these results in a seemingly objective way, people wrongly assume the computer must be correct when it’s not.

Even worse, the results of these skewered answers affects the lives of people, often in negative ways. Trying to argue that a computer algorithm is wrong is often a pointless and fruitless effort, and that’s the problem with machine learning.

Now in the world of Xcode, Core ML seems to have several faults. First, it’s not easy to create a machine learning model. That’s why Apple offers several machine learning models on their website. Second, there are plenty of machine learning models available that aren’t stored in the Core ML format, so Apple offers a bunch of tools for converting these machine learning models into Core ML files.

Unfortunately, installing and using these tools is clumsy and error-prone, making the process difficult for all but hardened developers. Apple will likely fix this process, but right now, it’s a huge pain in the neck. Still if you can get it to work, you can theoretically convert most machine learning models into Core ML files so you can add them to any Xcode project. That means you can add AI capabilities to macOS, iOS, watchOS, or tvOS apps.

Perhaps the greatest limitation of machine learning models is that once you have them stored on Core ML format, can you modify these models to make them more intelligent so they actually learn over time with new data?

If you can modify a machine learning model over time, then how do you do it and how do you keep it from making mistakes such as what happened with Microsoft’s chat bot that learned to swear and offer racist comments?

If you can’t modify a machine learning model over time, then it’s inherently limited. If you try several of the machine learning models that Apple provides, you’ll find that they’re only average in recognizing images in pictures.

So machine learning has a great future in making apps smarter. The problem is that machine learning is still limited and difficult. That will only get better over time and machine learning models will get smarter over time as well.

Until then, machine learning is the future so you better know how to add machine learning models to your Xcode projects. Just don’t expect miracles just yet, and keep in mind that “Weapons of Math Destruction” highlights the danger of relying too much on algorithms that we don’t fully understand and can’t modify.

Machine learning has its place, and it’s firmly in assisting humans, not substituting actual thought for machine learning results.

Posted in Algorithms, Programming, Xcode

May 30th, 2017 by admin

When you’re working with numbers, you may want to convert the number to a string. The simplest way to convert a number to a string is to use the String data type to convert a number to a string like this:

var aNumber = 76
String(aNumber)     // aNumber = "76"

A fancier way to convert a number to a string is to use the NumberFormatter class. At the simplest level, the NumberFormatter class just duplicates the String data type conversion like this:

var myNumber = NumberFormatter()

let costString = myNumber.string(from: 24)
print (costString!)

In the above code, the first line creates an object (myNumber) from the NumberFormatter class.

The second line converts a number (24) to a string and then stores that number into a constant named costString (“24”).

The NumberFormatter class can also convert a string into a number such as turning “9.4” into 9.4 like this:

var newStuff = myNumber.number(from: "9.4")

In this example, the line converts the string “9.4” into a number (9.4) and stores it into the newStuff variable.

Of course, you could just use the Double data type to convert a string into a number like this:

var decimal = "4.2"
Double(decimal)!

The first line creates a string variable that contains “4.2” as its value. The second line then uses the Double data type to convert the string from “4.2” to 4.2 as a Double value.

Up until this point, the NumberFormatter class simply duplicates the String and Double keywords to convert a number to a string or a string to a number. What makes the NumberFormatter class unique is that it offers the ability to spell out a number:

var myNumber = NumberFormatter()
myNumber.numberStyle = .spellOut

var x = myNumber.string(from: 742.409)

The first line defines an object called myNumber based on the NumberFormatter class. Then the second line defines the numberStyle property as .spellOut, which means it converts a number into actual words.

The third line above creates a string from the number 742.409 but spells this out as the string “seven hundred forty-two point four zero nine”, which it stores into the variable x.

The NumberFormatter class is just one of those oddball classes that you may find useful once in a while, so experiment with the NumberFormatter in a Swift playground and see how it works for yourself.

Posted in Algorithms

May 15th, 2017 by admin

Safety is crucial in most modern programming languages because programs that allow the wrong types of data will likely fail or crash the program completely. That’s why real-time avionics programs that control jet airliners rely on safe programming languages like Ada.

Swift emphasizes safety as well, and one feature that Swift offers is called the guard statement. The basic structure of the guard statement looks like this:

guard (condition) else {
        return
    }
// do something here

The guard statement looks to make sure a condition is true. If the condition is false, then exit out of a function without running any code.

By placing a guard statement at the beginning of a function, you can check to make sure all data is valid before running any code. A simple example of a guard statement might look like this, which you can paste and run in a Swift playground:

import Cocoa

func testGuard (myNumber: Int) {
    guard (myNumber % 2) == 0 else {
        print ("Odd number")
        return
    }
    print ("Even number")
}

testGuard (myNumber: 4)
testGuard (myNumber: 5)

This code checks to see if a number (stored in the myNumber variable), passed into a function, is an odd or even number. If it’s even, then the guard statement lets any code following run. If the number is odd, then the guard statement runs and the return command stops any further code from running in that function.

When you pass the number 4 into the testGuard function, the guard statement lets it run the testGuard code, which prints “Even number”. When you pass the number 5 into the testGuard function, the guard statement catches it, prints “Odd number”, and then exits out of the function.

By placing a guard statement at the beginning of each function, you can make sure that function only receives valid data. By using the guard statement, you can make your code more reliably.

Posted in Algorithms

May 4th, 2017 by admin

When you create a macOS project that uses storyboards, each window is called a view, which has a border. Two ways to modify the border of a view is to change its width and change its color.

To change the view’s border width, you need to use the borderWidth property like this:

self.view.layer?.borderWidth = 5

One way to make it easy to change the width of a border is to use a slider. Then create an IBOutlet for that slider along with an IBAction method like this:

@IBOutlet weak var borderSlider: NSSlider!

@IBAction func sliderChanged(_ sender: NSSlider) {
        self.view.layer?.borderWidth = CGFloat(borderSlider.intValue)
}

To change the view’s border color, you need to use the borderColor property like this:

self.view.layer?.borderColor = NSColor.blue.cgColor

The simplest way to change the border color is through a color well. Just create an IBOutlet and an IBAction method for that color well, in addition to overriding the changeColor function like this:

@IBOutlet weak var colorWell: NSColorWell!

@IBAction func pickColor(_ sender: NSColorWell) {
        colorWell.activate(true)
        colorWell.action = #selector(changeColor)
}
    
override func changeColor(_ sender: Any?) {
        self.view.layer?.borderColor = colorWell.color.cgColor
}

If you have a slider and a color well on your view, users can drag the slider back and forth to modify the border width and click on the color well to choose a different color for that border. You can download a sample program that shows how this works:

BorderSetting sample program.

Posted in Algorithms, User Interface

April 29th, 2017 by admin

Most of the time if you want text to appear on your user interface, you just type it directly into your user interface, such as editing a text field or label. You can also create and edit text using the Attributes Inspector pane as well, but if you need to display large amounts of text, it’s often easier to create and edit that text in a separate file.

Once you create a separate text file (not stored in a word processor format like the Microsoft Word .docx file format), you can then drag and drop that text file into the Project navigator pane.

When you drag and drop a file in the Project navigator pane, a window will appear to display options for adding a file. Make sure the “Copy items if needed” check box is selected.

To retrieve a file, you must specify the filename and extension. If you stored text in a file called “Xcode.txt,” then the filename would be “Xcode” and the extension would be “txt”.

If the text file exists, then you can store the contents of that file in a variable name. If the file can’t load or the file you specify isn’t found, then you need to handle this possible error so your program doesn’t crash. You can do all this with the following code:

        if let filepath = Bundle.main.path(forResource: "Xcode", ofType: "txt") {
            do {
                let contents = try String(contentsOfFile: filepath)
            } catch {
                // Contents could not be loaded
            }
        } else {
            // Xcode.txt file not found!
        }

The above code would store the contents of the “Xcode.txt” file in the “contents” variable. Just remember that if your file were called “Data.asc” then the above code would replace “Xcode” with “Data” and “txt” with “asc”.

To see how this works in a simple macOS program, download and run the following sample program that displays a text view in a window and a push button. By clicking on the push button, you can load the contents of the Xcode.txt file:

TextImport

Posted in Algorithms

April 25th, 2017 by admin

An array typically contains items of the same data type such as strings or integers. To declare an array to hold a specific data type, you just need to state the data type inside square brackets like this:

var beasts = [String] ()

Then you can just add items to the array using the append command like this:

beasts.append("tiger")
beasts.append("bear")
beasts.append("duck")

You can also define an array just by stuffing it with data right away like this:

var pets = ["Fido", "Rover", "Puff", "Goldy", "Pete"]

Once you fill an array with data, you can sort it using the sorted() method like this:

var beasts = [String] ()

beasts.append("tiger")
beasts.append("bear")
beasts.append("duck")

beasts.sorted()

This would create a sorted array that contains [“bear”, “duck”, “tiger”]. In the above code, the array appears sorted but the original beasts array is actually still unsorted. If you want to save the sorted results, you must store them in a new variable like this:

var pets = ["Fido", "Rover", "Puff", "Goldy", "Pete"]

let newArray : [String]
newArray = pets.sorted()

let sameArray = pets.sorted()

In this code, newArray is defined as an array of String data types. Then the sorted() data gets stored in the newArray variable.

Of course, you could just declare a new variable and store the sorted results in that new variable in one line. In the above example, sameArray is defined and given a value of sorted array data all in one line.

Typically an array doesn’t contain just one data type like a String or Int, but a structure that contains multiple fields such as the following:

struct Contacts {
    var first: String
    var last: String
    var phone: String
}

var rolodexFile = [Contacts] ()

This code creates an array of structures called Contacts where each Contact contains a first, last, and phone field that can hold a String data type. To create a structure, you need to define a variable and data for each field in that structure like this:

var employee = Contacts(first: "Fred", last: "Zimmerman", phone: "555-1234")

var prospect = Contacts(first: "Susan", last: "Acker", phone: "555-7894")

var salesContact = Contacts(first: "Bill", last: "Miller", phone: "555-2456")

This creates three variables (employee, prospect, and salesContact) that each contain a first, last, and phone string data. To add these structures to an array, you can just use the append command like this:

rolodexFile.append(employee)
rolodexFile.append(prospect)
rolodexFile.append(salesContact)

This creates an array that holds three structures. The first structure in the array is the name “Fred Zimmerman,” the second structure is “Susan Acker” and the third structure is “Bill Miller.”

Now to sort this array, you must specify the field to sort on. If we wanted to sort by the “last” field, you would use the sorted command like this:

let sortedContacts = rolodexFile.sorted {
    $0.last < $1.last
}

The above code would create sortedContacts array where the first structure is the name “Susan Acker,” the second structure is “Bill Miller” and the third structure is “Fred Zimmerman.”

The entire code for defining a structure, creating variables to store data in structures, creating an array of structures, and then sorting that array of structures would look like this in a Swift playground:

struct Contacts {
    var first: String
    var last: String
    var phone: String
}

var rolodexFile = [Contacts] ()

var employee = Contacts(first: "Fred", last: "Zimmerman", phone: "555-1234")

var prospect = Contacts(first: "Susan", last: "Acker", phone: "555-7894")

var salesContact = Contacts(first: "Bill", last: "Miller", phone: "555-2456")


rolodexFile.append(employee)
rolodexFile.append(prospect)
rolodexFile.append(salesContact)

let sortedContacts = rolodexFile.sorted {
    $0.last < $1.last
}

With an array of structures, you can sort on individual fields.

Posted in Algorithms

HTML Snippets Powered By : XYZScripts.com