Multiply and add elements in 2 arrays - ios

I have 2 arrays say arrayA & arrayB. arrayA has the elements say [1,2] and arrayB has the elements say [3,4]. Now I want to multiply and add the elements in these arrays like so.. 1x3 + 2x4 = 11. How can I achieve this...?

Here a combo of zip, map and reduce:
let result = (zip([1,2], [3,4]).map { $0.0 * $0.1 }).reduce(0, +)
print(result) // 11
Zip makes a sequence of pairs based on the two arrays: (1,3), (2,4)
with map I am iterating for each element of the array producing at each iteration a new element
$0 means the element of the sequence at the current iteration. Since the element is a pair (because of zip), we can access to the first sub-element of the pair with $0.0 and to the second with $0.1.
finally (after map) we get an array of products, just need to "reduce" it to a number, summing all the resulting elements with reduce.
(0, +) means that reduce starts from 0 as initial value, then with the abbreviation + we can accumulate the sums of all the elements.

Note that rather than using a chained map and reduce (for multiplication and summation, respectively), you could directly apply the reduce operation on the zipped sequence, and modify the reduce closure to accordingly calculate the sum of the pair-wise multiplied objects in the zipped sequence:
let a = [1, 2]
let b = [3, 4]
let result = zip(a,b).reduce(0) { $0 + $1.0 * $1.1 } // 11

Try this.
let A = [1,2]
let B = [3,4]
let C = zip(A, B).map {$0.0 * $0.1}
print(C) // [3, 8]
let sum = C.reduce(0, +)
print(sum)//11

Related

My coremlmodel gives different output on swift

I create my MLMultiArray like this
var mlInput = try? MLMultiArray(shape: [1,2,12,120], dataType: MLMultiArrayDataType.float32)
and fill this with values which I get from json file like below
mlInput![0 * 12 * 120 + 0 * 120 + 5] = value as! NSNumber
basically I take index 0 over 2 index 0 over 12 and index 5 over 120
and giving it to model like below
let obj = try! mlModel.prediction(input: ml3dmodelInput(input: mlInput))
and get the result with these steps you see. It gives wrong prediction output. I did same things in python to test coremlmodel it did work well with python. I just did same steps fill the array with values from json giving it to model and get the output. What did I do wrong?
You should use the array's strides to calculate the indices.
If the array has shape [A, B, C, D] then the correct index is:
a * strides[0] + b * strides[1] + c * strides[2] + d * strides[3]
However, you can also simply do:
mlInput[[a, b, c, d] as [NSNumber]] = value
Solved the problem by using cpu only.
let options = MLPredictionOptions()
options.usesCPUOnly = true
let obj = try! mlModel.prediction(input: ml3dmodelInput(input: mlInput), options: options)
Changed third step like this.

Generate all numbers for 0 to 1 using a loop

This question might seem a bit silly..:) But I think I'm missing something somewhere..so bit confused...
I wanted to generate all numbers from 0 to 1. In other words, if I do 1/2, I get 0.5. Then 0.5/2 = 0.25. Then 0.25/2 = 0.125. This will go on until 0.00000001 (A total of 26 divisions)
But I want to generate all numbers in an increasing order from 0.00000001 to 1.
I tried doing something like so...
let first = 0.00000001
let last = 1.0
let interval = first * 2
let sequence = stride(from: first, to: last, by: interval)
for element in sequence {
print(element)
}
But it's not working. It seemed it just prints infinitely...
How can I properly use a for loop and print from 0.00000001 to 1 in a limited number of iterations..? Or any other loops to be used in this case..?
You can't use stride. stride produces an arithmetic sequence with a difference of interval, which is 0.00000002:
0.00000001
0.00000003
0.00000005
0.00000007
...
You want a geometric sequence between 0 and 1.
You could use sequence instead, which generates an infinite sequence:
let first = 0.00000001
let last = 1.0
for item in sequence(first: first, next: { $0 * 2 }).prefix(while: { $0 < last }) {
print(item)
}
{ $0 * 2 } is the function that generates the next element, and prefix(while:) is used to get first elements that satisfy the < last condition.
Here is another way you could approach it. Use stride to count down the powers of 2 from 26 to 0 and divide 1.0 by that power of 2 and display only the first 8 decimal places:
for n in stride(from: 26, through: 0, by: -1) {
print(String(format: "%.8f", 1.0 / pow(2.0, Double(n))))
}
or equivalently (removing the 1/n by using negative exponents):
for n in -26...0 {
print(String(format: "%.8f", pow(2.0, Double(n))))
}
Output:
0.00000001
0.00000003
0.00000006
0.00000012
0.00000024
0.00000048
0.00000095
0.00000191
0.00000381
0.00000763
0.00001526
0.00003052
0.00006104
0.00012207
0.00024414
0.00048828
0.00097656
0.00195312
0.00390625
0.00781250
0.01562500
0.03125000
0.06250000
0.12500000
0.25000000
0.50000000
1.00000000

