Well, that wasn’t listed as a requirement. The code as I delivered it has 9 lines in it.
One is completely redundant (two versions for printing output, one is prettier because it has line numbers);
Two lines are there solely for readability (line 2 and 3) and can be removed, with their expression equivalents directly integrated into (current) lines 5-7…
With some loss of generality, one can remove the first line as well.
So that brings the code down to 5 lines, at the cost of hardwiring in n=100 in multiple statements.
If you really wanted to economise on # of lines, then your looped if statements are shorter, but a vectorized solution will run faster as well as being easier to read.
EDIT: jmh made the code more general, which of course isn’t a bad idea, but does start to make it more complex. I do like how it solves the problem of appending Fizz Buzz and whatever else comes up.
As for the output being integers versus text. I’m not sure this makes much sense. Either you are going to return the output to a data object, which typically will expect an array or vector of a constant type, or you are going to output it to something like a printer or a text file, where strings and integers are going to look pretty much identical anyway. I suppose you could want to output to some kind of XML that says whether it is a number or a word, but that wasn’t in the requirements either.
In C, you could use pointers to write integers and characters directly to memory, I suppose, and then return an array of pointers to their location, but that sounds to me like an messy way of handling stuff that is almost guaranteed to blow up at some point if it’s mishandled. You’d want a class or structure that has a pointer and then a bool saying whether it’s a number or a string, and then some kind of array of all of them. Unless there is a compelling reason to organize memory that way, it sounds like a bad idea if done solely for the sake of saving a few lines of code.
I suppose could add a line like this:
for (i in 1:100) { ifelse( ((i %% 5) | (i %% 3)), print( output[i] ), print( format(i, digits=3) ) ) }
But if it’s important to know which are strings and which are not, I would probably just create a vector like "outputIsChar
output[outputIsChar] -> all the entries which are strings
output[!outputIsChar] -> all the entries which are not strings.