How do I combine numbers in array in Swift? - arrays

I am not trying to add the arrays like all the other questions. This is what I want to do:
var a = [1,2,3]
var b = [4,5,6]
var outPut = [14,25,36]
As you can see I want to combine the indexes. How would I do that?

You can zip the two collections, and map the tuple elements multiplying the first element by 10 and adding the second. Of course this assumes your collection of integers are limited to a single digit:
let outPut = zip(a,b).map{ $0 * 10 + $1 } // [14,25,36]
If your collection elements are not limited to a single digit you can multiply the first element by 10 powered by the number of digits of the second collection (this considers that all integers are not negative:
var a = [12,25,37]
var b = [34,567,6443]
let outPut = zip(a,b).map{ $0 * Int(pow(Double(10),Double(String($1).count))) + $1 } // [1234, 25567, 376443]

Related

Math with typescript array - Angular

I'm really confused about how to approach this:
I have an array like this:
arr=["X12","Z1","Y7","Z22","X4","X8"]
I wish to perform mathematical functions on the elements such that:
Each element starting with "X" will have a fixed value 5, hence if there are 3 elements starting with "X" inside the array arr, it should go as : (fixed value of X) multiplied by (No. of "X" element occurrences inside array) = 5x3 = 15.
I tried something like this to calculate the no. of occurrences of "X" element but it doesn't work.
var xcounter = 0;
calculate(){
this.arr.forEach(element => {
if(this.arr.includes("X"))
{
this.xcounter++; //this doesn't give me no. of X element occurrences though.
}
});
}
What would be a clutter-free way to do this?
You could try to use array filter() with string startsWith() method.
var arr = ["X12","Z1","Y7","Z22","X4","X8"];
var valueX = 5;
var occurencesX = arr.filter(item => item.startsWith('X')).length;
console.log(occurencesX * valueX);
You can also try this
loop in to your array
Find how many time you found values which has X in starts
var arr=["X12","Z1","Y7","Z22","X4","X8"]
let total = 0
arr.forEach(
(row) =>{
total = row.startsWith('X')? total + 1 : total
}
)
console.log(total * 5)

Determine Size of Multidimensional Array in Swift

I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.
I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.
var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)
2
The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.
In Matlab this is a simple task with the following line of code,
a = [1,2,3;3,4,5]
size(a)
ans =
2 3
Is there a simple equivalent in Swift
I have looked high and low for a solution and cant seem to find exactly what i am after.
Thanks
- HB
Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.
let arr = [
[1,2,3,4,5],
[1,2,3],
[2,3,4,5],
]
So the concept of "rows" and "columns" does not exist. There's only count.
If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:
arr.flatMap { $0 }.count
If you are sure that your array is a matrix, you can do this:
let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
You must ask the size of a specific row of your array to get column sizes :
print("\(a.count) \(a[0].count)")
If you are trying to find the length of 2D array which in this case the number of rows (or # of subarrays Ex.[1,2,3]) you may use this trick: # of total elements that can be found using:
a.flatMap { $0 }.count //a is the array name
over # of elements in one row using:
a[0].count //so elemints has to be equal in each subarray
so your code to get the length of 2D array with equal number of element in each subarray and store it in constant arrayLength is:
let arrayLength = (((a.flatMap { $0 }.count ) / (a[0].count))) //a is the array name

How to obtain three arrays containing three objects or less?

I want to obtain three arrays containing three objects or less. I have a class named Product and an array who have 9 products or less downloaded form Firebase, so I want to generate three arrays, each one will have three different products in order. This is what I have:
var products = [Product]()
products = [product1, product2, product3, product4, product5, product6, product7, product8, product9]
And this is what I want to obtain:
array1 = [product1, product2, product3]
array2 = [product4, product5, product6]
array3 = [product7, product8, product9]
In some cases the array named product will have a number of products less than 9 so I have to create those arrays automatically with 3 or less products.
I'm doing this because my code have to generate an array that has three arrays inside, each one with three products or less to show in a collection view inside a tableview [[Product]].
You can slice an array by using the [] operator with a range. Note that this returns a view into the original array, so if you want a copy you pass the slice to Array() to create a new copy:
let numbers:[Int] = stride(from: 1, to: 10, by: 1).map{$0}
print(numbers.count)
let first = Array(numbers[0...2])
let second = Array(numbers[3...5])
let third = Array(numbers[6...8])
print(first, second, third)
To convert an array of arbitrary length into a number of arrays with 3 elements or less:
let numbers:[Int] = stride(from: 1, to: 14, by: 1).map{$0}
var bins: [[Int]] = []
for index in stride(from: 0, to: numbers.count, by: 3) {
let endIndex = min(index + 2, numbers.count - 1)
bins.append(Array(numbers[index...endIndex]))
}
print(bins)
Gustavo expects the extra variables to contain empty arrays when there are fewer than 6 or 3 products.
this should do it:
let productsBy3 = (0..<3).map{ i in products.indices.filter{$0/3==i}.map{products[$0]}}

Choose elements from array randomly in matlab and store the remain element

I have array contain 1 column with 225 rows and I want to select 170 elements from these elements randomly and store it in another array also store the remain elements at another array, I used this code to choose randomly elements but I don't know how I can store the remain elements (55) at another array !
Code : my original array A
msize = numel(A);
firstpart = A(randperm(msize, 170))
secondpart = !!!!! ( remain elements ) % This is my question
Instead of throwing away the other elements, just get a permutation of all of them and then partition the array:
msize = numel(A);
allperm = A(randperm(msize));
firstpart = allperm(1:170);
secondpart = allperm(171:end);
You can use boolean indexing.
A = rand(255,1); % just generating an example matrix
indices = false(size(A));
indices(randsample(1:numel(A),170)) = true; % select what to keep
firstpart = A(indices);
secondpart = A(~indices);

swift getting an array from something like array[0..<10]

I want to get a range of objects from an array. Something like this:
var array = [1,3,9,6,3,4,7,4,9]
var newArray = array[1...3] //[3,9,6]
The above would access elements from index 1 to 3.
Also this:
newArray = array[1,5,3] // [3,4,6] would be cool
This would retrieve elements from index 1, 5 and 3 respectively.
That last example can be achieved using PermutationGenerator:
let array = [1,3,9,6,3,4,7,4,9]
let perms = PermutationGenerator(elements: array, indices: [1,5,3])
// perms is now a sequence of the values in array at indices 1, 5 and 3:
for x in perms {
// iterate over x = 3, 4 and 6
}
If you really need an array (just the sequence may be enough for your purposes) you can pass it into Array's init method that takes a sequence:
let newArray = Array(perms)
// newArray is now [3, 4, 6]
For your first example - with arrays, that will work as-is. But it looks from your comments like you're trying it with strings as well. Strings in Swift are not random-access (for reasons relating to unicode). So you can't use integers, they have an String-specific bidirectional index type:
let s = "Hello, I must be going"
if let i = find(s, "I") {
// prints "I must be going"
println(s[i..<s.endIndex])
}
This works :
var n = 4
var newArray = array[0..<n]
In any case in
Slicing Arrays in Swift you'll find a very nice sample of the Python slice using a extension to Arrays in Swift.

Resources