How to get each N element of array in Swift? [duplicate] - arrays

This question already has answers here:
Swift Append every second item to Array
(5 answers)
Closed 1 year ago.
I have an array of, for example 10 elements:
var Ar = [0,1,2,3,4,5,6,7,8,9]
And I need to make new array from current array by taken each second element for example -
var newAr = [1,3,5,7,9]
How can I do it in Swift?

You can loop over all the indices, and if an odd number, append it to a result array.
Example:
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var result = [Int]()
for index in arr.indices {
if !index.isMultiple(of: 2) {
result.append(arr[index])
}
}
print(result)

Related

Swift: is there an "elegant" way to filter a dictionary value (which is an array)? [duplicate]

This question already has answers here:
Swift: Filter a Dictionary with Array as Value
(3 answers)
Closed 1 year ago.
here is this simple example:
let i: [String: [Int]] = ["a": [1, 3, 6, 10],
"b": [3, 4, 8, 12]]
I would like to create a new dictionary, filtering the arrays in order to get only values which are lower than 7. I wrote this:
var j: [String: [Int]] {
var result = [String: [Int]]()
i.forEach { key, value in
result[key] = value.filter({ $0 < 7 })
}
return result
}
I would like to know, however, if there is a simpler and more elegant way to do this?
Thank you for your help!
You can use mapValues and then filter for the actual values
let output = i.mapValues { $0.filter { value in value < 7 } }

Is there an easy way to compute difference between two arrays [duplicate]

This question already has answers here:
How to multiply two arrays element-wise
(5 answers)
Closed 3 years ago.
I am trying to compute the difference between the values in two arrays in Swift. I want to subtract values at each index between two arrays.
I tried doing the following:
var array1 : [Double] = [1, 2, 3, 4, 5]
var array2 : [Double] = [2, 3, 4, 5, 6]
var result = array2 - array1
Expected answer:
result = [1, 1, 1, 1, 1]
I get the following error message:
Binary operator '-' cannot be applied to two '[Double]' operands
The following worked:
var array1 : [Double] = [1, 2, 3, 4, 5]
var array2 : [Double] = [2, 3, 4, 5, 6]
let velocity = (0..<5).map { array2[$0] - array1[$0] }
print(velocity)
I wanted to understand if there is an efficient way to accomplish this.
Your attempt works quite well. In general, you would need to check which array has the fewer elements (just in case):
(0..<(min(array1.count, array2.count))).map { array2[$0] - array1[$0] }
Or, as Connor mentioned in their answer, use zip, which handles this comparison of array lengths for you.
zip(lhs, rhs).map { $0.0 - $0.1 }
You can go one step further and overload the - operator to achieve the syntax you wanted (array1 - array2):
func -<T: Numeric>(lhs: [T], rhs: [T]) -> [T] {
return zip(lhs, rhs).map(-)
}
// usage:
print([1,2,3] - [0, 1, 2])
But do note that, to other people, it might be quite unclear what an array “minus” another array means.
You can zip the 2 arrays together to get pairs of elements, and then map over them:
let result = zip(array1, array2).map { $0 - $1 }
Note that, with this method, if one array has more elements than the other, those extra elements will be ignored.

Trying to make a specific index in my array to no longer be of array type [duplicate]

This question already has answers here:
Flatten [Any] Array Swift
(3 answers)
Closed 4 years ago.
I have an array that takes in a set of values. At a certain index in the array, the value is an array. So it looks like this
[1, 2, 3, [4, 5]]
I'm trying to change the array value to be like this
[1, 2, 3, 4, 5]
How would you go back about doing this in Swift?
Here is how I get the result
let array = [value1, value2, [value3, value4]].compactMap{$0}
Here is a straightforward solution that handles int values and arrays of ints in the original array
let arr:[Any] = [1, 2, 3, [4, 5]]
var output: [Int] = []
for x in arr {
if let value = x as? Int {
output.append(value)
} else if let array = x as? [Int] {
output.append(contentsOf: array)
}
//else ignore
}

Swift 3 - check, how many identical elements array contents [duplicate]

This question already has answers here:
Removing duplicate elements from an array in Swift
(49 answers)
Closed 5 years ago.
I have an [Int] array and I need to check for all elements, that don't have identical value with some another element. Those non- identical elements I would like to insert to a new array.
var spojeni1 = [1, 1, 2, 3, 4, 4] // Here it is values 2,3
var NewArray = [Int]()
for i in spojeni1 {
if { // the value hasn't another identical value in the array
NewArray.append(i)
}
}
Hope it is clear, thank you
This can be done in a single line:
let numbers = [1, 1, 2, 3, 4, 4] // Here it is values 2,3
let uniques = Set(numbers).filter{ (n) in numbers.filter{$0==n}.count == 1 }
UPDATE
With Swift 4, you could also use a dictionary constructor to do it:
let uniques = Dictionary(grouping:numbers){$0}.filter{$1.count==1}.map{$0.0}
I would make use of 2 sets:
var seenOnce: Set<Int> = []
var seenMorethanOnce: Set<Int> = []
let input = [1, 1, 2, 3, 4, 4]
for number in input
{
if seenMorethanOnce.contains(number)
{
// Skip it since it's already been detected as a dupe.
}
else if seenOnce.contains(number)
{
// We saw it once, and now we have a dupe.
seenOnce.remove(number)
seenMorethanOnce.insert(number)
}
else
{
// First time seeing this number.
seenOnce.insert(number)
}
}
When that for loop finishes, the seenOnce set will have your values, and you can easily convert that to an array if you wish.

Create a range or array of integers up to a total int number [duplicate]

This question already has answers here:
Is there a way to instantly generate an array filled with a range of values in Swift?
(4 answers)
Closed 7 years ago.
I want to be able to convert a whole int to an array of elements. So If the int is 4 I want to be able to convert it to an array with 4 elements. Like so:
var num = 4
var arr = [1,2,3,4]
You could use an Int's array initializer with a range.
Either:
let arr = [Int](1...4)
or:
let arr = Array(1...4)
Result:
[1, 2, 3, 4]
let num = 4
let arr = Array(1...num)

Resources