Turning my code into a better Swift like answer for a FizzBuzz response [closed]

梦想与她 提交于 2019-12-21 21:26:37

问题


I was searching the internet last night while working on some programming, and I noticed that there was this interesting test that employers sometimes use for testing programmers to see if they can actually apply code to a real world problem. It is referred to as the FizzBuzz test, and it works like this.

"Write a program that prints the numbers 1 to 100. But, for multiples of 3, print "Fizz" instead of the number and for multiples of 5, print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"."

Now, I sat down and came up with this code very quickly, which I placed in my viewDidLoad method:

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

And, although this fulfils the brief, I feel very dissatisfied by using this as my solution (it seems too simple and basic to me).

I have recently read the book, iOS 9 Programming Fundamentals With Swift by Matt Neuburg (this book has blown my mind and opened my eyes in so many levels). And I am captivated by trying to make things as Swift-y as possible (passing functions, and the like). Then, I came to the sobering and disheartening realisation that I really have no idea how to improve this code.

Therefore, I am turning to the Swift community in hopes that you could better educate me on what would be the most sophisticated Swift answer for the FiizBuzz test question.

I am desperately trying to improve my Swift programming and would like to know a better Swift-y programming approach to my code.


回答1:


Try this in a playground. It is an attempt at a functional approach. It is not efficient.

let range = (1...100)
let fizz  = range.map{ ($0 % 3 == 0) ? "Fizz" : "" }
let buzz  = range.map{ ($0 % 5 == 0) ? "Buzz" : "" }
zip(range, zip(fizz, buzz))
  .map {
    let fb = $1.0 + $1.1
    print(fb.isEmpty ? $0 : fb)
  }




回答2:


Following Dan's link in comments I came up with:

for i in 1...100 {
  switch (i%3, i%5) {
  case (0,0): print("FizzBuzz")
  case (0,_): print("Fizz")
  case (_,0): print("Buzz")
  default: print(i)
  }
}

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz



来源:https://stackoverflow.com/questions/35822271/turning-my-code-into-a-better-swift-like-answer-for-a-fizzbuzz-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!