General FizzBuzz: Difference between revisions

Content added Content deleted
(Added R.)
(→‎{{header|R}}: Changed variable name, refactored if statement, and added new solution.)
Line 2,651: Line 2,651:
</pre>
</pre>
=={{header|R}}==
=={{header|R}}==
===... solution===
The task asks that we assume 3 factors for the sake of simplicity. However, R makes the k factors case not much more complicated, so we will do that. The only major downside is that checking for malformed user input becomes so difficult that we will not bother.
The task asks that we assume 3 factors for the sake of simplicity. However, R makes the k factors case not much more complicated, so we will do that. The only major downside is that checking for malformed user input becomes so difficult that we will not bother.
<lang r>genFizzBuzz<-function(n,...)
<lang r>genFizzBuzz<-function(n,...)
Line 2,664: Line 2,665:
for(i in 1:n)
for(i in 1:n)
{
{
validFactorIndices<-i %% factors == 0
isFactor<-i %% factors == 0
if(sum(validFactorIndices)==0){print(i)}else{print(paste0(words[validFactorIndices],collapse = ""))}
if(any(isFactor)){print(paste0(words[isFactor],collapse = ""))}else{print(i)}
}
}
invisible()
invisible()
Line 2,671: Line 2,672:
genFizzBuzz(105,c(3,"Fizz"),c(5,"Buzz"),c(7,"Baxx"))
genFizzBuzz(105,c(3,"Fizz"),c(5,"Buzz"),c(7,"Baxx"))
genFizzBuzz(105,c(5,"Buzz"),c(9,"Prax"),c(3,"Fizz"),c(7,"Baxx"))</lang>
genFizzBuzz(105,c(5,"Buzz"),c(9,"Prax"),c(3,"Fizz"),c(7,"Baxx"))</lang>

===Names solution===
If we deviate from the task's example of how to input parameters and instead use R's names function to make our (number, name) pairs, we get a much cleaner solution.
<lang r>namedGenFizzBuzz<-function(n,namedNums)
{
factors<-sort(namedNums)#Required by the task: We must go from least factor to greatest.
for(i in 1:n)
{
isFactor<-i %% factors == 0
if(any(isFactor)){print(paste0(names(factors)[isFactor],collapse = ""))}else{print(i)}
}
invisible()
}
namedNums<-c(3,5,7); names(namedNums)<-c("Fizz","Buzz","Baxx")
namedGenFizzBuzz(105,namedNums)
shuffledNamedNums<-c(5,9,3,7); names(shuffledNamedNums)<-c("Buzz","Prax","Fizz","Baxx")
namedGenFizzBuzz(105,shuffledNamedNums)</lang>


=={{header|Racket}}==
=={{header|Racket}}==