FizzBuzz with more parameters in SwiftUltimate FizzBuzzShort Java FizzBuzz using recursion and parametersIs this FizzBuzz Swift-y?Down with FizzBuzz… LOLSwift complexities with DictionaryUltimate FizzBuzzFizzBuzz in Swift 2FizzBuzz in accordance with standardsFizzBuzz with debugging outputNavigation controller in SwiftMVVM in Swift iOS
What would it take to get a message to another star?
Finding the shaded region
How can I shoot a bow using strength instead of dexterity?
How to prevent criminal gangs from making/buying guns?
Do I have to cite common CS algorithms?
How would armour (and combat) change if the fighter didn't need to actually wear it?
Units of measurement, especially length, when body parts vary in size among races
What is the most difficult concept to grasp in Calculus 1?
How can I find an old paper when the usual methods fail?
Why does Japan use the same type of AC power outlet as the US?
Attacking the Hydra
Boss wants me to ignore a software API license
How do I ask for 2-3 days per week remote work in a job interview?
Prestidigitation to replace bathing and washing clothes worn?
What are the odds of rolling specific ability score totals in D&D?
Are there really no countries that protect Freedom of Speech as the United States does?
What is the hottest thing in the universe?
Escape Velocity - Won't the orbital path just become larger with higher initial velocity?
What unique challenges/limitations will I face if I start a career as a pilot at 45 years old?
How does the Athlete Feat affect the Ravnica Centaur playable race?
Is there a way to proportionalize fixed costs in a MILP?
Do beef farmed pastures net remove carbon emissions?
How would you translate this? バタコチーズライス
What should I do if actually I found a serious flaw in someone's PhD thesis and an article derived from that PhD thesis?
FizzBuzz with more parameters in Swift
Ultimate FizzBuzzShort Java FizzBuzz using recursion and parametersIs this FizzBuzz Swift-y?Down with FizzBuzz… LOLSwift complexities with DictionaryUltimate FizzBuzzFizzBuzz in Swift 2FizzBuzz in accordance with standardsFizzBuzz with debugging outputNavigation controller in SwiftMVVM in Swift iOS
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3
and 5
).
I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz
return values.
I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.
How can I improve it?
func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String
var result: String = ""
for key in responsesByMultiples
let (multiple, response) = key,
isMultiple: Bool = (n % multiple) == 0
if isMultiple
result += response
return result == "" ? String(n) : result
for i in 1...100
print(fizzBuzz(n: i))
swift fizzbuzz
$endgroup$
add a comment |
$begingroup$
Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3
and 5
).
I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz
return values.
I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.
How can I improve it?
func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String
var result: String = ""
for key in responsesByMultiples
let (multiple, response) = key,
isMultiple: Bool = (n % multiple) == 0
if isMultiple
result += response
return result == "" ? String(n) : result
for i in 1...100
print(fizzBuzz(n: i))
swift fizzbuzz
$endgroup$
add a comment |
$begingroup$
Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3
and 5
).
I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz
return values.
I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.
How can I improve it?
func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String
var result: String = ""
for key in responsesByMultiples
let (multiple, response) = key,
isMultiple: Bool = (n % multiple) == 0
if isMultiple
result += response
return result == "" ? String(n) : result
for i in 1...100
print(fizzBuzz(n: i))
swift fizzbuzz
$endgroup$
Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just 3
and 5
).
I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to BuzzFizz
return values.
I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task.
How can I improve it?
func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -> String
var result: String = ""
for key in responsesByMultiples
let (multiple, response) = key,
isMultiple: Bool = (n % multiple) == 0
if isMultiple
result += response
return result == "" ? String(n) : result
for i in 1...100
print(fizzBuzz(n: i))
swift fizzbuzz
swift fizzbuzz
edited Aug 2 at 22:58
Tiago Marinho
asked Aug 2 at 22:52
Tiago MarinhoTiago Marinho
2741 silver badge13 bronze badges
2741 silver badge13 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
🔆 Bright side
Your code gives the correct output and delivers on the premise of extensibility.
📝 Suggestions
Here are some suggestions:
The name
key
is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict withresponsesByMultiples
. Then It would have made more sense for the latter to be namedkeys
. Personally, I'd prefer to callresponses
orrules
.These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.
You can easily decompose a tuple this way:
for (multiple, response) in responsesByMultiples
...Calling the first element
multiple
is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability thatn
is actually a multiple ofmultiple
. It would make more sense to me to name the first element of the tuplesdividsor
.n
is a bit too generic, usedividend
instead.You don't have to specify the type in
isMultiple: Bool
, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.Instead of using
(n % multiple) == 0
, there is a nice syntax in Swift 5 :n.isMultiple(of: multiple)
(this syntax exacerbates the problem mentioned in 4.)
To check that a String is empty, it is more efficient to check the
.isEmpty
property. Here is a benchmark that confirms it:import Foundation
let array = (0..<1_000_000).map _ in
Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())
do
let start = Date()
let result = array.filter $0 == ""
let end = Date()
print(result.count, end.timeIntervalSince(start))
do
let start = Date()
let result = array.filter $0.isEmpty
let end = Date()
print(result.count, end.timeIntervalSince(start))The execution times are respectively
44ms
and34ms
.
💔 Putting it all together ❤️
Here a version of your code that takes the previous points into account :
func fizzBuzz (
number dividend: Int,
rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
) -> String
var result: String = ""
for (divider, response) in rules
where dividend.isMultiple(of: divider)
result += response
return result.isEmpty ? String(dividend) : result
🧐 Further reading
You can find many implementations of this classic question on Code Review. Here is a quite informative one.
$endgroup$
1
$begingroup$
Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
$endgroup$
– Tiago Marinho
Aug 3 at 0:38
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f225438%2ffizzbuzz-with-more-parameters-in-swift%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
🔆 Bright side
Your code gives the correct output and delivers on the premise of extensibility.
📝 Suggestions
Here are some suggestions:
The name
key
is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict withresponsesByMultiples
. Then It would have made more sense for the latter to be namedkeys
. Personally, I'd prefer to callresponses
orrules
.These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.
You can easily decompose a tuple this way:
for (multiple, response) in responsesByMultiples
...Calling the first element
multiple
is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability thatn
is actually a multiple ofmultiple
. It would make more sense to me to name the first element of the tuplesdividsor
.n
is a bit too generic, usedividend
instead.You don't have to specify the type in
isMultiple: Bool
, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.Instead of using
(n % multiple) == 0
, there is a nice syntax in Swift 5 :n.isMultiple(of: multiple)
(this syntax exacerbates the problem mentioned in 4.)
To check that a String is empty, it is more efficient to check the
.isEmpty
property. Here is a benchmark that confirms it:import Foundation
let array = (0..<1_000_000).map _ in
Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())
do
let start = Date()
let result = array.filter $0 == ""
let end = Date()
print(result.count, end.timeIntervalSince(start))
do
let start = Date()
let result = array.filter $0.isEmpty
let end = Date()
print(result.count, end.timeIntervalSince(start))The execution times are respectively
44ms
and34ms
.
💔 Putting it all together ❤️
Here a version of your code that takes the previous points into account :
func fizzBuzz (
number dividend: Int,
rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
) -> String
var result: String = ""
for (divider, response) in rules
where dividend.isMultiple(of: divider)
result += response
return result.isEmpty ? String(dividend) : result
🧐 Further reading
You can find many implementations of this classic question on Code Review. Here is a quite informative one.
$endgroup$
1
$begingroup$
Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
$endgroup$
– Tiago Marinho
Aug 3 at 0:38
add a comment |
$begingroup$
🔆 Bright side
Your code gives the correct output and delivers on the premise of extensibility.
📝 Suggestions
Here are some suggestions:
The name
key
is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict withresponsesByMultiples
. Then It would have made more sense for the latter to be namedkeys
. Personally, I'd prefer to callresponses
orrules
.These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.
You can easily decompose a tuple this way:
for (multiple, response) in responsesByMultiples
...Calling the first element
multiple
is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability thatn
is actually a multiple ofmultiple
. It would make more sense to me to name the first element of the tuplesdividsor
.n
is a bit too generic, usedividend
instead.You don't have to specify the type in
isMultiple: Bool
, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.Instead of using
(n % multiple) == 0
, there is a nice syntax in Swift 5 :n.isMultiple(of: multiple)
(this syntax exacerbates the problem mentioned in 4.)
To check that a String is empty, it is more efficient to check the
.isEmpty
property. Here is a benchmark that confirms it:import Foundation
let array = (0..<1_000_000).map _ in
Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())
do
let start = Date()
let result = array.filter $0 == ""
let end = Date()
print(result.count, end.timeIntervalSince(start))
do
let start = Date()
let result = array.filter $0.isEmpty
let end = Date()
print(result.count, end.timeIntervalSince(start))The execution times are respectively
44ms
and34ms
.
💔 Putting it all together ❤️
Here a version of your code that takes the previous points into account :
func fizzBuzz (
number dividend: Int,
rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
) -> String
var result: String = ""
for (divider, response) in rules
where dividend.isMultiple(of: divider)
result += response
return result.isEmpty ? String(dividend) : result
🧐 Further reading
You can find many implementations of this classic question on Code Review. Here is a quite informative one.
$endgroup$
1
$begingroup$
Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
$endgroup$
– Tiago Marinho
Aug 3 at 0:38
add a comment |
$begingroup$
🔆 Bright side
Your code gives the correct output and delivers on the premise of extensibility.
📝 Suggestions
Here are some suggestions:
The name
key
is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict withresponsesByMultiples
. Then It would have made more sense for the latter to be namedkeys
. Personally, I'd prefer to callresponses
orrules
.These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.
You can easily decompose a tuple this way:
for (multiple, response) in responsesByMultiples
...Calling the first element
multiple
is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability thatn
is actually a multiple ofmultiple
. It would make more sense to me to name the first element of the tuplesdividsor
.n
is a bit too generic, usedividend
instead.You don't have to specify the type in
isMultiple: Bool
, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.Instead of using
(n % multiple) == 0
, there is a nice syntax in Swift 5 :n.isMultiple(of: multiple)
(this syntax exacerbates the problem mentioned in 4.)
To check that a String is empty, it is more efficient to check the
.isEmpty
property. Here is a benchmark that confirms it:import Foundation
let array = (0..<1_000_000).map _ in
Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())
do
let start = Date()
let result = array.filter $0 == ""
let end = Date()
print(result.count, end.timeIntervalSince(start))
do
let start = Date()
let result = array.filter $0.isEmpty
let end = Date()
print(result.count, end.timeIntervalSince(start))The execution times are respectively
44ms
and34ms
.
💔 Putting it all together ❤️
Here a version of your code that takes the previous points into account :
func fizzBuzz (
number dividend: Int,
rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
) -> String
var result: String = ""
for (divider, response) in rules
where dividend.isMultiple(of: divider)
result += response
return result.isEmpty ? String(dividend) : result
🧐 Further reading
You can find many implementations of this classic question on Code Review. Here is a quite informative one.
$endgroup$
🔆 Bright side
Your code gives the correct output and delivers on the premise of extensibility.
📝 Suggestions
Here are some suggestions:
The name
key
is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict withresponsesByMultiples
. Then It would have made more sense for the latter to be namedkeys
. Personally, I'd prefer to callresponses
orrules
.These rules expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.
You can easily decompose a tuple this way:
for (multiple, response) in responsesByMultiples
...Calling the first element
multiple
is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability thatn
is actually a multiple ofmultiple
. It would make more sense to me to name the first element of the tuplesdividsor
.n
is a bit too generic, usedividend
instead.You don't have to specify the type in
isMultiple: Bool
, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.Instead of using
(n % multiple) == 0
, there is a nice syntax in Swift 5 :n.isMultiple(of: multiple)
(this syntax exacerbates the problem mentioned in 4.)
To check that a String is empty, it is more efficient to check the
.isEmpty
property. Here is a benchmark that confirms it:import Foundation
let array = (0..<1_000_000).map _ in
Double.random(in: 0..<1) < 0.8 ? "" : String("Hello".shuffled())
do
let start = Date()
let result = array.filter $0 == ""
let end = Date()
print(result.count, end.timeIntervalSince(start))
do
let start = Date()
let result = array.filter $0.isEmpty
let end = Date()
print(result.count, end.timeIntervalSince(start))The execution times are respectively
44ms
and34ms
.
💔 Putting it all together ❤️
Here a version of your code that takes the previous points into account :
func fizzBuzz (
number dividend: Int,
rules: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]
) -> String
var result: String = ""
for (divider, response) in rules
where dividend.isMultiple(of: divider)
result += response
return result.isEmpty ? String(dividend) : result
🧐 Further reading
You can find many implementations of this classic question on Code Review. Here is a quite informative one.
answered Aug 3 at 0:23
ielyamaniielyamani
6281 gold badge4 silver badges15 bronze badges
6281 gold badge4 silver badges15 bronze badges
1
$begingroup$
Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
$endgroup$
– Tiago Marinho
Aug 3 at 0:38
add a comment |
1
$begingroup$
Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
$endgroup$
– Tiago Marinho
Aug 3 at 0:38
1
1
$begingroup$
Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
$endgroup$
– Tiago Marinho
Aug 3 at 0:38
$begingroup$
Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!
$endgroup$
– Tiago Marinho
Aug 3 at 0:38
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f225438%2ffizzbuzz-with-more-parameters-in-swift%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown