【问题标题】:Is using too many IF statements a problem? SWIFT使用太多 IF 语句有问题吗?迅速
【发布时间】:2021-02-17 10:54:26
【问题描述】:

我目前正在完成一项名为比较三元组 (https://www.hackerrank.com/challenges/compare-the-triplets/problem) 的黑客等级挑战,我只是想知道使用太多 IF 语句是否被认为是不好的编程习惯?除了使用 switch 语句之外,还有什么替代方法。请在下面查看我的代码解决方案:

import Foundation

func compareTriplets(a: [Int], b: [Int]) -> [Int] {
    
  var compareArray = [0,0]
    
    if a[0] == b[0]{
      compareArray[0] = compareArray[0]
    }
    if a[0] < b[0]{
      compareArray[0] = compareArray[0] + 1
    }
    if a[1] < b[1] {
        compareArray[0] = compareArray[0] + 1
    }
    if a[2] < b[2] {
        compareArray[0] = compareArray[0] + 1
    }
    if a[0] > b[0]{
      compareArray[1] = compareArray[1] + 1
    }
    if a[1] > b[1] {
        compareArray[1] = compareArray[1] + 1
    }
    if a[2] > b[2] {
        compareArray[1] = compareArray[1] + 1
    }
    
    return compareArray
}

print(compareTriplets(a: [17,28,30], b: [99,28,8]))

【问题讨论】:

  • 这会使代码更难阅读。您正在使用 if 而不是 if/else 这不合逻辑,因为 if a == b 例如,检查 a

标签: swift if-statement


【解决方案1】:

如果您发送的数组中的元素越来越多,这将大大扩展。

为什么不试试类似的东西

func compareTriplets(a: [Int], b: [Int]) -> [Int] {
    var compareArray = [0,0]
    
    if a.count != b.count {
        return compareArray
    }
    for index in 0..<(a.count) {
        if a[index] > b[index] {
            compareArray[0] += 1
        }
        else if a[index] < b[index] {
            compareArray[1] += 1
        }
    }
    
    return compareArray
}

当然,如果数组长度可以不同,那么您可以取 min 或转到最小数组长度。

【讨论】:

  • 因为我的大脑不允许我这样想,我应该放弃编程吗?
  • 不!差远了!你只需要继续练习和编码!不要放弃。
  • 如果你对编程感兴趣,你应该继续。你的大脑现在不会让你这样想,但是通过一些练习你肯定会的;)
  • @BabyProgrammer 我遇到了同样的问题,尝试学习一些其他语言(c 对我有很大帮助),然后快速返回。它将让您了解许多在开始时可能看起来很难的基本概念
猜你喜欢
  • 2014-04-25
  • 1970-01-01
  • 2014-01-23
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多