Summing an Array of Tuples - arrays

I have an an array of tuples defined like this:
var stringsWithLengthsArray:[(someString: String, someStringLength: Int)] = []
I've appended a number of tuples to this array. I would like to sum the someStringLength elements of each tuple in the array and think the best way to do this is to use the stringsWithLengthsArray.reduce method, but I can't figure out the syntax. What's the best way to sum the someStringLength elements?

I like this way best:
let total = stringsWithLengthsArray.reduce(0){$0 + $1.someStringLength}

This is another solution. Use reduce without map and access your tuple fields with the .0 / .1 accessors directly.
let total = stringsWithLengthsArray.reduce(0){$0 + $1.1}

You can use map to get only the someStringLength property value and use reduce to sum all the elements as follow:
let stringsWithLengthsArray:[(someString: String, someStringLength: Int)] = [("strA",2),("strB",3)]
let someStringLenghtTotal = stringsWithLengthsArray.map{$0.someStringLength}.reduce(0){$0+$1}
someStringLenghtTotal // 5

Related

Get the index of the last occurrence of each string in an array

I have an array that is storing a large number of various names in string format. There can be duplicates.
let myArray = ["Jim","Tristan","Robert","Lexi","Michael","Robert","Jim"]
In this case I do NOT know what values will be in the array after grabbing the data from a parse server. So the data imported will be different every time. Just a list of random names.
Assuming I don't know all the strings in the array I need to find the index of the last occurrence of each string in the array.
Example:
If this is my array....
let myArray = ["john","john","blake","robert","john","blake"]
I want the last index of each occurrence so...
blake = 5
john = 4
robert = 3
What is the best way to do this in Swift?
Normally I would just make a variable for each item possibility in the array and then increment through the array and count the items but in this case there are thousands of items in the array and they are of unknown values.
Create an array with elements and their indices:
zip(myArray, myArray.indices)
then reduce into a dictionary where keys are array elements and values are indices:
let result = zip(myArray, myArray.indices).reduce(into: [:]) { dict, tuple in
dict[tuple.0] = tuple.1
}
(myArray.enumerated() returns offsets, not indices, but it would have worked here too instead of zip since Array has an Int zero-based indices)
EDIT: Dictionary(_:uniquingKeysWith:) approach (#Jessy's answer) is a cleaner way to do it
New Dev's answer is the way to go. Except, the standard library already has a solution that does that, so use that instead.
Dictionary(
["john", "john", "blake", "robert", "john", "blake"]
.enumerated()
.map { ($0.element, $0.offset) }
) { $1 }
Or if you've already got a collection elsewhere…
Dictionary(zip(collection, collection.indices)) { $1 }
Just for fun, the one-liner, and likely the shortest, solution (brevity over clarity, or was it the other way around? :P)
myArray.enumerated().reduce(into: [:]) { $0[$1.0] = $1.1 }

how to get array value by using index value of another value?

let nameArray = ["ramesh","suresh","rajesh"]
let idArray = ["100","101","102"]
Now i want value of "idArray" by using index value of "nameArray".
if nameArray index is 0. Output is 100
In Object Oriented Programming, objects should own their properties. So instead of having two data structures describe the same object, either use structs like Mr. Vadian has suggested, or have one array store all the properties of the objects:
let zippedArray = Array(zip(nameArray, idArray))
And now to get the object in a given index, you can use the following:
let index = 0
let element = zippedArray[0]
print(element.0) //ramesh
print(element.1) //100

Array in Swift Xcode

I have an algorithm that intersects some array with Bool and give me back some other array. Now the problem is that the arrays I get has this form:
[[[[123.0,334.45]]],[[[342.35,2434.34]]],[[[...,...]]],....]
Now how you can see there are too Square brackets, is there any way to remove the parentheses too ?
thanking you.
Whew, now that's nesting!
I counted the brackets, and used the appropriate number of joined() methods to flatten the array:
let array = [[[[123.0,334.45]]],[[[342.35,2434.34]]]]
let flatArray = Array(array.joined().joined().joined())
...gives:
[123, 334.45, 342.35, 2434.34]

Swift - array of strings to multiple subarrays with constant number of strings

Let's say I have this array of strings:
let Vehicles = ["Aeroplane", "Bicycle", "CarVehicle", "Lorry", "Motorbike", "Scooter", "Ship", "Train"]
What I want is this result:
let resultArray = [["Aeroplane", "Bicycle", "CarVehicle", "Lorry"], ["Motorbike", "Scooter", "Ship", "Train"]]
I know I could do this by for but I want to use Higher Order functions in Swift. I mean functions like map, reduce, filter. I think it's possible to do this way and it could be better. Can anyone help me with this? Thanks
A possible solution with map() and stride():
let vehicles = ["Aeroplane", "Bicycle", "CarVehicle", "Lorry", "Motorbike", "Scooter", "Ship", "Train"]
let each = 4
let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
vehicles[$0 ..< advance($0, each, vehicles.count)]
}
println(resultArray)
// [[Aeroplane, Bicycle, CarVehicle, Lorry], [Motorbike, Scooter, Ship, Train]]
The usage of advance() in the closure guarantees that the code
works even if the number of array elements is not a multiple of 4
(and the last subarray in the result will then be shorter.)
You can simplify it to
let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
vehicles[$0 ..< $0 + each]
}
if you know that the number of array elements is a multiple of 4.
Strictly speaking the elements of resultArray are not arrays
but array slices. In many cases that does not matter, otherwise you
can replace it by
let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
Array(vehicles[$0 ..< advance($0, each, vehicles.count)])
}

Taking a column or row of a 2D Array in F#

How can I get hold of a column or row of a 2D Array in F# (ideally as a 1D array, but a Seq would be nice as well). Obviously I could write it myself, but you would think it must be already provided...
E.g. I am after built-in equivalent for:
let row i array = seq { for j in 0 .. (Array2D.length2 array)-1 do yield array.[i,j]}
I don't think there is a built-in function for this.
You could slice the array and flatten the slice using Seq.cast:
let row i (arr: 'T[,]) = arr.[i..i, *] |> Seq.cast<'T>

Resources