Swift Fun Algorithms #1: FizzBuzz

preview_player
Показать описание
We're going to take a quick break from building apps today to go over a very simple and straightforward algorithm called FizzBuzz. The general idea behind this algorithm is to run through a list of numbers and print Fizz when divisible by 3, Buzz when divisible by 5, and FizzBuzz when divisible by both 3 and 5.

Code available here:

Рекомендации по теме
Комментарии
Автор

Now, Array can also be created using a sequence. var oneThousandNumbers = Array(1...1000)

jabraham
Автор

Separate the conditionals, and concatenate a string as follows:

var result = "";

if num % 3 == 0 {
result += "fizz"
}

if num % 5 == 0 {
result += "buzz"
}

print(result);

voila!

lancewalker
Автор

Thanks that was very interesting. I am going to try it myself without looking back at the video.

stepbystepscience
Автор

Here is my solution. Putting the fizzBuzz logic in a function that takes an Int and returns a String also makes it testable. Swift also has the isMultiple(of:) method, which I think looks a bit nicer.

So this takes a range of numbers 1 to and including 1000. Map will perform the fizzBuzz function on every single item in the range. Because the fizzBuzz function takes one Int then we can use the shorthand syntax. We then take the array of String that the map generates and forEach and print each value "1", "2", "Fizz", "4", "Buzz" etc

(1...1000)
.map(fizzBuzz)
.forEach { print($0) }

func fizzBuzz(_ num: Int) -> String {
switch (num.isMultiple(of: 3), num.isMultiple(of: 5)) {
case (true, true): return "FizzBuzz"
case (true, false): return "Fizz"
case (false, true): return "Buzz"
case (false, false): return String(num)
}
}

func {
XCTAssertEqual(fizzBuzz(1), "1")
}

func {
XCTAssertEqual(fizzBuzz(3), "Fizz")
}

func {
XCTAssertEqual(fizzBuzz(5), "Buzz")
}

func {
XCTAssertEqual(fizzBuzz(15), "FizzBuzz")
}

mistymu
Автор

This is a trick question. The solution you provided is the naive solution. The “correct” solution is:

if num % 3 == 0 {
print(“fizz”)
}
if num % 5 == 0 {
print(“buzz”)
}

It handles all cases. You don’t need else clauses.

OroborOSX
Автор

This is great Chris keep going with the Algorithms its great content

alphainfo
Автор

Do you need the numbers array at the very top after you made the oneThousandNumbers array? Cuz I deleted the numbers array and it still works, but I don’t know why. Can someone explain? Is the num in for num in, a don’t care case? Like you could put anything in there like the i?

LoriWolfcat
Автор

we can just do the operation inside a for loop with 1 ... 1000. right?

ambientnaturalsounds
Автор

Hi loved your videos, recently i got a job as ios app developer i was from java, python background i was completely new to ios, learning swift, i was using ubuntu 16.04 i want ide that runs on ubuntu can you suggest one in ubuntu!!!!...

nallamillibalaveeraraghava
Автор

Thanks so much for these Algorithm challenges!

tomtravolta
Автор

hope you can post more Algorithms about Swift. Thanks ! fully support here !!

kidstagram
Автор

Hey Chris, great tutorials with an awesome format. Quick question.. For the modulo operator why are we putting "==0" to each one?

handicapper
Автор

Hi Brian .Can you please make a video showing how to map array of int to array of strings?

GG-hkiz
Автор

Challenge: Print a statement which counts the Fizzes, the Buzzes and the FizzBuzzes

Thanks, I've learned two new things, although I was capable of solving everything myself.

TheAlderFalder
Автор

A PSA/commentary, not directed at Brian...

Following on from Quisqueyano G91's comments, I did some testing. Turns out that Swift Array's _.append()_ method is horrendously slow. As in geologically slow. Even if you (allegedly) reserve space with the _.reserveCapacity()_ method, it's still tragic. So you never want to build a long list with _append()_! (At least not in a Playground, or in a debug build.)

If you know the values ahead of time, like in fizz-buzz (e.g. 1 to 15) then you can use Quisqueyano G91shorthand.

But if you need to build a list of values dynamically, DON'T use append. Instead, pre-build the entire array. THEN slot in the values you need. This is orders of magnitude faster.

e.g.

private let kLimit = 1000
var numbers = Array(repeating: 0, count: kLimit)
for i in 0..<kLimit {
numbers[i] = i + 1
}
print(numbers)

wmblemania
Автор

Learnt python not very long ago, this is my solution,
x = 1
for x in range(1, 100):
test1 = x % 3
test2 = x % 5
If test1 == 0 and test2 == 0:
print(FizzBuzz)
elif test1 == 0
print(fizz)
elif test2 == 0
print(buzz)
else
print(x)

x = x+1


Yeah, i know that to make it work with more stuff you'd have to create a new variable AND a new elif statement.... but thats what i can do

Fede_uyz
Автор

I have never met any better coding teacher ;)
Wish you the best bro

azicktusmatov
Автор

Your tuts are great!! The coding is so clean and nice. One thing I would like from your videos though... could you please zoom into the code? barely can see especially on mobiles. Thanks alot!

sunwoo
Автор

what would you do if you just wanted buzz, fizz, or fizzbuzz when you put in one input

darkninjapockiepiratex
Автор

Hi how can i make a UICollection Reusable Views . Thanks for the great Tutorials :D

coding