1
$\begingroup$

I'm working my way through Mathematica Challenges and tripped myself up on the first question. I have a basic piece of code which works, but am having trouble formatting it to be a proper written function. In searching for an answer myself, people online have made all sorts of shorter elegant solutions for this popular programming problem but my question is far simpler in that I don't know why my function is failing when I try to write it.

The working code I have:

 If[Mod[#,3]==Mod[#,5]==0,"fizzbuzz", 
  If[Mod[#,3]==0,"fizz",
   If[Mod[#,5]==0,"buzz",#]]] &/@ Range[100]

Wrapped into the function fizzbuzz:

 fizzbuzz[n_Integer]:= Module[{n},
  If[Mod[#,3]==Mod[#,5]==0,"fizzbuzz",
   If[Mod[#,3]==0,"fizz",
    If[Mod[#,5]==0,"buzz",#]]] &/@ Range[n]]

But fizzbuzz[100] just fails with no error given.

$\endgroup$
  • 1
    $\begingroup$ Syntax coloring should have clued you in to the issue. You can’t use n as both an argument and a module variable $\endgroup$ – Carl Woll Dec 19 '17 at 3:32
2
$\begingroup$

You don't need Module[]

fizzbuzz[n_Integer] := 
 If[Mod[#, 3] == Mod[#, 5] == 0, "fizzbuzz", 
    If[Mod[#, 3] == 0, "fizz", If[Mod[#, 5] == 0, "buzz", #]]] & /@ 
  Range[n]

The following provides the test:

fizzbuzz[100] == (If[Mod[#, 3] == Mod[#, 5] == 0, "fizzbuzz", 
     If[Mod[#, 3] == 0, "fizz", If[Mod[#, 5] == 0, "buzz", #]]] & /@ 
   Range[100])

returning: True

$\endgroup$
  • $\begingroup$ I had actually tried it without module initially. Trying your code in a new notebook worked. It might have been a quirk in MMA Online but it least it looks like I was doing it correctly. Thanks for the help. $\endgroup$ – BBirdsell Dec 19 '17 at 4:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.