I am trying to do fizzbuzz on a list of numbers, so if a number is divisible by 3 evenly, it gets replaced by "Fizz", if it is divisible by 5 evenly, it gets replaced by "Buzz", and if it is divisible by both, it gets replaced with "FizzBuzz".
For example, {1, 2, 3, 4, 5, 15} would turn into {1, 2, Fizz, 4, Buzz, FizzBuzz}.
However, my code isn't working as intended. The result variable in the For loop is always empty, even if the condition in the If function is true, so the same list that was passed into the function is returned. Why is this happening?
Code:
fizzbuzz[x_] := Module[{newList}, newList = x; For[i=1,i<=Length[x],i++,Module[{result},result="";result<> If[Mod[x[[i]], 3]==0, "Fizz", ""];result<>If[Mod[x[[i]], 5]==0, "Buzz", ""];If[result!="", newList[[i]]=result,]]];newList]
resultto its updated values. Replace the instances ofresult <> ...withresult = result <> .... – march Mar 09 '24 at 00:58CreateDataStructure– flinty Mar 09 '24 at 11:45