Samstag, 28. Februar 2015

Interval mapping / playing with intervals and functions in Swift

Diverse approaches of mapping intervals to something. And learning a bit of Swift on the way.

For example, given a mapping of interval 0..<2 to a string "first interval" and 2..<4 to a string "second interval", we want to get the string for the value 3.4.

I started thinking about this because in my work I had to map rating intervals to certain background colors. If e.g. a user gives a 5.9 rating this would be in the range 4.5 - 6.0 which has to be displayed with a dark green background, etc. Sadly I had to do this using objc. I wondered how I would do it with Swift.

This is O(n), since we will examine the whole array each time. Not so good. Coming back later to this. Also note we assume that the ranges don't overlap.

What if we want to generate the ranges dynamically, say, divide 1...7 in 16 equal parts?
Since in this case the intervals are continuos, we can represent them just as a succession of numbers.
We can use strides for this:

Now let's try out an alternative approach to =~. Since in this case we know the ranges are sorted in increasing order, we can use this information to find the value.

The number we will search from now on:

let search:Float = 4.12

This is a simple filtering function with which we retrieve the ranges witch a start value smaller than our searched value:

let filtered = tuples.filter {
return $0.0 < search
}

The range we are looking for is the range with the biggest starting value from result of above filtering. Since we know the ranges are sorted increasingly, we can just pick the last one from the filter results:

In this case we expect the ranges to be sorted, since we assumed this for the filtering. In an imaginary case that we didn't know that the values are sorted, we could get the range with the max. starting value using reduce:

So far functions. But in order to avoid having to go through the whole array each time, we will use a loop, that exits when we find the range.
Since there's no filtering step, we have to add logic to look ahead in the next range. If there's no next, or if its starting value is bigger than searched value, we know we are in the searched range.

So is there a way in which we use a functional construct with the performance of for loop?
We need something similar to a find function. This is an example of a find function:
(this is btw a nice to have in array extension)

In our current case we need that the predicate, besides of the current element, considers also the next one (note nextElement is optional - when we are examining the last element, there's no next element), so we create a customized version of find: