Swift Get x number of elements from an array - arrays

I would appreciates some help from someone who knows what they are doing as opposed to me with Arrays in Swift for Xcode.
I have an array of over 40+ heart rate readinsg that I get from an Apple Watch and want to make a new array of only exactly 40 to show on a graph, but they have to be in order, I don't want them to be out of order, so I can't use random or shuffle and get the first 40 or the last 40 of the doubles.
e.g. heartratereadings = [56.0, 57.0, 58.0 ... 101.0]
var fortyReadings = ??heartratereading.somthing to get 40 values in the order they were in?
What is a way I can do that? Thanks in advance ~ Kurt
Thanks you for the solution below I was able to great a cute graph on the watch that shows heart rate readings over time by using 40 instances of a line that is 200px hight. Then I use the individual heart rate to set the heights of each of the 40 bars. Looks great, obviously nt meant for any scientific or medical purpose, just gives me a rough idea of how the heart rate changes over given time. Apples simulator only gives heart rate readings from 58-62 so I can't wait to test. Thank you!!

This is similar to what #staticVoidMan suggested. Instead of recursion, the indices of the new (smaller) array are mapped to indices of the old (larger) array via linear interpolation:
extension Array {
/// Return a smaller array by picking “evenly distributed” elements.
///
/// - Parameter length: The desired array length
/// - Returns: An array with `length` elements from `self`
func pick(length: Int) -> [Element] {
precondition(length >= 0, "length must not be negative")
if length >= count { return self }
let oldMax = Double(count - 1)
let newMax = Double(length - 1)
return (0..<length).map { self[Int((Double($0) * oldMax / newMax).rounded())] }
}
}
Examples:
let doubleArray = [56.0, 57.0, 58.0, 98.0, 101.0, 88.0, 76.0]
print(doubleArray.pick(length: 5))
// [56.0, 58.0, 98.0, 88.0, 76.0]
let intArray = Array(1...10)
print(intArray.pick(length: 8))
// [1, 2, 4, 5, 6, 7, 9, 10]

For starters, this basic extension on Array adds the functionality to return alternate elements from any type of array:
extension Array {
func evenlySpaced(length: Int) -> [Element] {
guard length < self.count else { return self }
let takeIndex = (self.count / length) - 1
let nextArray = Array(self.dropFirst(takeIndex + 1))
return [self[takeIndex]] + nextArray.evenlySpaced(length: length - 1)
}
}
Example 1:
let doubleArray = [56.0, 57.0, 58.0, 98.0, 101.0, 88.0, 76.0]
print(doubleArray.evenlySpaced(length: 5))
[56.0, 57.0, 58.0, 98.0, 101.0, 88.0, 76.0]
evenly spaced would give:
[56.0, 57.0, 58.0, 101.0, 76.0]
Example 2:
let intArray = (1...1000).map { $0 }
print(intArray.evenlySpaced(length: 40))
This shows that if you had an array of 1000 elements, the chosen interval values would be:
[25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 525, 550, 575, 600, 625, 650, 675, 700, 725, 750, 775, 800, 825, 850, 875, 900, 925, 950, 975, 1000]
It's a simple implementation and you could loosely say it's evenly spaced because it tends to favour the initial elements in data sets that are small when compared to the requested length.
Example 3:
let array = (1...10).map { $0 }
print(array.evenlySpaced(length: 8))
[1, 2, 3, 4, 5, 6, 8, 10]
You could instead implement a more balanced logic but the general idea would be the same.

Here is the simplest way to do so:
var heartRateReading = [56.0, 57.0, 58.0, 98.0, ..., 101.0]
//If you want 40 items from the 10th position
var fortySelected = heartRateReading.suffix(from: 10).suffix(40)
// If you want to iterate each second and get 40 values out of it
_ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (_) in
let values = heartRateReading.suffix(40)
print(values)
}

To get X number of elements from Y index we can have generic function like below:
func fetchElements<T>(sourceArray: [T],
startIndex: Int,
recordCount: Int) -> [T] {
guard startIndex >= 0 && recordCount >= 0 else { return [] }
guard startIndex < sourceArray.count else { return [] }
let arrTrimmedFromStartIndex = Array(sourceArray.suffix(from: startIndex))
let arrWithRequiredCount = Array(arrTrimmedFromStartIndex.prefix(recordCount))
return arrWithRequiredCount
}
Now we can use it with any type as below:
class MyModel {
let name: String
init(name: String) {
self.name = name
}
}
Call to actual function:
let arr = (0..<10).map({ MyModel(name: "\($0)") })
let result = fetchElements(sourceArray: arr,
startIndex: 4,
recordCount: 3)
print(arr.map({$0.name}))
print(result.map({$0.name}))
Print result:
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
["4", "5", "6"]
Hope this helps!

Just use a for loop
Var forty = [double]()
For n in 1...40 {
forty.insert(heartRate[n], at: 0)
}

Related

How to split an Odd array

If I have an array [-23,0,43,7,5,2,4], how to do I split the array [odd][even].
I want 4 elements in the first array and 3 elements in the second array.
I tried to do something like this:
let leftArray = Array(mainArray[0..<mainArray.count/2])
let rightArray = Array(mainArray[mainArray.count/2..<mainArray.count])
I keep on getting [-23,0,43] and [7,5,2,4].
I'd create an extension implementing properties that yield the left and right halves of the array. In this implementation left includes the larger half of the array if the array has an odd number of elements.
extension Array {
var left: ArraySlice<Element> {
prefix(count / 2 + count % 2)
}
var right: ArraySlice<Element> {
suffix(count / 2)
}
}
And its usage would be:
let main = [-23, 0, 43, 7, 5, 2, 4]
let left = main.left
let right = main.right
The result of the above is an ArraySlice for efficiency, but if you want an Array you can just use map.
let main = [-23, 0, 43, 7, 5, 2, 4]
let left = main.left.map { $0 }
let right = main.right.map { $0 }
I think you want to split your array in the middle, and for odd counts, have the first part be the larger one. Use a function like this (intentionally spelled our very explicitly):
func splitArray(_ arr: [Int]) -> ([Int], [Int]) {
let count = arr.count
let half = count.isMultiple(of: 2) ? count / 2 : count / 2 + 1
let left = arr[0..<half]
let right = arr[half..<count]
return (Array(left), Array(right))
}
splitArray([-23,0,43,7,5,2,4]) // ([-23, 0, 43, 7], [5, 2, 4])
splitArray([-23,0,43,7,5,2,4,1]) // ([-23, 0, 43, 7], [5, 2, 4, 1])
This can be simplified and be made generic (i.e., work on all kinds of Collections) like so:
extension Collection {
func splitHalf() -> (SubSequence, SubSequence) {
let count = self.count
let left = self.prefix(count / 2 + count % 2)
let right = self.suffix(count / 2)
return (left, right)
}
}
[-23,0,43,7,5,2,4].splitHalf() // ([-23, 0, 43, 7], [5, 2, 4])
[-23,0,43,7,5,2,4,1].splitHalf() // ([-23, 0, 43, 7], [5, 2, 4, 1])
"12345".splitHalf() // (.0 "123", .1 "45")
"123456".splitHalf() // (.0 "123", .1 "456")
Function for split the array
func getSplitArr(arr:[Int])->Void{
let count = arr.count
let secArrCount = abs(count/2)
var firstArray = [Int]()
for i in 0..<secArrCount{
let value = arr[i]
firstArray.append(value)
}
var secondArray = [Int]()
for i in secArrCount..<count{
let value = arr[i]
secondArray.append(value)
}
print("\(firstArray)")
print("\(secondArray)")
}
Use of Functions
self.getSplitArr(arr: [-23,0,43,7,5,2,4])
Your first question wasn't clear. This should return two arrays one where the first array is even and the second is odd every time.
var array = [-23,0,43,7,5,2,4]
func splitArray(in array : [Int]) -> (firstArray :[Int], secondArray: [Int]) {
let firstArray = array.dropLast(array.count / 2).compactMap { item -> Int in
item
}
let secondArray = array.dropFirst((array.count / 2) + 1).compactMap { item -> Int in
item
}
return (firstArray,secondArray)
}
var newArray = splitArray(in: array)
print(newArray)