F# jagged array assignment

I am getting strange behavior - when I assign a single value to a jagged array, it changes values of the entire column.
let testArray = Array.create 5 (Array.create 5 nan)
testArray.[3].[3] <- 1.0
The code above, instead of changing the value of a single cell, changes the value of the entire column.
val it : float [] [] =
[|[|nan; nan; nan; 1.0; nan|]; [|nan; nan; nan; 1.0; nan|];
[|nan; nan; nan; 1.0; nan|]; [|nan; nan; nan; 1.0; nan|];
[|nan; nan; nan; 1.0; nan|]|]
This happens because you're not creating a 2-dimensional array (as I assume you expect), but rather you're creating exactly two arrays: one array with 5 nans in it, and another array with 5 references to the first array in it. Just to illustrate the matter, the following code is completely equivalent to yours:
let firstArray = Array.create 5 nan
let testArray = Array.create 5 firstArray
testArray.[3].[3] <- 1.0
So that the line testArray.[3].[3] <- 1.0 actually changes only one element - the fourth one in firstArray, but if you then try to print out testArray, that same element shows up multiple times, because there are multiple references to firstArray.
If you wanted to create an array with five different arrays in it, you need to use Array.init, which instead of the element takes a "create next element" function:
let testArray = Array.init 5 (fun _ -> Array.create 5 nan)
Alternatively, you can use list comprehension to create the array:
let testArray = [|for i in 1..5 -> Array.create 5 nan|]
Both will give you the same result, though the first one will have slightly better performance.
If you really need to work with two-dimensional arrays (rather than arrays of arrays), you might want to look at Array2D instead:
let testArray = Array2D.create 5 5 nan
testArray.[3,3] <- 1.0

Swift Range Operator with two unknown values

If I have two unknown values, lets say x and y, what is the best way loop through all of the values between between those values?
For example, given the values x = 0 and y = 5 I would like to do something with the values 0, 1, 2, 3, 4, and 5. The result could exclude 0 and 5 if this is simpler.
Using Swift's Range operator, I could do something like this:
for i in x...y {
// Do something with i
}
Except I do not know if x or y is the greater value.
The Swift documentation for Range Operators states:
The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
There are a number of solutions here. A pretty straight forward one is:
let diff = y - x
for i in 0...abs(diff) {
let value = min(x, y) + i
// Do something with value
}
Is there a better, or more elegant way to achieve this?
I guess the most explicit way of writing it would be:
for i in min(a, b)...max(a, b) {
// Do something with i
}
To exclude the first and last value, you can increment your lower limit and use the Swift ..< syntax:
let lowerLimit = min(a, b) + 1
let upperLimit = max(a, b)
for i in lowerLimit..<upperLimit {
// Do something with i
}

Codility: Passing cars in Lua

I'm currently practicing programming problems and out of interest, I'm trying a few Codility exercises in Lua. I've been stuck on the Passing Cars problem for a while.
Problem:
A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.
Array A contains only 0s and/or 1s:
0 represents a car traveling east,
1 represents a car traveling west.
The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.
For example, consider array A such that:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
Write a function:
function solution(A)
that, given a non-empty zero-indexed array A of N integers, returns the number of pairs of passing cars.
The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.
For example, given:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
the function should return 5, as explained above.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
My attempt in Lua keeps failing but I can't seem to find the issue.
local function solution(A)
local zeroes = 0
local pairs = 0
for i = 1, #A do
if A[i] == 0 then
zeroes = zeroes + 1
else
pairs = pairs + zeroes
if pairs > 1e9 then
return -1
end
end
end
return pairs
end
In terms of time-space complexity constraints, I think it should pass so I can't seem to find the issue. What am I doing wrong? Any advice or tips to make my code more efficient would be appreciated.
FYI: I keep getting a result of 2 when the desired example result is 5.
The problem statement says A is 0-based so if we ignore the first and start at 1, the output would be 2 instead of 5. 0-based tables should be avoided in Lua, they go against convention and will lead to a lot of off-by one errors: for i=1,#A do will not do what you want.
function solution1based(A)
local zeroes = 0
local pairs = 0
for i = 1, #A do
if A[i] == 0 then
zeroes = zeroes + 1
else
pairs = pairs + zeroes
if pairs > 1e9 then
return -1
end
end
end
return pairs
end
print(solution1based{0, 1, 0, 1, 1}) -- prints 5 as you wanted
function solution0based(A)
local zeroes = 0
local pairs = 0
for i = 0, #A do
if A[i] == 0 then
zeroes = zeroes + 1
else
pairs = pairs + zeroes
if pairs > 1e9 then
return -1
end
end
end
return pairs
end
print(solution0based{[0]=0, [1]=1, [2]=0, [3]=1, [4]=1}) -- prints 5

Resources