BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Checkpoint 3 - Is my solution optimal ?

Forums > SwiftUI

Hello everyone !

This is the solution I devised for Checkpoint 3 and it works 🙂

It doesn't seem to be Paul's prefered solution, though.

Is my solution as good, or is Paul's solution more efficient, and why ?

Thank you !

for i in 1...100 {
    if i % 3 == 0 && i % 5 != 0 {
    print("Fizz")
    }else if i % 5 == 0 && i % 3 != 0{
        print("Buzz")
    }else if i % 3 == 0 && i % 5 == 0 {
        print("FizzBuzz")
    }else{
        print(i)
    }
}

2      

I'm also learning so I can't say that there is just one solution, what should be the best. I think that there are more then one option to resolve this checkpoint. And yours works. So that is good I guess. I did it a little diffent again. And that worked aswel

2      

Pierre wants to know if he gets credit:

Is my solution as good, or is Paul's solution more efficient, and why ?

Welcome to Checkpoint 3!

Your solution works, so as @Suzanne points out, That's Great!

Are there better solutions to this Challenge? Sure, but you've not learned all the tricks yet. You haven't explored other coding techniques, nor have you gained the experience to rethink solutions. This will come with practice.

I'll share a few observations, but please don't worry that you didn't code this as tightly as possible. You're still learning.

You wrote:

if i % 3 == 0 && i % 5 != 0 {  // Yikes! what's all this robot / maths syntax?!
    print("Fizz")
}

To me, this looks like you've coded in C++, or perhaps JAVA. This code reeks of math formulae. You almost need an advanced education in maths symbols to understand this. Indeed, there's a more Swifty way to code the same thing.

// This solution is more Swifty, easier to read...
if i.isMultiple(of: 3) {
    print("Fizz")  // only print if i can be divided evenly by 3
}

Also, if you put the test for FizzBuzz first (multiple of 3 AND a multiple of 5), convince yourself that the other two cases only have to determine if your number is a multiple of three, or of five.

So, with a couple of changes to your code, you can make it shorter (fewer comparisons) and easier to read.

Keep Coding!

3      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.