Reverse array by group size

I was trying to solve this challenge: reverse an array of elements by groups given a group size.
Given Array: [1, 2, 3, 4, 5, 6]
Desired Result (group size of 3): [4, 5, 6, 1, 2, 3]
If last group has less elements than the group size, then just add them and finish, as follows:
Given Array: [1, 2, 3, 4, 5, 6, 7]
Desired Result: [5, 6, 7, 2, 3, 4, 1]
I tried this and it is working, but it looks kinda weird for me. Can anyone help me find a cleaner or much more intuitive solution?
extension Array {
func reverse(groupSize: Int) -> [Element] {
var reversed = [Element]()
let groups = count / groupSize
for group in 0...groups {
let lowerBound = count - group * groupSize - groupSize
let upperBound = count - 1 - group * groupSize
if lowerBound >= 0 {
reversed += Array(self[lowerBound...upperBound])
} else {
reversed += Array(self[0...upperBound])
}
}
return reversed
}
}
The following solution is based on a combo of stride+map:
let groupSize = 3
let array = [1, 2, 3, 4, 5, 6]
let reversedArray = Array(array.reversed())
let result = stride(from: 0, to: reversedArray.count, by: groupSize).map {
reversedArray[$0 ..< min($0 + groupSize, reversedArray.count)].reversed()
}.reduce([Int](), +)
print(result) // [4, 5, 6, 1, 2, 3]
You could say:
extension Array {
func groupedReversing(stride: Int) -> [Element] {
precondition(stride > 0, "stride must be > 0")
return Swift.stride(from: count, to: 0, by: -stride)
.flatMap { self[Swift.max(0, $0 - stride) ..< $0] }
}
}
let result = Array(1 ... 7).groupedReversing(stride: 3)
print(result) // [5, 6, 7, 2, 3, 4, 1]
We're using stride(from:through:by:) to iterate from array.count (inclusive) to 0 (exclusive) in increments of (minus) the stride. The Swift. prefix is in order to disambiguate it from the obsoleted Swift 2 stride method (which will be gone in Swift 4.1).
Then, we're flat-mapping the index to a slice of the input array that's up to stride elements long (truncating at the beginning of the array as we clamp the lower index to 0). And because this is flatMap, the resulting slices are concatenated into a single resulting array.
You could also implement a fully generic version across Sequence by first providing an implementation on BidirectionalCollection, advancing indices backwards and appending slices into a resulting array:
extension BidirectionalCollection {
func groupedReversing(stride: Int) -> [Element] {
precondition(stride > 0, "stride must be > 0")
var result: [Element] = []
result.reserveCapacity(numericCast(count))
var upper = endIndex
while upper != startIndex {
// get the next lower bound for the slice, stopping at the start index.
let lower = index(upper, offsetBy: -numericCast(stride),
limitedBy: startIndex) ?? startIndex
result += self[lower ..< upper]
upper = lower
}
return result
}
}
and then implement an overload on Sequence that first converts to an array, and then forwards onto the above implementation:
extension Sequence {
func groupedReversing(stride: Int) -> [Element] {
return Array(self).groupedReversing(stride: stride)
}
}
Now you can call it on, for example, a CountableClosedRange without first having to convert it to an array:
let result = (1 ... 7).groupedReversing(stride: 3)
print(result) // [5, 6, 7, 2, 3, 4, 1]
I think your function is okay, not sure what you meant by weird tbh, can separate to chunk or add each elements in reversed way ,but logic is same anyway, just need to mind the performance/complexity of each ways:
let a = [1,2,3,4,5,6,7,8,9,10,11]
extension Array {
func reverse(group: Int) -> [Element] {
guard group > 1 else { return self.reversed() }
var new = [Element]()
for i in stride(from: self.count-1, through: 0, by: -group) {
let k = i-group+1 < 0 ? 0 : i-group+1
for j in k...i {
new.append(self[j])
}
}
return new
}
}
a.reverse(group: 4) //[8, 9, 10, 11, 4, 5, 6, 7, 1, 2, 3]
The two following Swift 5 code snippets show how to implement a Collection or Array extension method in order to chunked it, reverse it then flatten it into a new array.
#1. Using AnyIterator and Sequence joined()
extension Collection {
func reverseFlattenChunked(by distance: Int) -> [Element] {
precondition(distance > 0, "distance must be greater than 0")
var index = endIndex
let iterator = AnyIterator({ () -> SubSequence? in
let newIndex = self.index(index, offsetBy: -distance, limitedBy: self.startIndex) ?? self.startIndex
defer { index = newIndex }
return index != self.startIndex ? self[newIndex ..< index] : nil
})
return Array(iterator.joined())
}
}
Usage:
let array = ["1", "2", "3", "4", "5", "6", "7"]
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: ["5", "6", "7", "2", "3", "4", "1"]
let array: [String] = ["1", "2", "3", "4", "5", "6"]
let newArray = array.reverseFlattenChunked(by: 2)
print(newArray) // prints: ["5", "6", "3", "4", "1", "2"]
let array: [String] = []
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: []
#2. Using stride(from:to:by:) and Sequence flatMap(_:)
extension Array {
func reverseFlattenChunked(by distance: Int) -> [Element] {
precondition(distance > 0, "distance must be greater than 0")
let indicesSequence = stride(from: self.endIndex, to: self.startIndex, by: -distance)
let array = indicesSequence.flatMap({ (index) -> SubSequence in
let advancedIndex = self.index(index, offsetBy: -distance, limitedBy: self.startIndex) ?? self.startIndex
// let advancedIndex = index.advanced(by: -distance) <= self.startIndex ? self.startIndex : index.advanced(by: -distance) // also works
return self[advancedIndex ..< index]
})
return array
}
}
Usage:
let array = ["1", "2", "3", "4", "5", "6", "7"]
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: ["5", "6", "7", "2", "3", "4", "1"]
let array: [String] = ["1", "2", "3", "4", "5", "6"]
let newArray = array.reverseFlattenChunked(by: 2)
print(newArray) // prints: ["5", "6", "3", "4", "1", "2"]
let array: [String] = []
let newArray = array.reverseFlattenChunked(by: 3)
print(newArray) // prints: []

