How do I pick the nearest element in an array in Swift? - arrays

I was surprised I could not find a thread on this, but I need to check a series of arrays for a specific value, and if not present, check if the value falls between the max and min value, and then choose the closest, most negative value to assign to a variable.
I attempted to accomplish this with the function below, but it yields a compiler error: Cannot call value of non-function type "Float!"
Is there any way to overcome the compiler error, or should I try a different approach?
func nearestElement(powerD : Float, array : [Float]) -> Float {
var n = 0
var nearestElement : Float!
while array[n] <= powerD {
n++;
}
nearestElement = array[n] // error: Cannot call value of non-function type "Float!"
return nearestElement;
}
I'd like to then call nearestElement() when I check each array, within arrayContains():
func arrayContains(array: [Float], powerD : Float) {
var nearestElement : Float!
if array.minElement() < powerD && powerD < array.maxElement() {
if array.contains(powerD) {
contactLensSpherePower = vertexedSpherePower
} else {
contactLensSpherePower = nearestElement(powerD, array)
}
}
}

Is there any way to overcome the compiler error, or should I try a different approach?
First, it's worth noting the behavior is largely dependent upon the version of Swift you're using.
In general though, your issue is with naming a variable the same as a method:
func nearestElement(powerD : Float, array : [Float]) -> Float {
var n = 0
var nearestElement : Float! //<-- this has the same name as the function
while array[n] <= powerD {
n++;
}
nearestElement = array[n] // error: Cannot call value of non-function type "Float!"
return nearestElement;
}
Also, in arrayContains, you'll also want to rename var nearestElement : Float! so there's no ambiguity there as well.

Optimised solution using higher order functions:
func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}
Swift is advancing with every version to optimise the performance and efficiency. With higher order functions finding the closest match in an array of values is much easier with this implementation. Change the type of value as per your need.

Related

How do I call my binary search function in swift?

