var number: [Int] = [1,2,3,4]
var newArray: [Int] = []
for i in 0...number.count-1{
newArray = number[i] * number[i 1]
}
print(newArray)
I want output like this: [1 * 2, 2 * 3, 3 * 4].
I just don't get it where is the problem...
CodePudding user response:
var number: [Int] = [1,2,3,4]
let things = zip(number, number.dropFirst()).map(*)
Whenever you need to turn something like [1, 2, 3, 4] into pairs (1, 2), (2, 3) etc, then the AdjacentPairs method is useful - in Swift Algorithms package - https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/AdjacentPairs.swift
Or you can zip
a collection with its dropFirst
for the same result.
And whenever you need to turn an [A]
s into an [B]
s then map
with a function that turns As into Bs. So in this example you want to turn an array of tuples of Int, like [(1,2), (2,3), (3,4)] into array of Int, like [2, 6, 12] by multiplying the 2 Ints together, so map
with *
The benefit of writing it this way is you would avoid the issues with your array mutation, getting index values wrong, running off the ends of arrays etc, and it's often easier to read and think about if you express it without the indices and assignments.
CodePudding user response:
The problem that the compiler flags you is that you assign a single Int
value to an array of Int
. The following line will resolve that immediate issue:
newArray.append(number[i] * number[i 1])
This should pass compilation but then create a runtime error at execution. The reason is that when you try to fetch number[i 1]
when i == number.count-1
, you actually fetch number[number.count]
. This entry does not exist with 0-based indices. To get 3 sums out of 4 array entries, your loop should iterate 3 times:
for i in 0 ..< number.count-1 {
Or, if you prefer closed ranges:
for i in 0 ... number.count-2 {
A more Swifty way would be to use map
, as @Dris suggested. The return type for map
is implicitly given by the result of the multiplication, so you can write:
let newArray = number.indices.dropLast().map { i in
number[i] * number[i 1]
}
CodePudding user response:
You can use map()
let numbers = [1,2,3,4]
let newArray = numbers.enumerated().map { $1 * numbers[($0 1) % numbers.count] }
CodePudding user response:
May be you should not loop to count-1 but stop before and add result to array :
for i in 0..<number.count-1 {
newArray.append(number[i] * number[i 1])
}