Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using too many IF statements a problem? SWIFT

I am currently completing a challenge on hacker rank called compare the triplets (https://www.hackerrank.com/challenges/compare-the-triplets/problem), and I was just wondering if using too many IF statements is considered bad programming practice? What are the alternatives other than using switch statements. Please see my code solution below :

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]))
like image 273
BabyProgrammer Avatar asked Nov 20 '25 07:11

BabyProgrammer


1 Answers

This will expand a lot if you will have more and more elements in arrays you send.

Why not try something like

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
}

Of course, if array lengths can differ then you can take min or go to minimum array length.

like image 160
Miknash Avatar answered Nov 22 '25 01:11

Miknash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!