【问题标题】:multiply the number in the array if it matches the given one如果与给定的数字匹配,则将数组中的数字相乘
【发布时间】:2021-08-04 15:32:39
【问题描述】:

我有一个这样的数组,如果是3,我需要乘以一个数字,但最后reduce消除了所有等于3的数字,并将其余的相乘。我该如何解决这个问题?

 let arr = [2, 4, 3, 1, 4, 3, 1, 3, 10, 4, 2, 13]

 let aaa = arr.reduce([]) { $1 == 3 ? $0 : $0 + [$1 * 5] }

//[10, 20, 5, 20, 5, 50, 20, 10, 65]
//[2,4,15,1,4,15,1,15,10,4,2,13] need this

【问题讨论】:

  • 你应该使用地图。

标签: swift reduce


【解决方案1】:

你应该使用 map 而不是 reduce

let arr = [2, 4, 3, 1, 4, 3, 1, 3, 10, 4, 2, 13]

let result = arr.map { $0 == 3 ? 15 : $0 }
// [2, 4, 15, 1, 4, 15, 1, 15, 10, 4, 2, 13

或者如果它应该适用于 3 的任何倍数

let result = arr.map { $0.isMultiple(of: 3) ? $0 * 5 : $0 }

【讨论】:

  • 实际上它说“乘以一个数字如果它是 3”所以我认为它只是 3 这意味着你实际上可以直接返回 15...
  • 这是真的,@JoakimDanielson,只是习惯了这么多问题是多个(的:)。我已经更新了我的答案。
猜你喜欢
  • 2019-10-10
  • 1970-01-01
  • 2019-09-04
  • 2020-05-26
  • 2015-09-22
  • 2021-02-05
  • 2020-05-24
  • 2021-07-12
  • 1970-01-01
相关资源
最近更新 更多