A concise way to not execute a loop now that C-Style for loops are going to be removed from Swift 3? - swift

Imagine we have this code which works perfectly for n >= 0.
func fibonacci(n: Int) -> Int {
var memo = [0,1]
for var i = 2; i <= n; i++ {
memo.append(memo[i-1] + memo[i-2])
}
return memo[n]
}
If I remove the C-style for loop due to upcoming changes to Swift 3.0, I get something like this:
func fibonacci(n: Int) -> Int {
var memo = [0,1]
for i in 2...n {
memo.append(memo[i-1] + memo[i-2])
}
return memo[n]
}
While this works fine for n >= 2, it fails for the numbers 0 and 1 with this error message:
fatal error: Can't form Range with end < start
What's the most concise way to fix this code so it works properly for 0 and 1?
(Note: It's okay, and even desirable, for negative numbers to crash the app.)
Note: I realize I could add a guard statement:
guard n >= 2 else { return memo[n] }
... but I'm hoping there is a better way to fix just the faulty part of the code (2...n).
For example, if there was a concise way to create a range that returns zero elements if end < start, that would be a more ideal solution.

To do this in a way that works for n < 2, you can use the stride method.
let startIndex = 2
let endIndex = n
for i in stride(from: startIndex, through: endIndex, by: 1) {
memo.append(memo[i-1] + memo[i-2])
}

You can easily create a valid range with the max() function:
for i in 2 ..< max(2, n+1) {
memo.append(memo[i-1] + memo[i-2])
}
This evaluates to an empty range 2 ..< 2 if n < 2.
It is important to use the ..< operator which excludes the upper bound because 2 ... 1 is not a valid range.
But in this function I would simply treat the special cases first
func fibonacci(n: Int) -> Int {
// Let it crash if n < 0:
precondition(n >= 0, "n must not be negative")
// Handle n = 0, 1:
if n <= 1 {
return n
}
// Handle n >= 2:
var memo = [0,1]
for i in 2 ... n {
memo.append(memo[i-1] + memo[i-2])
}
return memo[n]
}
(Note that your memo array is set to the initial value [0, 1]
for each function call, so the values are not really "memoized".
Without memoization you don't need an array, it would suffice to keep the last two numbers to compute the next.)

As it turns out, the variable i will always be equal to the count of the memoizing array, so you can just use that as your loop condition:
func fibonacci(n: Int) -> Int {
var memo = [0,1]
while n >= memo.count {
memo.append(memo[memo.count-1] + memo[memo.count-2])
}
return memo[n]
}
Alternatively, you could express the loop as a recursive function:
func fibonacci(n: Int) -> Int {
var memo = [0,1]
func rec(i: Int) -> Int {
if i >= memo.count { memo.append(rec(i-2) + rec(i-1)) }
return memo[i]
}
return rec(n)
}
Really, though, if is the best solution here. Ranges don't allow the end to be smaller than the beginning by design. The extra line for:
func fibonacci(n: Int) -> Int {
if n < 2 { return n }
var memo = [0,1]
for i in 2...n {
memo.append(memo[i-1] + memo[i-2])
}
return memo[n]
}
Is readable and understandable. (To my eye, the code above is better than the for ;; version)

#Marc's answer is great: https://stackoverflow.com/a/34324032/1032900
But the stride syntax is too long for frequent usage, so I made it a little more pleasant for the common i++ usages...
extension Strideable {
#warn_unused_result
public func stride(to end: Self) -> StrideTo<Self> {
return stride(to: end, by: 1)
}
}
extension Strideable {
#warn_unused_result
public func stride(thru end: Self) -> StrideThrough<Self> {
return stride(through: end, by: 1)
}
}
So use like this:
for i in startPos.stride(to: endPos) {
print("pos at: \(i)")
}

Related

Check if array contains any even numbers and then show lowest even (or odd if no evens present)

In a function, I want to first check if the array given contains any numbers.
If there is an even number in the array I want to show the smallest number, and if there aren't any even numbers I want to at least show the smallest odd number whilst informing the user there are no even numbers.
The issue I have run into is: if there is a lower odd number in the array than the lowest even number it will ignore the fact that there is an even number in the array.
My progress to solving this was to first be able to determine the smallest number in an array
func smallestNumberInArray(listOfNumbers numbers: [Int]) -> Int {
var smallestNumber = numbers[0]
for x in numbers {
if x < smallestNumber {
smallestNumber = x
}
}
return smallestNumber
}
I then test it with smallestNumberInArray(listOfNumbers: [33, 44, 10, 22222, 099, 83]) which prints out 10
To test the even or odd logic I simply did
var listOfNumbers = [200, 3, 202]
for x in listOfNumbers {
if x % 2 == 0 {
print("\(x)")
}
}
Which printed out 200 and 202
I tried to combine this into 1 function
func checkSmallestEvenNumber(yourNumbers numbers: [Int]) -> String {
var smallestNumber = numbers[0]
var returnString = "Placeholder"
for x in numbers {
if x % 2 == 0 {
if x < smallestNumber {
smallestNumber = x
returnString = "The smallest even number is: \(smallestNumber)"
}
} else {
if x < smallestNumber && x % 2 != 0 {
smallestNumber = x
returnString = "No Evens, but the smallest odd is: \(smallestNumber)"
}
}
}
return returnString
}
So my function call checkSmallestEvenNumber(yourNumbers: [29, 33, 55, 22, 130, 101, 99]) returns The smallest even number is: 22 in this scenario, but if I change say the 55 to a 5 the return value is No Evens, but the smallest odd is: 5 when I want it to be 22 still.
Take advantage of higher level functions like filter with predicate isMultiple(of: 2) and min()
The result must be an optional to cover the case that the input array can be empty
func smallestNumberInArray(listOfNumbers numbers: [Int]) -> Int? {
if let smallestEvenNumber = numbers.filter({$0.isMultiple(of: 2)}).min() { return smallestEvenNumber }
return numbers.min()
}
smallestNumberInArray(listOfNumbers: [29, 33, 5, 22, 130, 101, 99])
Alternatively – and probably more efficient – first sort the array then return the first even number or the first number which must be odd or – if the array is empty – return nil
func smallestNumberInArray(listOfNumbers numbers: [Int]) -> Int? {
let sortedArray = numbers.sorted()
return sortedArray.first{$0.isMultiple(of: 2)} ?? sortedArray.first
}
A third way is first to partition the array in even and odd numbers and get the smallest number of the slices
func smallestNumberInArray(listOfNumbers numbers: [Int]) -> Int? {
var mutableNumbers = numbers
let firstOddIndex = mutableNumbers.partition(by: {$0.isMultiple(of: 2)})
return mutableNumbers[firstOddIndex...].min() ?? mutableNumbers[0..<firstOddIndex].min()
}
There are a number of ways to fix it. I made some tweaks to your code
func checkSmallestEvenNumber(yourNumbers numbers: [Int]) -> String {
guard !numbers.isEmpty else {
return "Empty array"
}
var smallestNumber = numbers[0]
var returnString = ""
for x in numbers {
if x % 2 == 0,
(smallestNumber % 2 != 0 || x < smallestNumber) {
smallestNumber = x
print(smallestNumber)
returnString = "The smallest even number is: \(smallestNumber)"
} else if x < smallestNumber,
smallestNumber % 2 != 0,
x % 2 != 0 {
smallestNumber = x
returnString = "No Evens, but the smallest odd is: \(smallestNumber)"
}
}
if returnString.isEmpty {
if smallestNumber % 2 == 0 {
returnString = "The smallest even number is: \(smallestNumber)"
} else {
returnString = "No Evens, but the smallest odd is: \(smallestNumber)"
}
}
return returnString
}
checkSmallestEvenNumber(yourNumbers: [0, 2, 23, 55, 130, 101, 55])
You should be throwing an error for odd numbers, not returning Strings.
extension Sequence where Element: BinaryInteger {
func lowestEvenNumber() throws -> Element {
switch (minima { $0.isMultiple(of: 2) }) {
case (_, let even?):
return even
case (let odd?, nil):
throw NoEvenNumbersError.onlyOdds(odd)
case (nil, nil):
throw NoEvenNumbersError<Element>.empty
}
}
}
enum NoEvenNumbersError<Integer: BinaryInteger>: Error {
case empty
case onlyOdds(Integer)
}
vadian's partitioning solution is good enough for your use case, but it's not applicable for all sequences. It should be. This is, and uses memory only for two elements:
public extension Sequence where Element: Comparable {
/// Two minima, with the second satisfying a partitioning criterion.
func minima(
partitionedBy belongsInSecondPartition: (Element) -> Bool
) -> (Element?, Element?) {
reduce(into: (nil, nil)) { minima, element in
let partitionKeyPath = belongsInSecondPartition(element) ? \(Element?, Element?).1 : \.0
if minima[keyPath: partitionKeyPath].map({ element < $0 }) ?? true {
minima[keyPath: partitionKeyPath] = element
}
}
}
}
I already marked #achu 's answer to be correct but as I mentioned in comments I figured it out moments after #achu answered.
Here is my less elegant solution: I separated the functionality into two functions and passed a function as a parameter in the main function.
func findLowestNumber(passingArray nums: [Int]) -> Int{
var small = nums[0]
for x in nums {
if x < small {
small = x
}
}
return small
}
I will use this mini function as a passing parameter later on
func checkSmallestEvenNumber(yourNumbers numbers: [Int]) -> String {
var parameterIntArray = numbers[0]
var allEvens = [Int]()
var str = "Placeholder"
for x in numbers {
if x % 2 != 0 {
str = "No Evens, however the lowest odd is \(findLowestNumber(passingArray: numbers))"
} else {
allEvens.append(x)
}
}
if allEvens.isEmpty != true {
str = "The lowest even is \(findLowestNumber(passingArray: allEvens))"
}
return str
}
What I did first was to check if any of the numbers were even. If none were then I created a string saying such but then passed the earlier function as a parameter to at least find the lowest odd.
The main fix was if there were any evens I appended them to a new array. Within this new array I again passed the earlier function to find the lowest number.
I'm sure this could be cleaned up (without using higher functions like map etc)
This function might not be "Swifty" (using higher order functions) but it will give a result with a single pass through the array:
func lowestEvenFromArray(_ intArray: [Int]) -> Int? {
var lowestEven: Int? = nil
var lowestOdd: Int? = nil
for value in intArray {
if value.isMultiple(of: 2) {
if value < (lowestEven ?? Int.max) {
lowestEven = value
}
} else if value < (lowestOdd ?? Int.max) {
lowestOdd = value
}
}
return lowestEven ?? lowestOdd
}
It should be the fastest of the answers given, all of which will make at least 2 passes through the array.

Factorial with intermediate results - Swift playgrounds - index out of range error

Getting blind from looking at this for too long. Can't spot the error.
Getting the "index out of range" error when calling the function factorialIntermediateResults(n: 4) Hope somebody can take a look with fresh eyes and help me spot the error. Thanks!
func factorialIntermediateResults(n: Int) -> [Int] {
if n == 0 || n == 1 { return [1] }
var results = [Int]()
doAllFactorials(n, &results, 0)
return results
}
func doAllFactorials(_ n: Int, _ results: inout [Int], _ level: Int) -> Int {
if n > 1 {
results[level] = n * doAllFactorials(n-1, &results, level+1)
return results[level]
} else {
results[level] = 1
return 1
}
}
factorialIntermediateResults(n: 4)
results is an empty array but you try to access values without appending values first.
The simplest solution might be to pre-populate your array with zeros.
var results: [Int] = Array(repeating: 0, count: n)

How to compare characters in Swift efficiently

I have a function in Swift that computes the hamming distance of two strings and then puts them into a connected graph if the result is 1.
For example, read to hear returns a hamming distance of 2 because read[0] != hear[0] and read[3] != hear[3].
At first, I thought my function was taking a long time because of the quantity of input (8,000+ word dictionary), but I knew that several minutes was too long. So, I rewrote my same algorithm in Java, and the computation took merely 0.3s.
I have tried writing this in Swift two different ways:
Way 1 - Substrings
extension String {
subscript (i: Int) -> String {
return self[Range(i ..< i + 1)]
}
}
private func getHammingDistance(w1: String, w2: String) -> Int {
if w1.length != w2.length { return -1 }
var counter = 0
for i in 0 ..< w1.length {
if w1[i] != w2[i] { counter += 1 }
}
return counter
}
Results: 434 seconds
Way 2 - Removing Characters
private func getHammingDistance(w1: String, w2: String) -> Int {
if w1.length != w2.length { return -1 }
var counter = 0
var c1 = w1, c2 = w2 // need to mutate
let length = w1.length
for i in 0 ..< length {
if c1.removeFirst() != c2.removeFirst() { counter += 1 }
}
return counter
}
Results: 156 seconds
Same Thing in Java
Results: 0.3 seconds
Where it's being called
var graph: Graph
func connectData() {
let verticies = graph.canvas // canvas is Array<Node>
// Node has key that holds the String
for vertex in 0 ..< verticies.count {
for compare in vertex + 1 ..< verticies.count {
if getHammingDistance(w1: verticies[vertex].key!, w2: verticies[compare].key!) == 1 {
graph.addEdge(source: verticies[vertex], neighbor: verticies[compare])
}
}
}
}
156 seconds is still far too inefficient for me. What is the absolute most efficient way of comparing characters in Swift? Is there a possible workaround for computing hamming distance that involves not comparing characters?
Edit
Edit 1: I am taking an entire dictionary of 4 and 5 letter words and creating a connected graph where the edges indicate a hamming distance of 1. Therefore, I am comparing 8,000+ words to each other to generate edges.
Edit 2: Added method call.
Unless you chose a fixed length character model for your strings, methods and properties such as .count and .characters will have a complexity of O(n) or at best O(n/2) (where n is the string length). If you were to store your data in an array of character (e.g. [Character] ), your functions would perform much better.
You can also combine the whole calculation in a single pass using the zip() function
let hammingDistance = zip(word1.characters,word2.characters)
.filter{$0 != $1}.count
but that still requires going through all characters of every word pair.
...
Given that you're only looking for Hamming distances of 1, there is a faster way to get to all the unique pairs of words:
The strategy is to group words by the 4 (or 5) patterns that correspond to one "missing" letter. Each of these pattern groups defines a smaller scope for word pairs because words in different groups would be at a distance other than 1.
Each word will belong to as many groups as its character count.
For example :
"hear" will be part of the pattern groups:
"*ear", "h*ar", "he*r" and "hea*".
Any other word that would correspond to one of these 4 pattern groups would be at a Hamming distance of 1 from "hear".
Here is how this can be implemented:
// Test data 8500 words of 4-5 characters ...
var seenWords = Set<String>()
var allWords = try! String(contentsOfFile: "/usr/share/dict/words")
.lowercased()
.components(separatedBy:"\n")
.filter{$0.characters.count == 4 || $0.characters.count == 5}
.filter{seenWords.insert($0).inserted}
.enumerated().filter{$0.0 < 8500}.map{$1}
// Compute patterns for a Hamming distance of 1
// Replace each letter position with "*" to create patterns of
// one "non-matching" letter
public func wordH1Patterns(_ aWord:String) -> [String]
{
var result : [String] = []
let fullWord : [Character] = aWord.characters.map{$0}
for index in 0..<fullWord.count
{
var pattern = fullWord
pattern[index] = "*"
result.append(String(pattern))
}
return result
}
// Group words around matching patterns
// and add unique pairs from each group
func addHamming1Edges()
{
// Prepare pattern groups ...
//
var patternIndex:[String:Int] = [:]
var hamming1Groups:[[String]] = []
for word in allWords
{
for pattern in wordH1Patterns(word)
{
if let index = patternIndex[pattern]
{
hamming1Groups[index].append(word)
}
else
{
let index = hamming1Groups.count
patternIndex[pattern] = index
hamming1Groups.append([word])
}
}
}
// add edge nodes ...
//
for h1Group in hamming1Groups
{
for (index,sourceWord) in h1Group.dropLast(1).enumerated()
{
for targetIndex in index+1..<h1Group.count
{ addEdge(source:sourceWord, neighbour:h1Group[targetIndex]) }
}
}
}
On my 2012 MacBook Pro, the 8500 words go through 22817 (unique) edge pairs in 0.12 sec.
[EDIT] to illustrate my first point, I made a "brute force" algorithm using arrays of characters instead of Strings :
let wordArrays = allWords.map{Array($0.unicodeScalars)}
for i in 0..<wordArrays.count-1
{
let word1 = wordArrays[i]
for j in i+1..<wordArrays.count
{
let word2 = wordArrays[j]
if word1.count != word2.count { continue }
var distance = 0
for c in 0..<word1.count
{
if word1[c] == word2[c] { continue }
distance += 1
if distance > 1 { break }
}
if distance == 1
{ addEdge(source:allWords[i], neighbour:allWords[j]) }
}
}
This goes through the unique pairs in 0.27 sec. The reason for the speed difference is the internal model of Swift Strings which is not actually an array of equal length elements (characters) but rather a chain of varying length encoded characters (similar to the UTF model where special bytes indicate that the following 2 or 3 bytes are part of a single character. There is no simple Base+Displacement indexing of such a structure which must always be iterated from the beginning to get to the Nth element.
Note that I used unicodeScalars instead of Character because they are 16 bit fixed length representations of characters that allow a direct binary comparison. The Character type isn't as straightforward and take longer to compare.
Try this:
extension String {
func hammingDistance(to other: String) -> Int? {
guard self.characters.count == other.characters.count else { return nil }
return zip(self.characters, other.characters).reduce(0) { distance, chars in
distance + (chars.0 == chars.1 ? 0 : 1)
}
}
}
print("read".hammingDistance(to: "hear")) // => 2
The following code executed in 0.07 secounds for 8500 characters:
func getHammingDistance(w1: String, w2: String) -> Int {
if w1.characters.count != w2.characters.count {
return -1
}
let arr1 = Array(w1.characters)
let arr2 = Array(w2.characters)
var counter = 0
for i in 0 ..< arr1.count {
if arr1[i] != arr2[i] { counter += 1 }
}
return counter
}
After some messing around, I found a faster solution to #Alexander's answer (and my previous broken answer)
extension String {
func hammingDistance(to other: String) -> Int? {
guard !self.isEmpty, !other.isEmpty, self.characters.count == other.characters.count else {
return nil
}
var w1Iterator = self.characters.makeIterator()
var w2Iterator = other.characters.makeIterator()
var distance = 0;
while let w1Char = w1Iterator.next(), let w2Char = w2Iterator.next() {
distance += (w1Char != w2Char) ? 1 : 0
}
return distance
}
}
For comparing strings with a million characters, on my machine it's 1.078 sec compared to 1.220 sec, so roughly a 10% improvement. My guess is this is due to avoiding .zip and the slight overhead of .reduce and tuples
As others have noted, calling .characters repeatedly takes time. If you convert all of the strings once, it should help.
func connectData() {
let verticies = graph.canvas // canvas is Array<Node>
// Node has key that holds the String
// Convert all of the keys to utf16, and keep them
let nodesAsUTF = verticies.map { $0.key!.utf16 }
for vertex in 0 ..< verticies.count {
for compare in vertex + 1 ..< verticies.count {
if getHammingDistance(w1: nodesAsUTF[vertex], w2: nodesAsUTF[compare]) == 1 {
graph.addEdge(source: verticies[vertex], neighbor: verticies[compare])
}
}
}
}
// Calculate the hamming distance of two UTF16 views
func getHammingDistance(w1: String.UTF16View, w2: String.UTF16View) -> Int {
if w1.count != w2.count {
return -1
}
var counter = 0
for i in w1.startIndex ..< w1.endIndex {
if w1[i] != w1[i] {
counter += 1
}
}
return counter
}
I used UTF16, but you might want to try UTF8 depending on the data. Since I don't have the dictionary you are using, please let me know the result!
*broken*, see new answer
My approach:
private func getHammingDistance(w1: String, w2: String) -> Int {
guard w1.characters.count == w2.characters.count else {
return -1
}
let countArray: Int = w1.characters.indices
.reduce(0, {$0 + (w1[$1] == w2[$1] ? 0 : 1)})
return countArray
}
comparing 2 strings of 10,000 random characters took 0.31 seconds
To expand a bit: it should only require one iteration through the strings, adding as it goes.
Also it's way more concise 🙂.

How to split or iterate over an Int without converting to String in Swift [duplicate]

This question already has answers here:
Break A Number Up To An Array of Individual Digits
(6 answers)
Closed 5 years ago.
I was wondering if there was a way in Swift to split an Int up into it's individual digits without converting it to a String. For example:
let x: Int = 12345
//Some way to loop/iterate over x's digits
//Then map each digit in x to it's String value
//Return "12345"
For a bit of background, I'm attempting to create my own method of converting an Int to a String without using the String description property or using String Interpolation.
I've found various articles on this site but all the ones I've been able to find either start with a String or end up using the String description property to convert the Int to a String.
Thanks.
Just keep dividing by 10 and take the remainder:
extension Int {
func digits() -> [Int] {
var digits: [Int] = []
var num = self
repeat {
digits.append(num % 10)
num /= 10
} while num != 0
return digits.reversed()
}
}
x.digits() // [1,2,3,4,5]
Note that this will return all negative digits if the value is negative. You could add a special case if you want to handle that differently. This return [0] for 0, which is probably what you want.
And because everyone like pure functional programming, you can do it that way too:
func digits() -> [Int] {
let partials = sequence(first: self) {
let p = $0 / 10
guard p != 0 else { return nil }
return p
}
return partials.reversed().map { $0 % 10 }
}
(But I'd probably just use the loop here. I find sequence too tricky to reason about in most cases.)
A recursive way...
extension Int {
func createDigitArray() -> [Int] {
if self < 10 {
return [self]
} else {
return (self / 10).createDigitArray() + [self % 10]
}
}
}
12345.createDigitArray() //->[1, 2, 3, 4, 5]
A very easy approach would be using this function:
func getDigits(of number: Int) -> [Int] {
var digits = [Int]()
var x = number
repeat{
digits.insert(abs(x % 10), at: 0)
x/=10
} while x != 0
return digits
}
And using it like this:
getDigits(of: 97531) // [9,7,5,3,1]
getDigits(of: -97531) // [9,7,5,3,1]
As you can see, for a negative number you will receive the array of its digits, but at their absolute value (e.g.: -9 => 9 and -99982 => 99982)
Hope it helps!

Converting a C-style for loop that uses division for the step to Swift 3

I have this loop, decrementing an integer by division, in Swift 2.
for var i = 128; i >= 1 ; i = i/2 {
//do some thing
}
The C-style for loop is deprecated, so how can I convert this to Swift 3.0?
Quite general loops with a non-constant stride can be realized
with sequence:
for i in sequence(first: 128, next: { $0 >= 2 ? $0/2 : nil }) {
print(i)
}
Advantages: The loop variable i is a constant and its scope is
restricted to the loop body.
Possible disadvantages: The terminating condition must be adapted
(here: $0 >= 2 instead of i >= 1), and the loop is always executed
at least once, for the first value.
One could also write a wrapper which resembles the C-style for loop
more closely and does not have the listed disadvantages
(inspired by Erica Sadun: Stateful loops and sequences):
public func sequence<T>(first: T, while condition: #escaping (T)-> Bool, next: #escaping (T) -> T) -> UnfoldSequence<T, T> {
let nextState = { (state: inout T) -> T? in
guard condition(state) else { return nil }
defer { state = next(state) }
return state
}
return sequence(state: first, next: nextState)
}
and then use it as
for i in sequence(first: 128, while: { $0 >= 1 }, next: { $0 / 2 }) {
print(i)
}
MartinR's solution is very generic and useful and should be part of your toolbox.
Another approach is to rephrase what you want: the powers of two from 7 down to 0.
for i in (0...7).reversed().map({ 1 << $0 }) {
print(i)
}
I'll suggest that you should use a while loop to handle this scenario:
var i = 128
while i >= 1
{
// Do your stuff
i = i / 2
}