1 of 4
Sanchises
  • 9.5k
  • 1
  • 35
  • 61

#MATLAB / Octave

Of course, writing your own loops is fun for programmers, but everybody knows how tedious keeping track of indexing really is (who hasn't written for(j=i;j<n;i++) in a nested loop at least once in their lives?)

MATLAB has the solution. Really, this code is not the most efficient, and certainly not code-golfed, but it is by all means a good showcase of MATLAB's more interesting functions. Octave is the GNU version of MATLAB; it is however not suitable for code-golf since it is slightly stricter with variable types, which is detrimental for code-golf.

%Initialization (boring stuff)
function out = fizzjazzbuzz(n) 
    %Datatype of `out`? Don't know, don't care; it's free to change based
    %on the input, negating the need for different function prototypes for
    %functions that do the same thing for different data.
    numberlist=1:n;                 %Who needs a loop to fill an array?
    fizz=cell(1,100);       %MATLAB all-purpose container: cell!
    jazz=fizz;buzz=jazz;    %Taking DRY to a whole new level...
    
    %Now for the fun part. MATLAB's all-powerful logical indexing. If
    %you're looping over an array in MATLAB, chances are you could just as
    %well use logical indexing, which is always more readable.
    fizz(~mod(numberlist,3))={'Fizz'}; 
    jazz(~mod(numberlist,4))={'Jazz'};
    buzz(~mod(numberlist,5))={'Buzz'};
    %Oh no, you have three seperate arrays now. What complex loops are you
    %going to use to combine all three of them?
    out=strcat(fizz,buzz,jazz); %There.
    %You forgot to fill in the 'normal' numbers... Surely, NOW you'll have
    %to use a loop to fill those in?
    out(cellfun(@isempty,out))=num2cell(numberlist(cellfun(@isempty,out)));
    
    %Okay... then at least use a loop for creating a printable output.
    out=cellfun(@num2str,out,'UniformOutput',0);    %Nopety
    strjoin(out,sprintf('\n'))                      %nope
end
Sanchises
  • 9.5k
  • 1
  • 35
  • 61