How can I sort one array based on another array positions in swift?

In Swift, say I have two arrays:
var array1: [Int] = [100, 40, 10, 50, 30, 20, 90, 70]
var array2: [Int] = [50, 20, 100, 10, 30]
I want to sort my aary1 as per array2
So final output of my array1 will be: // array1 = [50, 20, 100, 10, 30,
40, 90, 70]
Even though your question is quite vaguely worded, judging from your example, what you actually want is the union of the two arrays, with the elements of the smaller array coming in first and after them the unique elements of the bigger array in an unchanged order at the end of this array.
The following code achieves the result of the example:
let combined = array2 + array1.filter{array2.index(of: $0) == nil}
You have not defined how you want the elements in array1 but not in array2 to be sorted. This solution assumes you want to sort those not-found elements by their numeric value:
var array1 = [100, 40, 10, 50, 30, 20, 90, 70]
var array2 = [50, 20, 100, 10, 30]
array1.sort {
let index0 = array2.index(of: $0)
let index1 = array2.index(of: $1)
switch (index0, index1) {
case (nil, nil):
return $0 < $1
case (nil, _):
return false
case (_, nil):
return true
default:
return index0! < index1!
}
}
print(array1) // [50, 20, 100, 10, 30, 40, 70, 90]
// ^ order not defined in array2

splitting an array into subarrays by variables value

