false
我想将第一个元素与下一个元素相乘,直到最后一个元素与第一个元素相乘
示例:
var numbers = [2, 4, 3, 7]
var computed = numbers
print(computed)
,输出将为2*4, 4*3, 3*7, 7*2
答案 0 :(得分:4)
我不懂Swift语言,但是算法非常简单,不依赖任何技术。试试这个:
let numbers = [2, 4, 3, 7]
let indexAndNum = numbers.enumerated().map { (index, element) in
return element * numbers[(index + 1) % numbers.count]
}
print(indexAndNum)
现场演示here
答案 1 :(得分:0)
var resultArray = [Int]()
for (index, number) in numbers.enumerated() {
if index < numbers.count - 1 {
resultArray.append(number * numbers[index + 1])
} else {
resultArray.append(number * numbers[0])
}
}
print(resultArray)
答案 2 :(得分:0)
塞巴斯蒂安·卡兹马里克(Sebastian Kaczmarek)的简洁版本:-
let numbers = [2, 4, 3, 7]
let computed = numbers.enumerated().map { $1 * numbers[($0 + 1) % numbers.count] }
print(computed)
输出:-
[8, 12, 21, 14]
答案 3 :(得分:-2)
嘿,试试看,这样就可以了:
var numbers = [2, 4, 3, 7]
numbers.enumerated().forEach { index, value in
return value * numbers[(index + 1) % numbers.count]
}
// numbers is now [8, 12, 21, 14]