samedi 20 février 2021

How can I iterate through a list in Mathematica and replace the values with a string if they are divisible by something.?

I need to take an input n and then output a list 1 to n where all the numbers that are divisible by 3 are replaced with "string". This is my code:

FizzBuzz[n_Integer] :=
 (x = Range[n];
  For[i = 0, i < n, i++, 
   If[Divisble[i, 3], ReplaceAll[x, i -> "Buzz"], Null]];
  x)

This is my input:

FizzBuzz[12]

This is my output:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

How come 3, 6, 9 and 12 are not being replaced with "Buzz"?

I have also tried:

x = Range[12]
For[i = 1, i < 12, i++, ReplaceAll[x, i -> "string"]]

Which outputs this:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Which I am guessing indicates that the problem with the code is the ReplaceAll bit but im not sure why.

Aucun commentaire:

Enregistrer un commentaire