I have an array of ages.
I want to split the array in to 4 subarrays by the age value.
A -> 0...25
B -> 26...50
c -> 51...75
d -> 76 +
I have no problem iterating through the array and append to different arrays by the age value.
let subArrays: [[Int]] = [[], [], [], []]
for age in ages {
switch age {
case 0...25:
subArrays[0].append(age)
case 26...50:
subArrays[1].append(age)
case 51...75:
subArrays[2].append(age)
default:
subArrays[3].append(age)
}
}
My questions is:
Is there a cleaner way to do this using map, split or any other function.
Thanks
This doesn't use map or anything fancy but you can easily eliminate the switch:
var subArrays: [[Int]] = [[], [], [], []]
for age in ages {
subArrays[min((age - 1) / 25, 3)].append(age)
}
The use of min ensures all values of 76 and greater go into the last slot.
And to test, with all boundary cases, try:
let ages = [ 50, 67, 75, 76, 25, 12, 26, 51, 99, 45, 0, 120, 16 ]
And then:
print(subArrays)
Gives:
[[25, 12, 0, 16], [50, 26, 45], [67, 75, 51], [76, 99, 120]]
A more generic version that does not depend on any mathematical property of your ranges:
func split<T>(array: [T], ranges: [CountableClosedRange<T>]) -> [[T]] {
var result = Array(repeating: [T](), count: ranges.count)
for element in array {
if let subIndex = ranges.index(where: { $0 ~= element }) {
result[subIndex].append(element)
}
}
return result
}
let ages = [10, 20, 30, 40, 50, 60]
let subarrays = split(array: ages, ranges: [0...25, 26...50, 51...75, 76...Int.max])
Note that it does not check for overlapping ranges.
Based on rmaddy's answer (practically the same) but within one line:
let subs = (0...3).map { sub in ages.filter { sub == min(($0 - 1) / 25, 3) } }

Convert String Array into Int Array Swift 2?

[Xcode 7.1, iOS 9.1]
I have an array: var array: [String] = ["11", "43", "26", "11", "45", "40"]
I want to convert that (each index) into an Int so I can use it to countdown from a timer, respective of the index.
How can I convert a String array into an Int Array in Swift 2?
I've tried several links, none have worked and all of them have given me an error. Most of the code from the links is depreciated or hasn't been updated to swift 2, such as the toInt() method.
Use the map function
let array = ["11", "43", "26", "11", "45", "40"]
let intArray = array.map { Int($0)!} // [11, 43, 26, 11, 45, 40]
Within a class like UIViewController use
let array = ["11", "43", "26", "11", "45", "40"]
var intArray = Array<Int>!
override func viewDidLoad() {
super.viewDidLoad()
intArray = array.map { Int($0)!} // [11, 43, 26, 11, 45, 40]
}
If the array contains different types you can use flatMap (Swift 2) or compactMap (Swift 4.1+) to consider only the items which can be converted to Int
let array = ["11", "43", "26", "Foo", "11", "45", "40"]
let intArray = array.compactMap { Int($0) } // [11, 43, 26, 11, 45, 40]
Swift 4, 5:
Use compactMap with cast to Int, solution without '!'.
let array = ["1","foo","0","bar","100"]
let arrayInt = array.compactMap { Int($0) }
print(arrayInt)
// [1, 0, 100]
Swift 4, 5:
The instant way if you want to convert string numbers into arrays of type int (in a particular case i've ever experienced):
let pinString = "123456"
let pin = pinString.map { Int(String($0))! }
And for your question is:
let pinArrayString = ["1","2","3","4","5","6"]
let pinArrayInt = pinArrayString.map { Int($0)! }
i suggest a little bit different approach
let stringarr = ["1","foo","0","bar","100"]
let res = stringarr.map{ Int($0) }.enumerate().flatMap { (i,j) -> (Int,String,Int)? in
guard let value = j else {
return nil
}
return (i, stringarr[i],value)
}
// now i have an access to (index in orig [String], String, Int) without any optionals and / or default values
print(res)
// [(0, "1", 1), (2, "0", 0), (4, "100", 100)]
A slightly different example
let digitNames = [0: "Zero", 1: "One", 2:"Two", 3: "Three",
4:"Four",5:"Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10:"Ten"
]
let numbers = [16,58,510]
let strings = numbers.map { (number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return (output)
}
print(strings)
// strings is inferred to be of type [String]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]

Resources