I'm an old C programmer. I'm trying to implement some code in Swift and needed a binary search algorithm that would return the closest element if an exact match isn't available.
I searched for a bit and either the code was invoking so many Swift concepts at once as to be opaque to my C eyes or it wasn't suitable for my use case.
I decided to port some old C code to get the job done and wrote the following:
public func bsearch(arr:[Any], target:Double, bcompare:(Any,Double)->Int)-> Int{
// v is array being searched
// target is what we're looking for
// bcompare is a pointer to user-supplied comparison function
// bcompare returns -1 if left element < right element, 0 if =, 1 if >
// target must be same type as v element being compared
// returns index of array element that is closest to <= target
// note! indexed returned may not match target value
var lo, hi, mid:Int
hi = v.count-1
if hi <= 0 {return -1}
lo = 0
while ((hi-lo) > 1) {
mid = (hi+lo)/2
if( bcompare(v[mid], target) == -1){
lo = mid + 1
}
else{
hi = mid
}
}
if bcompare(v[hi],target) == 0{
return hi
}
return lo
}
func eleCompare(left:locArrayele,right:Double)->Int{
if right < left.degrees{
return -1
}
else if right == left.degrees{
return 0
}
else {
return 1
}
}
In C, you can pass search functions pointers to structures and tell the compiler how to interpret the memory blocks in the comparison functions that you also pass to the search function. The comparison function reference is just another memory pointer and no parameters are needed.
I assumed a Swift "Any" declaration was equivalent to a pointer reference and wrote the above code with that idea in mind. The compiler complained about declaring the search target as an Any when the comparison function referred to the target as a double. To satisfy the compiler, I declared the target as a double and the code compiled fine.
My problem now is to actually test the code. No matter how I try to invoke the search function, the compiler is unhappy. This test snippet is the closest I could get to satisfying the compiler.
class locArrayele{
public var degrees = CLLocationDegrees()
public var ix = Int()
init( degrees:CLLocationDegrees, i:Int){
self.degrees = degrees
self.ix = i
}
}
public var latArray : [locArrayele] = []
.
.
.
ix = bsearch(v: latArray, target:35.0, bcompare: eleCompare )
print(" when lat is 35, closest ix is \(ix))
Apparently, the compiler wants me to supply parameters to eleCompare, a task I expect bsearch to do as it executes.
How do I invoke the code? I realize I'm c-ifing Swift but I'm just trying to get something to work. Elegance can come later as I get comfortable in the language.
You need to make your bsearch() generic. You have two types that can vary: the first type is the one that the array v contains, and the other is the target's type.
Change your first line to:
public func bsearch<T, U>(v: [T], target: U, bcompare: (T, U) -> Int) -> Int {
You don't have to use 2 different types when you call it, but you can.
Example: String and Int
This example has an array of words of type [String] and it is searching for the word with 5 letters, so the target in an Int.
let words = ["a", "to", "the", "seven", "butter"]
func compareNameLength(left: String, right: Int) -> Int {
if left.count < right {
return -1
} else if left.count == right {
return 0
} else {
return 1
}
}
// search for the 5 letter word
let i = bsearch(v: words, target: 5, bcompare: compareNameLength)
print(words[i])
seven
Example: Int and Int
This example has an [Int] containing prime numbers, and it is searching for a prime closest to a number without going over, so the target is an Int.
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
func compareInt(left: Int, right: Int) -> Int {
if left < right {
return -1
} else if left == right {
return 0
} else {
return 1
}
}
// search for closest prime to 8
let p = bsearch(v: primes, target: 8, bcompare: compareInt)
print(primes[p])
7

Swift: Ambiguous reference to member '+' when using .sorted on optional

I am trying to use .sorted on an array whose properties are optional, and I get this error:
Ambiguous reference to member '+'
I'm not sure how to deal with the optional here, and adding ! to force unwrap doesn't work (I am certain the array will have a value by the time this code runs).
let sortedoptions = decisions[selectedDecision].options.sorted(by: { $0.ratings.reduce(0, +) < $1.ratings.reduce(0, +) } )
And the Options class:
struct Option: Codable {
var title: String
var ratings: [Int?]
}
Would anyone know how to fix this please?
This can be fixed by
let sortedoptions = decisions[selectedDecision].options.sorted(by: { $0.ratings.reduce(0, {x,y in x + y!}) < $1.ratings.reduce(0, {x,y in x + y!})} )
This is because as the error says addition cannot be performed on two Int? types.
Also this is assuming the array values will never be nil
Safer option would be to replace y! by y ?? 0

Type Int does not conform to protocol sequence

I have the following code in Swift 3:
var numbers = [1,2,1]
for number in numbers.count - 1 { // error
if numbers[number] < numbers[number + 1] {
print(number)
}
}
I am checking if the value on the index [number] is always higher than the value on the index [number + 1]. I am getting an error:
Type Int does not conform to protocol sequence
Any idea?
It may be swift.
You can use this iteration.
for number in 0..<(numbers.count-1)
The error is because Int is not a Sequence. You can create a range as already suggested, which does conform to a sequence and will allow iteration using for in.
One way to make Int conform to a sequence is:
extension Int: Sequence {
public func makeIterator() -> CountableRange<Int>.Iterator {
return (0..<self).makeIterator()
}
}
Which would then allow using it as a sequence with for in.
for i in 5 {
print(i)
}
but I wouldn't recommend doing this. It's only to demonstrate the power of protocols but would probably be confusing in an actual codebase.
From you example, it looks like you are trying to compare consecutive elements of the collection. A custom iterator can do just that while keeping the code fairly readable:
public struct ConsecutiveSequence<T: IteratorProtocol>: IteratorProtocol, Sequence {
private var base: T
private var index: Int
private var previous: T.Element?
init(_ base: T) {
self.base = base
self.index = 0
}
public typealias Element = (T.Element, T.Element)
public mutating func next() -> Element? {
guard let first = previous ?? base.next(), let second = base.next() else {
return nil
}
previous = second
return (first, second)
}
}
extension Sequence {
public func makeConsecutiveIterator() -> ConsecutiveSequence<Self.Iterator> {
return ConsecutiveSequence(self.makeIterator())
}
}
which can be used as:
for (x, y) in [1,2,3,4].makeConsecutiveIterator() {
if (x < y) {
print(x)
}
}
In the above example, the iterator will go over the following pairs:
(1, 2)
(2, 3)
(3, 4)
This maybe a little late but you could have done:
for number in numbers { }
instead of:
for number in numbers.count - 1 { }
For a for loop to work a sequence (range) is needed. A sequence consists of a stating a value, an ending value and everything in between. This means that a for loop can be told to loop through a range with ether
for number in 0...numbers.count-1 { } `or` for number in numbers { }
Both example give the nesasery sequences. Where as:
for number in numbers.count - 1 { }
Only gives one value that could either be the starting or the ending value, making it impossible to work out how many time the for loop will have to run.
For more information see Apple's swift control flow documnetation
This error can also come about if you try to enumerate an array instead of the enumerated array. For example:
for (index, element) in [0, 3, 4] {
}
Should be:
for (index, element) in [0, 3, 4].enumerated() {
}
So first you need to understand what is sequence..
A type that provides sequential, iterated access to its elements.
A sequence is a list of values that you can step through one at a time. The most common way to iterate over the elements of a sequence is to use a for-in loop:
let oneTwoThree = 1...3. // Sequence
for loop actually means
For number in Sequences {}
So you need to use
for number in 0..<(numbers.count-1) {}
The error is because number is not an index, but the element of the array on each iteration. You can modify your code like this:
var numbers = [1,2,1,0,3]
for number in 0..<numbers.count - 1 {
if numbers[number] < numbers[number + 1] {
print(numbers[number])
}
}
Or there is a trick using the sort method, but that's kind of a hack (and yes, the subindexes are right, but look like inverted; you can try this directly on a Playground):
var numbers = [1,2,1,0,3]
numbers.sort {
if $0.1 < $0.0 {
print ($0.1)
}
return false
}
For me, this error occurred when I tried writing a for loop, not for an array but a single element of the array.
For example:
let array = [1,2,3,4]
let item = array[0]
for its in item
{
print(its)
}
This gives an error like: Type Int does not conform to protocol 'sequence'
So, if you get this error in for loop, please check whether you are looping an array or not.

Swift Array extension for standard deviation

I am frequently needing to calculate mean and standard deviation for numeric arrays. So I've written a small protocol and extensions for numeric types that seems to work. I just would like feedback if there is anything wrong with how I have done this. Specifically, I am wondering if there is a better way to check if the type can be cast as a Double to avoid the need for the asDouble variable and init(_:Double) constructor.
I know there are issues with protocols that allow for arithmetic, but this seems to work ok and saves me from putting the standard deviation function into classes that need it.
protocol Numeric {
var asDouble: Double { get }
init(_: Double)
}
extension Int: Numeric {var asDouble: Double { get {return Double(self)}}}
extension Float: Numeric {var asDouble: Double { get {return Double(self)}}}
extension Double: Numeric {var asDouble: Double { get {return Double(self)}}}
extension CGFloat: Numeric {var asDouble: Double { get {return Double(self)}}}
extension Array where Element: Numeric {
var mean : Element { get { return Element(self.reduce(0, combine: {$0.asDouble + $1.asDouble}) / Double(self.count))}}
var sd : Element { get {
let mu = self.reduce(0, combine: {$0.asDouble + $1.asDouble}) / Double(self.count)
let variances = self.map{pow(($0.asDouble - mu), 2)}
return Element(sqrt(variances.mean))
}}
}
edit: I know it's kind of pointless to get [Int].mean and sd, but I might use numeric elsewhere so it's for consistency..
edit: as #Severin Pappadeux pointed out, variance can be expressed in a manner that avoids the triple pass on the array - mean then map then mean. Here is the final standard deviation extension
extension Array where Element: Numeric {
var sd : Element { get {
let sss = self.reduce((0.0, 0.0)){ return ($0.0 + $1.asDouble, $0.1 + ($1.asDouble * $1.asDouble))}
let n = Double(self.count)
return Element(sqrt(sss.1/n - (sss.0/n * sss.0/n)))
}}
}
Swift 4 Array extension with FloatingPoint elements:
extension Array where Element: FloatingPoint {
func sum() -> Element {
return self.reduce(0, +)
}
func avg() -> Element {
return self.sum() / Element(self.count)
}
func std() -> Element {
let mean = self.avg()
let v = self.reduce(0, { $0 + ($1-mean)*($1-mean) })
return sqrt(v / (Element(self.count) - 1))
}
}
There's actually a class that provides this functionality already - called NSExpression. You could reduce your code size and complexity by using this instead. There's quite a bit of stuff to this class, but a simple implementation of what you want is as follows.
let expression = NSExpression(forFunction: "stddev:", arguments: [NSExpression(forConstantValue: [1,2,3,4,5])])
let standardDeviation = expression.expressionValueWithObject(nil, context: nil)
You can calculate mean too, and much more. Info here: http://nshipster.com/nsexpression/
In Swift 3 you might (or might not) be able to save yourself some duplication with the FloatingPoint protocol, but otherwise what you're doing is exactly right.
To follow up on Matt's observation, I'd do the main algorithm on FloatingPoint, taking care of Double, Float, CGFloat, etc. But then I then do another permutation of this on BinaryInteger, to take care of all of the integer types.
E.g. on FloatingPoint:
extension Array where Element: FloatingPoint {
/// The mean average of the items in the collection.
var mean: Element { return reduce(Element(0), +) / Element(count) }
/// The unbiased sample standard deviation. Is `nil` if there are insufficient number of items in the collection.
var stdev: Element? {
guard count > 1 else { return nil }
return sqrt(sumSquaredDeviations() / Element(count - 1))
}
/// The population standard deviation. Is `nil` if there are insufficient number of items in the collection.
var stdevp: Element? {
guard count > 0 else { return nil }
return sqrt(sumSquaredDeviations() / Element(count))
}
/// Calculate the sum of the squares of the differences of the values from the mean
///
/// A calculation common for both sample and population standard deviations.
///
/// - calculate mean
/// - calculate deviation of each value from that mean
/// - square that
/// - sum all of those squares
private func sumSquaredDeviations() -> Element {
let average = mean
return map {
let difference = $0 - average
return difference * difference
}.reduce(Element(0), +)
}
}
But then on BinaryInteger:
extension Array where Element: BinaryInteger {
var mean: Double { return map { Double(exactly: $0)! }.mean }
var stdev: Double? { return map { Double(exactly: $0)! }.stdev }
var stdevp: Double? { return map { Double(exactly: $0)! }.stdevp }
}
Note, in my scenario, even when dealing with integer input data, I generally want floating point mean and standard deviations, so I arbitrarily chose Double. And you might want to do safer unwrapping of Double(exactly:). You can handle this scenario any way you want. But it illustrates the idea.
Not that I know Swift, but from numerics POV you're doing it a bit inefficiently
Basically, you're doing two passes (actually, three) over the array to compute two values, where one pass should be enough. Vairance might be expressed as E(X2) - E(X)2, so in some pseudo-code:
tuple<float,float> get_mean_sd(data) {
float s = 0.0f;
float s2 = 0.0f;
for(float v: data) {
s += v;
s2 += v*v;
}
s /= count;
s2 /= count;
s2 -= s*s;
return tuple(s, sqrt(s2 > 0.0 ? s2 : 0.0));
}
Just a heads-up, but when I tested the code outlined by Severin Pappadeux the result was a "population standard deviation" rather than a "sample standard deviation". You would use the first in an instance where 100% of the relevant data is available to you, such as when you are computing the variance around an average grade for all 20 students in a class. You would use the second if you did not have universal access to all the relevant data, and had to estimate the variance from a much smaller sample, such as estimating the height of all males within a large country.
The population standard deviation is often denoted as StDevP. The Swift 5.0 code I used is shown below. Note that this is not suitable for very large arrays due to loss of the "small value" bits as the summations get large. Especially when the variance is close to zero you might run into run-times errors. For such serious work you might have to introduce an algorithm called compensated summation
import Foundation
extension Array where Element: FloatingPoint
{
var sum: Element {
return self.reduce( 0, + )
}
var average: Element {
return self.sum / Element( count )
}
/**
(for a floating point array) returns a tuple containing the average and the "standard deviation for populations"
*/
var averageAndStandardDeviationP: ( average: Element, stDevP: Element ) {
let sumsTuple = sumAndSumSquared
let populationSize = Element( count )
let average = sumsTuple.sum / populationSize
let expectedXSquared = sumsTuple.sumSquared / populationSize
let variance = expectedXSquared - (average * average )
return ( average, sqrt( variance ) )
}
/**
(for a floating point array) returns a tuple containing the sum of all the values and the sum of all the values-squared
*/
private var sumAndSumSquared: ( sum: Element, sumSquared: Element ) {
return self.reduce( (Element(0), Element(0) ) )
{
( arg0, x) in
let (sumOfX, sumOfSquaredX) = arg0
return ( sumOfX + x, sumOfSquaredX + ( x * x ) )
}
}
}

How to swap two dates in swift

Trying to swap two dates in Swift. It currently gives me an error saying:
Cannot subscript a value of type '[Mission]' with an index of type 'Int'
func sort (mission: [Mission]) -> Bool {
for (var i = 0; i < mission.count; i++) {
println(mission[i].createdAt)
if mission[i].createdAt.timeIntervalSince1970 > mission[i+1].createdAt.timeIntervalSince1970 {
var temp = mission[i]
mission[i] = mission[i+1]
mission[i+1] = temp
}
}
println()
return true
}
This function is named sort, but it doesn't actually sort the array. If you're actually trying to sort the array, you should just use the builtin sort function:
missions.sort { $0.createdAt.timeIntervalSince1970 > $1.createdAt.timeIntervalSince1970 }
The function as you've written it, were it compilable, would always cause a fatalError because you always try to access an out-of-bounds index. i goes from 1 to count - 1 and then you try to do mission[i+1]. To fix this you should change the range of the for loop to stop at count - 2.
The error the compiler is giving you is actually caused by the fact that function parameters are immutable by default, so your assignments aren't actually possible. If you want your changes to be visible outside the function, you'll need to mark the argument inout.
Further, to do the swap you should use swift's builtin swap function instead of implementing it yourself. Putting all of that together:
func sort(inout mission: [Mission]) -> Bool {
for i in 0..<mission.count-1 {
println(mission[i].createdAt)
if mission[i].createdAt.timeIntervalSince1970 > mission[i+1].createdAt.timeIntervalSince1970 {
swap(&mission[i], &mission[i+1])
}
}
println()
return true
}

Resources