
Write a generalized version ofFizzBuzz that works for any list of factors, along with their words.
This is basically a "fizzbuzz" implementation where the user supplies the parameters.
The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.
For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.
For example, given:
>20 #This is the maximum number, supplied by the user>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)
In other words: For this example, print the numbers1 through20, replacing every multiple of3 with "Fizz", every multiple of5 with "Buzz", and every multiple of7 with "Baxx".
In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.
For instance, the number15 is a multiple of both3 and5; print "FizzBuzz".
If the max number was105 instead of20, you would print "FizzBuzzBaxx" because it's a multiple of3,5, and7.
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
F genfizzbuzz(factorwords, numbers) V sfactorwords = sorted(factorwords, key' p -> p[0]) [String] lines L(num) numbers V words = sfactorwords.filter2((fact, wrd) -> (@num % fact) == 0).map2((fact, wrd) -> wrd).join(‘’) lines.append(I words != ‘’ {words} E String(num)) R lines.join("\n")print(genfizzbuzz([(5, ‘Buzz’), (3, ‘Fizz’), (7, ‘Baxx’)], 1..20))12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
DEFINE MAX_NUMBERS="200"DEFINE MAX_LEN="20"DEFINE MAX_FACTORS="5"DEFINE PTR="CARD"PROC PrintResult(BYTE max,n BYTE ARRAY factors PTR ARRAY texts) BYTE i,j,t BYTE ARRAY values(MAX_FACTORS) FOR j=0 TO n-1 DO values(j)=1 OD FOR i=1 TO max DO t=0 FOR j=0 TO n-1 DO IF values(j)=0 THEN t=1 Print(texts(j)) FI values(j)==+1 IF values(j)=factors(j) THEN values(j)=0 FI OD IF t=0 THEN PrintB(i) FI Put(32) ODRETURNBYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err) BYTE i FOR i=1 TO s(0) DO IF s(i)=c THEN err^=0 RETURN (i) FI OD err^=1RETURN (0)PROC Main() BYTE max,i,n,pos,err BYTE ARRAY factors(MAX_FACTORS) PTR ARRAY texts(MAX_FACTORS) CHAR ARRAY s(100),tmp(100), t0(MAX_LEN),t1(MAX_LEN),t2(MAX_LEN), t3(MAX_LEN),t4(MAX_LEN) texts(0)=t0 texts(1)=t1 texts(2)=t2 texts(3)=t3 texts(4)=t4 DO PrintF("Max number (1-%B): ",MAX_NUMBERS) max=InputB() UNTIL max>=1 AND max<=MAX_NUMBERS OD n=0 DO PrintF("Number of rules (1-%B): ",MAX_FACTORS) n=InputB() UNTIL n>=1 AND n<=MAX_FACTORS OD FOR i=0 TO n-1 DO DO PrintF("Rule #%B (number space text):",i+1) InputS(s) pos=Find(s,' ,@err) IF pos=1 OR pos=s(0) THEN err=1 FI IF err=0 THEN SCopyS(tmp,s,1,pos-1) factors(i)=ValB(tmp) IF factors(i)<2 THEN err=1 FI SCopyS(texts(i),s,pos+1,s(0)) FI UNTIL err=0 OD OD PutE() PrintResult(max,n,factors,texts)RETURNScreenshot from Atari 8-bit computer
Max number (1-200): 105Number of rules (1-5): 3Rule #1 (number space text):3 FizzRule #2 (number space text):5 BuzzRule #3 (number space text):7 Baxx1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz FizzBaxx 22 23Fizz Buzz 26 Fizz Baxx 29 FizzBuzz 31 32 Fizz 34 BuzzBaxx Fizz 37 38 Fizz Buzz 41 FizzBaxx 43 44FizzBuzz 46 47 Fizz Baxx Buzz Fizz 52 53 Fizz Buzz Baxx Fizz 58 59 FizzBuzz 61 62 FizzBaxx 64 BuzzFizz 67 68 Fizz BuzzBaxx 71 Fizz 73 74 FizzBuzz 76 Baxx Fizz 79 Buzz Fizz 82 83 FizzBaxx Buzz 86Fizz 88 89 FizzBuzz Baxx 92 Fizz 94 Buzz Fizz 97 Baxx Fizz Buzz 101 Fizz 103 104 FizzBuzzBaxx
withAda.Text_IO;useAda.Text_IO;withAda.Integer_Text_IO;useAda.Integer_Text_IO;withAda.Containers.Generic_Array_Sort;withAda.Strings.Unbounded;useAda.Strings.Unbounded;withAda.Text_IO.Unbounded_IO;useAda.Text_IO.Unbounded_IO;procedureMainistypemap_elementisrecordNum:Positive;Word:Unbounded_String;end record;typemap_listisarray(Positiverange<>)ofmap_element;function"<"(Left,Right:map_element)returnBooleanisbeginreturnLeft.Num<Right.Num;end"<";procedurelist_sortisnewAda.Containers.Generic_Array_Sort(Index_Type=>Positive,Element_Type=>map_element,Array_Type=>map_list);proceduregeneral_fizz_buzz(max:Positive;words:inoutmap_list)isfound:Boolean;beginlist_sort(words);foriin1..maxloopfound:=False;forelementofwordsloopifimodelement.Num=0thenfound:=True;Put(element.Word);endif;endloop;ifnotfoundthenPut(Item=>i,Width=>1);endif;New_Line;endloop;endgeneral_fizz_buzz;fizzy:map_list:=((3,To_Unbounded_String("FIZZ")),(7,To_Unbounded_String("BAXX")),(5,To_Unbounded_String("BUZZ")));begingeneral_fizz_buzz(20,fizzy);endMain;
12FIZZ4BUZZFIZZBAXX8FIZZBUZZ11FIZZ13BAXXFIZZBUZZ1617FIZZ19BUZZ
Uses a modified version of the Algol 68 Quicksort task sample.
BEGIN # generalised FizzBuzz # # prompts for an integer, reads it and returns it # PROC read an integer = ( STRING prompt )INT: BEGIN print( ( prompt ) ); INT result; read( ( result, newline ) ); result END; # read an integer # # prompts for a string, reads it and returns it # PROC read a string = ( STRING prompt )STRING: BEGIN print( ( prompt ) ); STRING result; read( ( result, newline ) ); result END; # read a string # # mode to hold a factor and associated text # MODE FBFACTOR = STRUCT( INT factor, STRING text ); #===============================================================# # quicksort routine for the factors # # - from the Algol 68 task sample # #---------------------------------------------------------------# #--- Swap function ---# PROC swap = (REF[]FBFACTOR array, INT first, INT second) VOID: ( FBFACTOR temp = array[first]; array[first] := array[second]; array[second] := temp ); #--- Quick sort 3 arg function ---# PROC quick = (REF[]FBFACTOR array, INT first, INT last) VOID: ( INT smaller := first + 1, larger := last; FBFACTOR pivot := array[first]; WHILE smaller <= larger DO WHILE array[smaller] < pivot AND smaller < last DO smaller +:= 1 OD; WHILE array[larger] > pivot AND larger > first DO larger -:= 1 OD; IF smaller < larger THEN swap(array, smaller, larger); smaller +:= 1; larger -:= 1 ELSE smaller +:= 1 FI OD; swap(array, first, larger); IF first < larger -1 THEN quick(array, first, larger-1) FI; IF last > larger +1 THEN quick(array, larger+1, last) FI ); # comparison operators # OP < = ( FBFACTOR a, b )BOOL: factor OF a < factor OF b; OP > = ( FBFACTOR a, b )BOOL: factor OF a > factor OF b; #===============================================================# # get the maximum number to consider # INT max number = read an integer( "Numbers required: " ); # number of factors required # INT max factor = 3; # get the factors and associated words # [ max factor ]FBFACTOR factors; FOR i TO max factor DO factor OF factors[ i ] := read an integer( "Factor " + whole( i, 0 ) + ": " ); text OF factors [ i ] := read a string( "Text for " + whole( factor OF factors[ i ], 0 ) + ": " ) OD; # sort the factors into order # quick( factors, 1, UPB factors ); # play the game # FOR n TO max number DO STRING text := ""; FOR factor TO max factor DO IF n MOD factor OF factors[ factor ] = 0 THEN text +:= text OF factors[ factor ] FI OD; IF text = "" THEN # no words applicable to n, just show the digits # text := whole( n, 0 ) FI; print( ( text, newline ) ) ODEND
Numbers required: 20Factor 1: 7Text for 7: BaxxFactor 2: 3Text for 3: FizzFactor 3: 5Text for 5: Buzz12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
--------------------- GENERAL FIZZBUZZ --------------------- fizzEtc :: [(Int, String)] -> [Symbol]onfizzEtc(rules)-- A non-finite sequence of fizzEtc symbols,-- as defined by the given list of rules.scriptnumberOrNoiseon|λ|(n)scriptruleMatchon|λ|(a,mk)set{m,k}tomkif0=(nmodm)thenifintegerisclassofathenkelsea&kendifelseaendifend|λ|endscriptfoldl(ruleMatch,n,rules)end|λ|endscriptfmapGen(numberOrNoise,enumFrom(1))endfizzEtc--------------------------- TEST -------------------------onrununlines(take(20,¬fizzEtc({{3,"Fizz"},{5,"Buzz"},{7,"Baxx"}})))endrun------------------------- GENERIC -------------------------- enumFrom :: Enum a => a -> [a]onenumFrom(x)scriptpropertyv:missing valueon|λ|()ifmissing valueis notvthensetvto1+velsesetvtoxendifreturnvend|λ|endscriptendenumFrom-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]onfmapGen(f,gen)scriptpropertyg:mReturn(f)on|λ|()setvtogen's|λ|()ifvismissing valuethenvelseg's|λ|(v)endifend|λ|endscriptendfmapGen-- foldl :: (a -> b -> a) -> a -> [b] -> aonfoldl(f,startValue,xs)tellmReturn(f)setvtostartValuesetlngtolengthofxsrepeatwithifrom1tolngsetvto|λ|(v,itemiofxs,i,xs)endrepeatreturnvendtellendfoldl-- mReturn :: First-class m => (a -> b) -> m (a -> b)onmReturn(f)-- 2nd class handler function lifted into 1st class script wrapper.ifscriptisclassoffthenfelsescriptproperty|λ|:fendscriptendifendmReturn-- take :: Int -> [a] -> [a]-- take :: Int -> String -> Stringontake(n,xs)setysto{}repeatwithifrom1tonsetvto|λ|()ofxsifmissing valueisvthenreturnyselsesetendofystovendifendrepeatreturnysendtake-- unlines :: [String] -> Stringonunlines(xs)-- A single string formed by the intercalation-- of a list of strings with the newline character.set{dlm,mytext item delimiters}to¬{mytext item delimiters,linefeed}setstoxsastextsetmytext item delimiterstodlmsendunlines
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
maxNum:to:integerstripinput"Set maximum number:"facts:map1..3'x->split.wordsstripinput~"Enter factor|x|:"loop1..maxNum'i[printNum:trueloopfacts'fact->ifzero?i%to:integerfact\0[printsfact\1printNum:false]print(printNum)?->i->""]
Set maximum number: 20Enter factor 1: 3 FizzEnter factor 2: 5 BuzzEnter factor 3: 7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
; Test parametersmax:=20,fizz:=3,buzz:=5,baxx:=7Loop%max{output:=""if(Mod(A_Index,fizz)=0)output.="Fizz"if(Mod(A_Index,buzz)=0)output.="Buzz"if(Mod(A_Index,baxx)=0)output.="Baxx"if(output="")FileAppend%A_Index%`n,*elseFileAppend%output%`n,*}
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
This is a two-step solution:
Input:
1053 Fizz5 Buzz7 Baxx
awk-ffizzbuzzGenerate.awkinput.txt>fizzbuzzCustom.awkawk-ffizzbuzzCustom.awknumbers.txt
# usage: awk -f fizzbuzzGen.awk > fizzbuzzCustom.awk#functionPrint(s){prints>"/dev/stderr"}BEGIN{Print("# FizzBuzz-Generate:")q2="\""fN="numbers.txt"#fP = "fizzbuzzCustom.awk"}NF==1{Print("# "$1" Numbers:")for(i=1;i<=$1;i++)print(i)>fN# (!!) write to file not allowed in sandbox at ideone.comPrint("# Custom program:")print"BEGIN {print "q2"# CustomFizzBuzz:"q2"} \n"next}NF==2{Print("# "$1"-->"$2)##print"$1 % "$1" == 0 {x = x "q2$2q2"}"next}END{print""print"!x {print $1; next}"print" {print "q2" "q2", x; x="q2q2"} \n"print"END {print "q2"# Done."q2"}"Print("# Done.")}
Example output seeFizzBuzz/AWK#Custom_FizzBuzz
@echo offrem input rangeset/p"range=> "rem input data (no error-checking)set"data_ctr=0":input_loopset"data="set/p"data=> "if"%data%"equ""gotocountrem parsing data into 1-based pseudo-arrayset/a"data_ctr+=1"for/f"tokens=1-2 delims= "%%Din("%data%")do(set"facto%data_ctr%=%%D"set"print%data_ctr%=%%E")gotoinput_looprem perform fizzbuzz now:countsetlocal enabledelayedexpansionfor/l%%Cin(1,1,%range%)do(set"out="for/l%%Xin(1,1,%data_ctr%)do(set/a"mod=%%C%% facto%%X"if!mod!equ 0set"out=!out!!print%%X!")ifnotdefinedout(echo%%C)else(echo!out!))pauseexit /b 0
> 20> 3 Fizz> 5 Buzz> 7 Baxx>12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19BuzzPress any key to continue . . .
This implementation (unlike some of the ones given on this page...) fully obeys the specification, in that it prompts the user for the parameters at run time. It also allows users to specify as many factors as they want, rather than limiting them to three.
REM >genfizzbINPUT"Maximum number: "max%INPUT"Number of factors: "n%DIMfactors%(n%-1)DIMwords$(n%-1)FORi%=0TOn%-1INPUT"> "factor$factors%(i%)=VAL(LEFT$(factor$,INSTR(factor$," ")-1))words$(i%)=MID$(factor$,INSTR(factor$," ")+1)NEXTFORi%=1TOmax%matched%=FALSEFORj%=0TOn%-1IFi%MODfactors%(j%)=0THENPRINTwords$(j%);matched%=TRUEENDIFNEXTIFmatched%THENPRINTELSEPRINT;i%NEXT
Output:
Maximum number: 20Number of factors: 3> 3 Fizz> 5 Buzz> 7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
GenFizzBuzz←{factors‿words←<˘⍉>𝕨⋄(∾´∾⟜words/˜·(¬∨´)⊸∾0=factors|⊢)¨1+↕𝕩}
Example usage:
⟨3‿"Fizz", 5‿"Buzz", 7‿"Baxx"⟩ GenFizzBuzz 20⟨ 1 2 "Fizz" 4 "Buzz" "Fizz" "Baxx" 8 "Fizz" "Buzz" 11 "Fizz" 13 "Baxx" "FizzBuzz" 16 17 "Fizz" 19 "Buzz" ⟩
#include<stdio.h>#include<stdlib.h>structreplace_info{intn;char*text;};intcompare(constvoid*a,constvoid*b){structreplace_info*x=(structreplace_info*)a;structreplace_info*y=(structreplace_info*)b;returnx->n-y->n;}voidgeneric_fizz_buzz(intmax,structreplace_info*info,intinfo_length){inti,it;intfound_word;for(i=1;i<max;++i){found_word=0;/* Assume sorted order of values in the info array */for(it=0;it<info_length;++it){if(0==i%info[it].n){printf("%s",info[it].text);found_word=1;}}if(0==found_word)printf("%d",i);printf("\n");}}intmain(void){structreplace_infoinfo[3]={{5,"Buzz"},{7,"Baxx"},{3,"Fizz"}};/* Sort information array */qsort(info,3,sizeof(structreplace_info),compare);/* Print output for generic FizzBuzz */generic_fizz_buzz(20,info,3);return0;}
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
Not extremely clever and doesn't use anything too fancy.
usingSystem;publicclassGeneralFizzBuzz{publicstaticvoidMain(){inti;intj;intk;intlimit;stringiString;stringjString;stringkString;Console.WriteLine("First integer:");i=Convert.ToInt32(Console.ReadLine());Console.WriteLine("First string:");iString=Console.ReadLine();Console.WriteLine("Second integer:");j=Convert.ToInt32(Console.ReadLine());Console.WriteLine("Second string:");jString=Console.ReadLine();Console.WriteLine("Third integer:");k=Convert.ToInt32(Console.ReadLine());Console.WriteLine("Third string:");kString=Console.ReadLine();Console.WriteLine("Limit (inclusive):");limit=Convert.ToInt32(Console.ReadLine());for(intn=1;n<=limit;n++){boolflag=true;if(n%i==0){Console.Write(iString);flag=false;}if(n%j==0){Console.Write(jString);flag=false;}if(n%k==0){Console.Write(kString);flag=false;}if(flag)Console.Write(n);Console.WriteLine();}}}
#include<algorithm>#include<iostream>#include<vector>#include<string>classpair{public:pair(ints,std::stringz){p=std::make_pair(s,z);}booloperator<(constpair&o)const{returni()<o.i();}inti()const{returnp.first;}std::strings()const{returnp.second;}private:std::pair<int,std::string>p;};voidgFizzBuzz(intc,std::vector<pair>&v){booloutput;for(intx=1;x<=c;x++){output=false;for(std::vector<pair>::iteratori=v.begin();i!=v.end();i++){if(!(x%(*i).i())){std::cout<<(*i).s();output=true;}}if(!output)std::cout<<x;std::cout<<"\n";}}intmain(intargc,char*argv[]){std::vector<pair>v;v.push_back(pair(7,"Baxx"));v.push_back(pair(3,"Fizz"));v.push_back(pair(5,"Buzz"));std::sort(v.begin(),v.end());gFizzBuzz(20,v);return0;}
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
GENFIZBUZZ(MAX,WORDS,NUMBERS) ; loop until max, casting numeric to avoid errors for i=1:1:+MAX { set j = 1 set descr = "" ; assumes NUMBERS parameter is comma-delimited while (j <= $length(NUMBERS,",")) { if ((i # $piece(NUMBERS,",",j,j)) = 0) { ; build descriptor string, again assuming comma-delimited WORDS parameter set descr = descr_$piece(WORDS,",",j,j) } set j = j + 1 } ; check list of numbers ; output values to screen write " "_$case(descr,"":i,:descr) } ; next value until MAX quitSAMPLES>do ^GENFIZBUZZ(12,"FIN,FANG,FOOM","2,3,4") 1 FIN FANG FINFOOM 5 FINFANG 7 FINFOOM FANG FIN 11 FINFANGFOOM
sharedvoidrun(){print("enter the max value");assert(existsmaxLine=process.readLine(),existsmax=parseInteger(maxLine));print("enter your number/word pairs enter a blank line to stop");variablevaluedivisorsToWords=map<Integer,String>{};while(true){valueline=process.readLine();assert(existsline);if(line.trimmed.empty){break;}valuepair=line.trimmed.split().sequence();if(existsfirst=pair.first,existsinteger=parseInteger(first),existsword=pair[1]){divisorsToWords=divisorsToWords.patch(map{integer->word});}}valuedivisors=divisorsToWords.keys.sort(byIncreasing(Integer.magnitude));for(iin1..max){valuebuilder=StringBuilder();for(divisorindivisors){if(divisor.divides(i),existsword=divisorsToWords[divisor]){builder.append(word);}}if(builder.empty){print(i);}else{print(builder.string);}}}
(defnfix[pairs](map secondpairs))(defngetvalid[pairsn](filter(fn[p](zero?(modn(firstp))))(sort-by firstpairs)))(defngfizzbuzz[pairsnumbers](interpose"\n"(map(fn[n](let[f(getvalidpairsn)](if(empty?f)n(applystr(fixf)))))numbers)))
Usage:
user#=> (def pairs [[5 "Buzz"] [3 "Fizz"] [7 "Baxx"]])#'user/pairsuser#=> (println (apply str (gfizzbuzz pairs (range 1 21))))12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzznil
(defunfizzbuzz(limitfactor-words)(loopforifrom1tolimitif(assoc-if#'(lambda(factor)(zerop(modifactor)))factor-words)do(loopfor(factor.word)infactor-wordswhen(zerop(modifactor))do(princword)finally(fresh-line))elsedo(formatt"~a~%"i)))(defunread-factors(&optionalfactor-words)(princ"> ")(let((input(read-linetnil)))(cond((zerop(lengthinput))(sortfactor-words#'<:key#'car))((digit-char-p(charinput0))(multiple-value-bind(ni)(parse-integerinput:junk-allowedt)(read-factors(aconsn(string-trim" "(subseqinputi))factor-words))))(t(write-line"Invalid input.")(read-factorsfactor-words)))))(defunmain()(loopinitially(princ"> ")forinput=(read-linetnil)until(and(>(lengthinput)0)(digit-char-p(charinput0))(not(zerop(parse-integerinput:junk-allowedt))))finally(fizzbuzz(parse-integerinput:junk-allowedt)(read-factors))))
deffizz_buzz_plus(factorwords,limit)factorwords=factorwords.sort_by{|f,w|f}(1..limit).eachdo|n|shout=""factorwords.eachdo|factor,word|shout+=wordifn%factor==0endputs(shout==""?n:shout)endendfizz_buzz_plus[{3,"Fizz"},{5,"Buzz"},{7,"Baxx"}],20
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
importcore.stdc.stdlib;importstd.stdio;voidmain(){intlimit;write("Max number (>0): ");readf!"%d\n"(limit);if(limit<=0){writeln("The max number to consider must be greater than zero.");exit(1);}intterms;write("Terms (>0): ");readf!"%d\n"(terms);if(terms<=0){writeln("The number of terms to consider must be greater than zero.");exit(1);}int[]factors=newint[terms];string[]words=newstring[terms];for(inti=0;i<terms;++i){write("Factor ",i+1," and word: ");readf!"%d %s\n"(factors[i],words[i]);if(factors[i]<=0){writeln("The factor to consider must be greater than zero.");exit(1);}}foreach(n;1..limit+1){boolprint=true;for(inti=0;i<terms;++i){if(n%factors[i]==0){write(words[i]);print=false;}}if(print){writeln(n);}else{writeln();}}}
Max number (>0): 20Terms (>0): 3Factor 1 and word: 3 FizzFactor 2 and word: 5 BuzzFactor 3 and word: 7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
max = 20words$[] = [ "Fizz" "Buzz" "Baxx" ]keys[] = [ 3 5 7 ]# for n = 1 to max prnt = 1 for j = 1 to len keys[] if n mod keys[j] = 0 write words$[j] prnt = 0 . . if prnt = 1 write n . print "".
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
defmoduleGeneraldodeffizzbuzz(input)do[num|nwords]=String.split(input)max=String.to_integer(num)dict=Enum.chunk(nwords,2)|>Enum.map(fn[n,word]->{String.to_integer(n),word}end)Enum.each(1..max,fni->str=Enum.map_join(dict,fn{n,word}->ifrem(i,n)==0,do:wordend)IO.putsifstr=="",do:i,else:strend)endendinput="""1053 Fizz5 Buzz7 Baxx"""General.fizzbuzz(input)
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19BuzzFizzBaxx...Buzz101Fizz103104FizzBuzzBaxx
%%% @doc Implementation of General FizzBuzz%%% @see https://rosettacode.org/wiki/General_FizzBuzz-module(general_fizzbuzz).-export([run/2]).-specrun(N::pos_integer(),Factors::list(tuple()))->ok.fizzbuzz(N,[],[])->integer_to_list(N);fizzbuzz(_,[],Result)->lists:flatten(lists:reverse(Result));fizzbuzz(N,Factors,Result)->[{Factor,Output}|FactorsRest]=Factors,NextResult=caseNremFactorof0->[Output|Result];_->Resultend,fizzbuzz(N,FactorsRest,NextResult).run(N,Factors)->lists:foreach(fun(S)->io:format("~s~n",[S])end,[fizzbuzz(X,Factors,[])||X<-lists:seq(1,N)]).
Usage:
$ erl 1> c(general_fizzbuzz). 2> general_fizzbuzz:run(105, [{3, "Fizz"}, {5, "Buzz"}, {7, "Baxx"}]).12Fizz4BuzzFizzBaxx8FizzBuzz...Fizz97BaxxFizzBuzz101Fizz103104FizzBuzzBaxxok
USING:assocscombinators.extrasiokernelmathmath.parsermath.rangesprettyprintsequencessplitting;IN:rosetta-code.general-fizzbuzz:prompt(--str)">"writereadln;:get-factor(--seq)prompt" "splitfirst2[string>number]dip{}2sequence;:get-input(--assocn)promptstring>number[1,b][get-factor]thrice{}3sequenceswap;:fizzbuzz(assocn--)swapdupd[dropswapmod0=]withassoc-filterdupempty?[drop.][nipvaluesconcatprint]if;:main(--)get-input[fizzbuzz]witheach;MAIN:main
>20>3 Fizz>5 Buzz>7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
Uses GForth specific words ']]' and '[['.If your forth does not have them: Sequence ']] A B C .. [[' is equivalent with 'postpone A postpone B postpone C ..'
\ gfb.fs - generalized fizz buzz:times( xt n -- )BEGINdupWHILE1-overswap2>rexecute2r>REPEAT2drop;\ 'Domain Specific Language' compiling words\ -- First comment: stack-effect at compile-time\ -- Second comment: stack efect of compiled sequence:]+[( u ca u -- )( u f -- u f' )2>r>r]]]over[[r>]]literalmod0=IF[[2r>]]sliteraltype1+THEN[[[;:]fb( -- xt )( u f -- u+1 )]]IFspaceELSEdupu.THEN1+;[[;:fb[( -- )( u -- u 0 ;'u' is START-NUMBER ):noname0]]literal[[[;\ Usage: START-NUMBER COMPILING-SEQUENCE U times drop ( INCREASED-NUBER )\ Example:\ 1 fb[ 3 s" fizz" ]+[ 5 s" buzz" ]+[ 7 s" dizz" ]+[ ]fb 40 times drop
gforth gfb.fs --evaluate '1 fb[ ]fb 40 times drop cr bye'1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 gforth gfb.fs --evaluate '1 fb[ 3 s" F" ]+[ 5 s" B" ]+[ 7 s" G" ]+[ ]fb 40 times drop cr bye'1 2 F 4 B F G 8 F B 11 F 13 G FB 16 17 F 19 B FG 22 23 F B 26 F G 29 FB 31 32 F 34 BG F 37 38 F B
' version 01-03-2018' compile with: fbc -s consoleDimAsUIntegerf(),factor,c,i,nDimAsIntegermaxDimAsStringw(),wordDimAsbooleanflagDoInput"Enter maximum number, if number < 1 then the program wil end ",maxIfmax<1ThenExitDoPrintWhilec=0Orc>maxInput"Total number of factors ",cWendc-=1ReDimf(c),w(c)PrintFori=0TocInput"Enter factor and word, separated by a comma ",factor,wordf(i)=factorw(i)=wordNextWhileflag=FALSEflag=TRUEForn=0Toc-1Fori=1TocIff(n)>f(i)Thenflag=FALSESwapf(n),f(i)Swapw(n),w(i)EndIfNextNextWendForn=1Tomaxflag=FALSEFori=0TocIfnModf(i)=0Thenflag=TRUEPrintw(i);EndIfNextPrintIIf(flag,"",Str(n))NextExitDoLoop' empty keyboard bufferWhileInkey<>"":WendPrint:Print"hit any key to end program"SleepEnd
Enter maximum number, if number < 1 then the program wil end 110Total number of factors 3Enter factor and word, separated by a comma 3, FizzEnter factor and word, separated by a comma 5, BuzzEnter factor and word, separated by a comma 7, Baxx12Fizz4BuzzFizzBaxx8...101Fizz103104FizzBuzzBaxx106107Fizz109Buzz
include "NSLog.incl"_mfile = 1begin enum _iNewGame _ _iCloseend enum_mEdit = 2_window = 1begin enum 1 _maxNumLabel _maxNumFld _f1Label _f1Fld _wd1Label _wd1Fld _f2Label _f2Fld _wd2Label _wd2Fld _f3Label _f3Fld _wd3Label _wd3Fld _playBtnend enumvoid local fn BuildMenu menu _mFile,,, @"File" menu _mFile, _iNewGame,, @"New Game" menu _mFile, _iClose,, @"Close", @"w" MenuItemSetAction( _mFile, _iClose, @"performClose:" ) editmenu _mEditend fnvoid local fn BuildWindow window _window, @"General FizzBuzz", (0,0,362,188), NSWindowStyleMaskTitled textlabel _maxNumLabel, @"Maximum number:", (18,150,116,16) textfield _maxNumFld,, @"20", (140,147,202,21) ControlSetFormat( _maxNumFld, @"0123456789", YES, 0, 0 ) textlabel _f1Label, @"Factor 1:", (18,121,58,16) textfield _f1Fld,, @"3", (80,118,54,21) ControlSetFormat( _f1Fld, @"0123456789", YES, 0, 0 ) textlabel _wd1Label, @"Word 1:", (138,121,52,16) textfield _wd1Fld,, @"Fizz", (196,118,146,21) textlabel _f2Label, @"Factor 2:", (18,92,58,16) textfield _f2Fld,, @"5", (80,89,54,21) ControlSetFormat( _f2Fld, @"0123456789", YES, 0, 0 ) textlabel _wd2Label, @"Word 2:", (138,92,52,16) textfield _wd2Fld,, @"Buzz", (196,89,146,21) textlabel _f3Label, @"Factor 3:", (18,63,58,16) textfield _f3Fld,, @"7", (80,60,54,21) ControlSetFormat( _f3Fld, @"0123456789", YES, 0, 0 ) textlabel _wd3Label, @"Word 3:", (138,63,52,16) textfield _wd3Fld,, @"Baxx", (196,60,146,21) button _playBtn,,, @"Play FizzBuzz", (122,13,118,32) WindowMakeFirstResponder( _window, _maxNumFld )end fnvoid local fn PlayFizzBuzz long maxNum = intval(textfield(_maxNumFld)) long f1 = intval(textfield(_f1Fld)) long f2 = intval(textfield(_f2Fld)) long f3 = intval(textfield(_f3Fld)) CFStringRef f1Word = textfield(_wd1Fld) CFStringRef f2Word = textfield(_wd2Fld) CFStringRef f3Word = textfield(_wd3Fld) CFStringRef string = NULL NSLogClear long i for i = 1 to maxNum string = @"" if ( i mod f1 == 0 ) then string = f1Word if ( i mod f2 == 0 ) then string = fn StringByAppendingString( string, f2Word ) if ( i mod f3 == 0 ) then string = fn StringByAppendingString( string, f3Word ) if ( len(string) == 0 ) then string = fn StringWithFormat( @"%ld", i ) NSLog(@"%@",string) nextend fnvoid local fn DoDialog( ev as long, tag as long ) select ( ev ) case _btnClick select ( tag ) case _playBtn : fn PlayFizzBuzz end select end selectend fnfn BuildMenufn BuildWindowon dialog fn DoDialogHandleEvents
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in itswebsite.
Inthis page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
⋈ is the operator for string concatenation
a | b is the divisibility operator, it returns true if a divides b
|x| is the cardinailty operator, when applied to a matrix, it retrieves the number of rows.
Test case
packagemainimport("fmt")constnumbers=3funcmain(){//using the provided datamax:=20words:=map[int]string{3:"Fizz",5:"Buzz",7:"Baxx",}keys:=[]int{3,5,7}divisible:=falsefori:=1;i<=max;i++{for_,n:=rangekeys{ifi%n==0{fmt.Print(words[n])divisible=true}}if!divisible{fmt.Print(i)}fmt.Println()divisible=false}}
deflog=''(1..40).each{Integervalue->log+=(value%3==0)?(value%5==0)?'FIZZBUZZ\n':(value%7==0)?'FIZZBAXX\n':'FIZZ\n':(value%5==0)?(value%7==0)?'BUZBAXX\n':'BUZZ\n':(value%7==0)?'BAXX\n':(value+'\n')}printlnlog
12FIZZ4BUZZFIZZBAXX8FIZZBUZZ11FIZZ13BAXXFIZZBUZZ1617FIZZ19BUZZFIZZBAXX2223FIZZBUZZ26FIZZBAXX29FIZZBUZZ3132FIZZ34BUZBAXXFIZZ3738FIZZBUZZ
or (inspired by normal FizzBuzz in Groovy:https://rosettacode.org/wiki/FizzBuzz#Groovy
deffizzBuzz={i->[[3,'Fizz'],[5,'Buzz'],[7,'Baxx']].collect{i%it[0]?'':it[1]}.join()?:i}1.upto(100){printlnfizzBuzz(it)}
fizz::(Integrala,Showa)=>a->[(a,String)]->Stringfizzaxs|nullresult=showa|otherwise=resultwhereresult=concatMap(fizz'a)xsfizz'a(factor,str)|a`mod`factor==0=str|otherwise=""main=doline<-getLineletn=readlinecontents<-getContentsletmultiples=map(convert.words)$linescontentsmapM_(\x->putStrLn$fizzxmultiples)[1..n]whereconvert[x,y]=(readx,y)
Or, as a function which takes a list of rules as an argument:
typeRule=(Int,String)----------------- FIZZETC (USING RULE SET) ---------------fizzEtc::[(Int,String)]->[String]fizzEtcrules=foldrnextLine[][1..]wherenextLinexa|nullnoise=showx:a|otherwise=noise:awherenoise=foldlreWrite[]rulesreWrites(m,k)|0==remxm=s<>k|otherwise=s------------------- TEST OF SAMPLE RULES -----------------fizzTest::[String]fizzTest=fizzEtc[(3,"Fizz"),(5,"Buzz"),(7,"Baxx")]main::IO()main=mapM_putStrLn$take20fizzTest
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
The following is Unicon specific because of the use of list comprehension. It can easily be translated into Icon.
linkfactorsproceduremain(A)/A:=[20,3,"Fizz",5,"Buzz",7,"Baxx"]mtable:=table()limit:=get(A)while*A>0domtable[integer(get(A))]:=get(A)mlist:=sort([:key(mtable):])everyi:=1tolimitdowrite((""~==fizzbuzz(i,mlist,mtable))|i)endprocedurefizzbuzz(n,a,t)every(s:="",n%(f:=!a)=0)dos||:=t[f]returnsend
Sample runs:
->fizzbuzz12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz->
>fizzbuzz 8 7 Fizz 3 Buzz 2 Blax 9 Bart 4 Flax1BlaxBuzzBlaxFlax5BlaxBuzzFizzBlaxFlax->
The trick here involves looking for where the factors evenly divide the counting numbers. Where no factor is relevant we use the counting number, an in the remaining cases we use the string which corresponds to the factor:
genfb=:1 :0:b=.*x|/1+i.y>,&":&.>/(m#inv"_1~-.b),(*/b)#&.>1+i.y)
Example use:
357('Fizz';'Buzz';'Baxx')genfb2012Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
For our example, b looks like this:
110110110110110110111111011110111101111011111101111110111111
*/b gives us 1s where we want numbers and 0s where we want to plug in the strings:
*/*357|/1+i.2011010001001010011010
m is our strings, and #inv expands values out to match a selection. So, in our example,m#inv"_1~-.b looks like this:
┌┬┬────┬┬────┬────┬────┬┬────┬────┬┬────┬┬────┬────┬┬┬────┬┬────┐│││Fizz│││Fizz│││Fizz│││Fizz│││Fizz│││Fizz│││├┼┼────┼┼────┼────┼────┼┼────┼────┼┼────┼┼────┼────┼┼┼────┼┼────┤│││││Buzz│││││Buzz│││││Buzz│││││Buzz│├┼┼────┼┼────┼────┼────┼┼────┼────┼┼────┼┼────┼────┼┼┼────┼┼────┤│││││││Baxx│││││││Baxx│││││││└┴┴────┴┴────┴────┴────┴┴────┴────┴┴────┴┴────┴────┴┴┴────┴┴────┘
All that remains is to assemble these pieces into the final result...
publicclassFizzBuzz{publicstaticvoidmain(String[]args){Sound[]sounds={newSound(3,"Fizz"),newSound(5,"Buzz"),newSound(7,"Baxx")};for(inti=1;i<=20;i++){StringBuildersb=newStringBuilder();for(Soundsound:sounds){sb.append(sound.generate(i));}System.out.println(sb.length()==0?i:sb.toString());}}privatestaticclassSound{privatefinalinttrigger;privatefinalStringonomatopoeia;publicSound(inttrigger,Stringonomatopoeia){this.trigger=trigger;this.onomatopoeia=onomatopoeia;}publicStringgenerate(inti){returni%trigger==0?onomatopoeia:"";}}}
For a more complete example seejFizzBuzz
Or using a lot of Lambdas ...
importjava.util.stream.*;importjava.util.function.*;importjava.util.*;publicclassfizzbuzz_general{/** * To run: java fizzbuzz_general.java 3=Fizz 5=Buzz 7=Baxx 100 * */publicstaticvoidmain(String[]args){Function<String[],Function<Integer,String>>make_cycle_function=parts->j->j%(Integer.parseInt(parts[0]))==0?parts[1]:"";List<Function<Integer,String>>cycle_functions=Stream.of(args).map(arg->arg.split("=")).filter(parts->parts.length==2).map(make_cycle_function::apply).collect(Collectors.toList());Function<Integer,String>moduloTesters=i->cycle_functions.stream().map(fcn->fcn.apply(i)).collect(Collectors.joining());BiFunction<Integer,String,String>formatter=(i,printThis)->"".equals(printThis)?Integer.toString(i):printThis;Function<Integer,String>fizzBuzz=i->formatter.apply(i,moduloTesters.apply(i));IntStream.rangeClosed(0,Integer.parseInt(args[args.length-1])).mapToObj(Integer::valueOf).map(fizzBuzz::apply).forEach(System.out::println);}}
In a functional style of JavaScript, with two nestedreduce folds – one through the integer series,and one through the series of rules.
First as compacted by Google's Closure compiler:
functionfizz(d,e){returnfunctionb(a){returna?b(a-1).concat(a):[];}(e).reduce(function(b,a){returnb+(d.reduce(function(b,c){returnb+(a%c[0]?"":c[1]);},"")||a.toString())+"\n";},"");}
and then in the original expanded form, for better legibility:
functionfizz(lstRules,lngMax){return(functionrng(i){returni?rng(i-1).concat(i):[]})(lngMax).reduce(function(strSeries,n){// The next member of the series of lines:// a word string or a number stringreturnstrSeries+(lstRules.reduce(function(str,tplNumWord){returnstr+(n%tplNumWord[0]?'':tplNumWord[1])},'')||n.toString())+'\n';},'');}fizz([[3,'Fizz'],[5,'Buzz'],[7,'Baxx']],20);
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
// range :: Int -> Int -> [Int]constrange=(min,max)=>Array.from({length:max-min},(_,i)=>min+i)constdefaultRules=Object.freeze([[3,'Fizz'],[5,'Buzz'],[7,'Baxx'],])// fizzBuzz :: Int -> [[Int, String]] -> StringconstfizzBuzz=(max,rules=defaultRules)=>range(1,max+1).map(n=>rules.reduce((words,[factor,word])=>words+(n%factor?'':word),'')||n).join('\n')console.log(fizzBuzz(20))
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
For simplicity, assume that the user will enter valid input.
functionfizzbuzz(triggers::Vector{Tuple{Int,ASCIIString}},upper::Int)fori=1:uppertriggered=falsefortriggerintriggersifi%trigger[1]==0triggered=trueprint(trigger[2])endend!triggered&&print(i)println()endendprint("Enter upper limit:\n> ")upper=parse(Int,readline())triggers=Tuple{Int,ASCIIString}[]print("Enter factor/string pairs (space delimited; ^D when done):\n> ")while(r=readline())!=""input=split(r)push!(triggers,(parse(Int,input[1]),input[2]))print("> ")endprintln("EOF\n")fizzbuzz(triggers,upper)
Enter upper limit:> 20Enter factor/string pairs (space delimited; ^D when done):> 3 Fizz> 5 Buzz> 7 Baxx> EOF12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
funmain(args:Array<String>){//Read the maximum number, set to 0 if it couldn't be readvalmax=readLine()?.toInt()?:0valwords=mutableMapOf<Int,String>()//Read input three times for a factor and a word(1..3).forEach{readLine()?.let{valtokens=it.split(' ')words.put(tokens[0].toInt(),tokens[1])}}//Sort the words so they will be output in arithmetic ordervalsortedWords=words.toSortedMap()//Find the words with matching factors and print them, print the number if no factors matchfor(iin1..max){valwordsToPrint=sortedWords.filter{i%it.key==0}.map{it.value}if(wordsToPrint.isNotEmpty()){wordsToPrint.forEach{print(it)}println()}elseprintln(i)}}
function generalisedFizzBuzz m, f1, f2, f3 put f1 & cr & f2 & cr & f3 into factors sort factors ascending numeric repeat with i = 1 to m put false into flag if i mod (word 1 of line 1 of factors) = 0 then put word 2 of line 1 of factors after fizzbuzz put true into flag end if if i mod (word 1 of line 2 of factors) = 0 then put word 2 of line 2 of factors after fizzbuzz put true into flag end if if i mod (word 1 of line 3 of factors) = 0 then put word 2 of line 3 of factors after fizzbuzz put true into flag end if if flag is false then put i after fizzbuzz put cr after fizzbuzz end repeat return fizzbuzzend generalisedFizzBuzz
Example
put generalisedFizzBuzz(20,"7 baxx","3 fizz","5 buzz")
functiongenFizz(param)localresponseprint("\n")forn=1,param.limitdoresponse=""fori=1,3doifn%param.factor[i]==0thenresponse=response..param.word[i]endendifresponse==""thenprint(n)elseprint(response)endendendlocalparam={factor={},word={}}param.limit=io.read()fori=1,3doparam.factor[i],param.word[i]=io.read("*number","*line")endgenFizz(param)
localfunctionfizzbuzz(n,mods)localres={}fori=1,#mods,2dolocalmod,name=mods[i],mods[i+1]fori=mod,n,moddores[i]=(res[i]or'')..nameendendfori=1,ndores[i]=res[i]oriendreturntable.concat(res,'\n')enddolocaln=tonumber(io.read())-- number of lines, eg. 100localmods={}localn_mods=0whilen_mods~=3do-- for reading until EOF, change 3 to -1localline=io.read()ifnotlinethenbreakendlocals,e=line:find(' ')localnum=tonumber(line:sub(1,s-1))localname=line:sub(e+1)mods[#mods+1]=nummods[#mods+1]=namen_mods=n_mods+1endprint(fizzbuzz(n,mods))end
> mods = {>> 3, 'cheese ',>> 2, 'broccoli ',>> 3, 'sauce ',>> }> fizzbuzz(8, mods)1broccoli cheese sauce broccoli 5cheese broccoli sauce 7broccoli#!/usr/bin/env luajitlocalnum=arg[1]ortonumber(arg[1])or110localt={{3,"Fizz"},{5,"Buzz"},{7,"Gazz"},}-- `cnt` contains counters for each factor-word pair; when a counter of a pair reaches its factor,-- the counter is reset to zero and the word is written to outputlocalcnt=setmetatable({},{__index=function()return0end})fori=1,numdofori=1,#tdocnt[i]=cnt[i]+1endlocalmatch=falsefori=1,#tdoifcnt[i]==t[i][1]thenio.write(t[i][2])cnt[i]=0match=trueendendifnotmatchthenio.write(i)endio.write(", ")end
> ./fizzbuzz_gen.lua 1, 2, Fizz, 4, Buzz, Fizz, Gazz, 8, Fizz, Buzz, 11, Fizz, 13, Gazz, FizzBuzz, 16, 17, Fizz, 19, Buzz, FizzGazz, 22, 23, Fizz, Buzz, 26, Fizz, Gazz, 29, FizzBuzz, 31, 32, Fizz, 34, BuzzGazz, Fizz, 37, 38, Fizz, Buzz, 41, FizzGazz, 43, 44, FizzBuzz, 46, 47, Fizz, Gazz, Buzz, Fizz, 52, 53, Fizz, Buzz, Gazz, Fizz, 58, 59, FizzBuzz, 61, 62, FizzGazz, 64, Buzz, Fizz, 67, 68, Fizz, BuzzGazz, 71, Fizz, 73, 74, FizzBuzz, 76, Gazz, Fizz, 79, Buzz, Fizz, 82, 83, FizzGazz, Buzz, 86, Fizz, 88, 89, FizzBuzz, Gazz, 92, Fizz, 94, Buzz, Fizz, 97, Gazz, Fizz, Buzz, 101, Fizz, 103, 104, FizzBuzzGazz, 106, 107, Fizz, 109, Buzz,
findNum:=proc(str)#help parse inputlocali;i:=1:while(true)doif(StringTools:-IsAlpha(str[i]))thenreturni-2:endif:i:=i+1:enddo:endproc:path:="input.txt";input:=readline(path):T:=table():maxnum:=parse(input):while(true)doinput:=readline(path):ifinput=0thenbreak;endif:pos:=findNum(input):num:=parse(input[..pos]):T[num]:=input[pos+2..]:enddo:forifrom1tomaxnumdofactored:=false:forjin[indices(T)]doifimodj[1]=0thenfactored:=true:printf(T[j[1]]);endif:enddo:if(notfactored)thenprintf("%d",i):endif:printf("\n");enddo:
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
list={{5,"Buzz"},{3,"Fizz"},{7,"Baxx"}};runTo=(*LCM@@list[[All,1]]+1*)20;Column@Table[Select[list,Mod[x,#[[1]]]==0&][[All,2]]/.{}->{x},{x,1,runTo}]
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
srep(n,s):=block(l:charlist(s),lrep:map(lambda([c],smake(n,c)),l),apply(sconcat,lrep))$srep_zip(nums,strings):=block(len:min(length(nums),length(strings)),makelist(srep(nums[i],strings[i]),i,1,len))$genfizzbuzz(factors,words,n1,n2):=forifromn1thrun2do(flags:map(lambda([k],charfun(mod(i,k)=0)),factors),ifmember(1,flags)thensprint(apply(sconcat,srep_zip(flags,words)))elsesprint(i),ifmod(i-n1+1,10)=0thennewline())$genfizzbuzz([3,5,7],["Fizz","Buzz","Baxx"],1,105);
1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz FizzBaxx 22 23 Fizz Buzz 26 Fizz Baxx 29 FizzBuzz 31 32 Fizz 34 BuzzBaxx Fizz 37 38 Fizz Buzz 41 FizzBaxx 43 44 FizzBuzz 46 47 Fizz Baxx Buzz Fizz 52 53 Fizz Buzz Baxx Fizz 58 59 FizzBuzz 61 62 FizzBaxx 64 Buzz Fizz 67 68 Fizz BuzzBaxx 71 Fizz 73 74 FizzBuzz 76 Baxx Fizz 79 Buzz Fizz 82 83 FizzBaxx Buzz 86 Fizz 88 89 FizzBuzz Baxx 92 Fizz 94 Buzz Fizz 97 Baxx Fizz Buzz 101 Fizz 103 104 FizzBuzzBaxx done
This implementation improves slightly over the proposed task, making the prompts a little friendlier.
factorWords={}maxNr=val(input("Max number? "))whiletruefactorInput=input("Factor? ")iffactorInput==""thenbreak// Split inputparts=factorInput.split(" ")factor=val(parts[0])word=parts[1]// Assign factor/wordfactorWords[factor]=wordendwhilefornrinrange(1,maxNr)matchingWords=""forfactorinfactorWords.indexesifnr%factor==0thenmatchingWords=matchingWords+factorWords[factor]endifendforifmatchingWordsthenprintmatchingWordselseprintnrendfor
Sample session:
Max number? 20Factor? 3 FizzFactor? 5 BuzzFactor?12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz1617Fizz19Buzz
MODULEGeneralFizzBuzz;FROMConversionsIMPORTStrToInt;FROMFormatStringIMPORTFormatString;FROMTerminalIMPORTWrite,WriteString,WriteLn,ReadChar;TYPEWord=ARRAY[0..63]OFCHAR;PROCEDUREWriteInt(i:INTEGER);VARbuf:Word;BEGINFormatString("%i",buf,i);WriteString(buf);ENDWriteInt;PROCEDUREReadInt():INTEGER;VARbuf:ARRAY[0..9]OFCHAR;c:CHAR;i:INTEGER;BEGINi:=0;LOOPc:=ReadChar();IF(c=0C)OR(i>9)THENBREAKELSIF(c=012C)OR(c=015C)THENWriteLn;buf[i]:=0C;BREAKELSIF(c<'0')OR(c>'9')THENWrite(c);buf[i]:=0C;BREAKELSEWrite(c);buf[i]:=c;INC(i)ENDEND;StrToInt(buf,i);RETURNiENDReadInt;PROCEDUREReadLine():Word;VARbuf:Word;i:INTEGER;c:CHAR;BEGINi:=0;WHILEi<HIGH(buf)DOc:=ReadChar();IF(c=0C)OR(c=012C)OR(c=015C)THENWriteLn;buf[i]:=0C;BREAKELSEWrite(c);buf[i]:=c;INC(i)ENDEND;RETURNbuf;ENDReadLine;VARi,max:INTEGER;fa,fb,fc:INTEGER;wa,wb,wc:Word;done:BOOLEAN;BEGINmax:=ReadInt();fa:=ReadInt();wa:=ReadLine();fb:=ReadInt();wb:=ReadLine();fc:=ReadInt();wc:=ReadLine();FORi:=1TOmaxDOdone:=FALSE;IFiMODfa=0THENdone:=TRUE;WriteString(wa);END;IFiMODfb=0THENdone:=TRUE;WriteString(wb);END;IFiMODfc=0THENdone:=TRUE;WriteString(wc);END;IFNOTdoneTHENWriteInt(i)END;WriteLn;END;ReadCharENDGeneralFizzBuzz.
factors = {}words = {}// get the max numberprint ">"max = int(input())// get the factorsinp = " "while inp != ""print ">"inp = input()if " " in inpfactors.append(int(split(inp, " ")[0]))words.append(split(inp, " ")[1])endend// output all the numbersfor i in range(1, max)foundfactor = falsefor j in range(0, len(factors) - 1)if (i % factors[j]) = 0foundfactor = trueprint words[j]endendj = 0if !foundfactorprint iendprintlnend>20>3 Fizz>5 Buzz>7 Baxx>12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
This solution has no input validation
importparseutils,strutils,algorithmtypeFactorAndWord=tuple[factor:int,word:string]varnumber:intvarfactorAndWords:array[3,FactorAndWord]#custom comparison proc for the FactorAndWord typeproccustomCmp(x,y:FactorAndWord):int=ifx.factor<y.factor:-1elifx.factor>y.factor:1else:0echo"Enter max number:"varinput=readLine(stdin)discardparseInt(input,number)foriin0..2:echo"Enter a number and word separated by space:"varinput=readLine(stdin)vartokens=input.splitdiscardparseInt(tokens[0],factorAndWords[i].factor)factorAndWords[i].word=tokens[1]#sort factors in ascending ordersort(factorAndWords,customCmp)#implement fiz buzforiin1..number:varwritten=false;foriteminitems(factorAndWords):ifimoditem.factor==0:write(stdout,item.word)written=trueifwritten:write(stdout,"\n")else:writeLine(stdout,i)
Original version byUser:Vanyamil
(* Task : General_FizzBuzz *)(*The FizzBuzz problem, butgeneralized to have any strings, at any steps,up to any number of iterations.*)letgen_fizz_buzz(n:int)(l:(int*string)list):unit=letfold_fi(acc:bool)(k,s)=ifimodk=0then(print_strings;true)elseaccinletrechelperi=ifi>nthen()elseletany_printed=List.fold_left(fold_fi)falselinbegin(ifnotany_printedthenprint_inti);print_newline();helper(succi)endinhelper1;;(*** Output ***)gen_fizz_buzz20[(3,"Fizz");(5,"Buzz");(7,"Baxx")];;
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
This version uses a variadic argument to allow more or less than 3 factors. It could be easily modified for earlier versions, either by taking a vector rather than bare arguments (making the callfizz(20,[[3,"Fizz"],[5,"Buzz"],[7,"Baxx"]])) or to support exactly factors (keeping the call the same).
fizz(n,v[..])={v=vecsort(v,1);for(k=1,n,my(t);for(i=1,#v,if(k%v[i][1]==0,print1(v[i][2]);t=1));print(if(t,"",k)));}fizz(20,[3,"Fizz"],[5,"Buzz"],[7,"Baxx"])12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
##forvari:=1to20dobeginvars:='';ifimod3=0thens+='Fizz';ifimod5=0thens+='Buzz';ifimod7=0thens+='Baxx';ifs=''thenPrintln(i)elsePrintln(s);end
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
#!bin/usr/perluse5.020;usestrict;usewarnings;#Get a max number from the usersay("Please enter the maximum possible multiple. ");my$max=<STDIN>;#Get the factors from the usermy@factors=();my$buffer;say("Now enter the first factor and its associated word. Ex: 3 Fizz ");chomp($buffer=<STDIN>);push@factors,$buffer;say("Now enter the second factor and its associated word. Ex: 5 Buzz ");chomp($buffer=<STDIN>);push@factors,$buffer;say("Now enter the third factor and its associated word. Ex: 7 Baxx ");chomp($buffer=<STDIN>);push@factors,$buffer;#Counting from 1 to maxfor(my$i=1;$i<=$max;$i++){#Create a secondary buffer as well as set the original buffer to the current indexmy$oBuffer;$buffer=$i;#Run through each element in our arrayforeachmy$element(@factors){#Look for white space$element=~ /\s/;#If the int is a factor of max, append it to oBuffer as a string to be printedif($i%substr($element,0,@-)==0){$oBuffer=$oBuffer.substr($element,@++1,length($element));#This is essentially setting a flag saying that at least one element is a factor$buffer="";}}#If there are any factors for that number, print their words. If not, print the number.if(length($buffer)>0){print($buffer."\n");}else{print($oBuffer."\n");}}
Please enter the maximum possible multiple. 20Now enter the first factor and its associated word. Ex: 3 Fizz 3 FizzNow enter the second factor and its associated word. Ex: 5 Buzz 5 BuzzNow enter the third factor and its associated word. Ex: 7 Baxx 7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
withjavascript_semanticsproceduregeneral_fizz_buzz(integerlim,sequencewords,facts)fori=1tolimdostringword=""forj,finfactsdoifremainder(i,f)=0thenword&=words[j]endifendforiflength(word)=0thenword=sprintf("%d",i)endifprintf(1,"%s\n",{word})endforendproceduregeneral_fizz_buzz(20,{"Fizz","Buzz","Baxx"},{3,5,7})
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
<?php$max=20;$factor=array(3=>'Fizz',5=>'Buzz',7=>'Jazz');for($i=1;$i<=$max;$i++){$matched=false;foreach($factorAS$number=>$word){if($i%$number==0){echo$word;$matched=true;}}echo($matched?'':$i),PHP_EOL;}?>
12Fizz4BuzzFizzJazz8FizzBuzz11Fizz13JazzFizzBuzz1617Fizz19Buzz
interactive => print("> "), MaxNum = read_int(), Map = new_map(), print("> "), while (Line = read_line(), Line != "") [N,V] = split(Line), Map.put(N.to_int,V), print("> ") end, general_fizzbuzz(MaxNum,Map.to_list.sort), nl.general_fizzbuzz(N,L) => FB = [I.to_string : I in 1..N], foreach(I in 1..N) Vs = [V : K=V in L, I mod K == 0].join(''), if Vs != "" then FB[I] := Vs end end, println([F : F in FB].join(" ")).Testing:
$ echo "106\n3 Fizz\n5 Buzz\n7 Bazz\n" | picat -g interactive general_fizzbuzz.pi
Here's an interactive session:
> 106> 3 Fizz> 5 Buzz> 7 Baxx> 12Fizz4BuzzFizzBazz8FizzBuzz11Fizz13BazzFizzBuzz1617Fizz19BuzzFizzBazz22...BazzFizzBuzz101Fizz103104FizzBuzzBazz106
(de general (N Lst) (for A N (prinl (or (extract '((L) (and (=0 (% A (car L))) (cdr L)) ) Lst ) A ) ) ) )(general 20 '((3 . Fizz) (5 . Buzz) (7 . Baxx)))
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
require"io2"localn=io.readInt("Maximum number : ",3)localfactors={}localwords={}fori=1,3dowhiletruedolocalfactor=io.readInt($"Factor {i} : ",2)iffactorinfactorsthenprint("Must be an unused integer > 1, try again.")elsefactors:insert(factor)localword=io.readStr($" Word {i} : ",1)words[factor]=wordbreakendendendfactors:sort()print()fori=1,ndolocals=""forj=1,3dolocalfactor=factors[j]ifi%factor==0thens..=words[factor]endendifs==""thens=tostring(i)endprint(s)end
Sample run:
Maximum number : 20Factor 1 : 3 Word 1 : FizzFactor 2 : 5 Word 2 : BuzzFactor 3 : 7 Word 3 : Bazz12Fizz4BuzzFizzBazz8FizzBuzz11Fizz13BazzFizzBuzz1617Fizz19Buzz
$limit=20$data=@("3 Fizz","5 Buzz","7 Baxx")#An array with whitespace as the delimiter#Between the factor and the wordfor($i=1;$i-le$limit;$i++){$outP=""foreach($xin$data){$data_split=$x-split" "#Split the "<factor> <word>"if(($i%$data_split[0])-eq0){$outP+=$data_split[1]#Append the <word> to outP}}if(!$outP){#Is outP equal to NUL?Write-HoSt$i}else{Write-HoSt$outP}}
PS> ./GENFB12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19BuzzPS>
Assuming the user specifies as input two facts of the form:
maxNumber(105).factors([(3,"Fizz"),(5,"Buzz"),(7,"Baxx")]).
A simple Prolog solution to the generalised FizzBuzz problem is as follows:
go:-maxNumber(M),factors(Fs),MLastisM+1,loop(1,MLast,Fs).loop(B,B,_).loop(A,B,Fs):-A<B,fizzbuzz(A,Fs,S),((S="",ResisA);Res=S),writeln(Res),NextisA+1,loop(Next,B,Fs).fizzbuzz(_,[],"").fizzbuzz(N,[(F,S)|Fs],Res):-fizzbuzz(N,Fs,OldRes),(NmodF=:=0,string_concat(S,OldRes,Res);Res=OldRes).
The program can be launched by querying the predicate
?-go.
It is worth noting that
factors([(3,"Fizz"),(5,"Buzz")]).
corresponds to basic FizzBuzz and that the proposed solution can handle an arbitrary number of factors.
defgenfizzbuzz(factorwords,numbers):# sort entries by factorfactorwords.sort(key=lambdafactor_and_word:factor_and_word[0])lines=[]fornuminnumbers:words=''.join(wordforfactor,wordinfactorwordsif(num%factor)==0)lines.append(wordsifwordselsestr(num))return'\n'.join(lines)if__name__=='__main__':print(genfizzbuzz([(5,'Buzz'),(3,'Fizz'),(7,'Baxx')],range(1,21)))
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
n=20mappings={3:"Fizz",5:"Buzz",7:"Baxx"}foriinrange(1,n+1):print(''.join(word*(i%key==0)forkey,wordinmappings.items())ori)
fromcollectionsimportdefaultdictN=100FACTOR_TO_WORD={3:"Fizz",5:"Buzz",}deffizzbuzz(n=N,factor_to_word=FACTOR_TO_WORD):factors=defaultdict(list)forfactorinfactor_to_word:factors[factor].append(factor)foriinrange(1,n+1):res=''forfactorinsorted(factors.pop(i,())):factors[i+factor].append(factor)res+=factor_to_word[factor]yieldresoriif__name__=='__main__':n=int(input('Enter number: '))mods={int(k):vfork,vin(input('Enter "<factor> <word>" (without quotes): ').split(maxsplit=1)for_inrange(3))}forlineinfizzbuzz(n,mods):print(line)
This variant uses ranges with step 3, 5, etc. Preserves order and duplicate moduli.
fromcollectionsimportdefaultdictn=100mods=[(3,'Fizz'),(5,'Buzz'),]deffizzbuzz(n=n,mods=mods):res=defaultdict(str)fornum,nameinmods:foriinrange(num,n+1,num):res[i]+=namereturn'\n'.join(res[i]orstr(i)foriinrange(1,n+1))if__name__=='__main__':n=int(input())mods=[]whilelen(mods)!=3:# for reading until EOF change 3 to -1try:line=input()exceptEOFError:breakidx=line.find(' ')# preserves whitespacenum,name=int(line[:idx]),line[idx+1:]# after the first spacemods.append((num,name))# preserves order and duplicate moduliprint(fizzbuzz(n,mods))
>>> mods = [... (4, 'Four '),... (6, 'six '),... (2, 'Two '),... (8, 'eight... '),... (6, 'HA! SIX!'),... ]>>> print(fizzbuzz(16, mods))1Two 3Four Two 5six Two HA! SIX!7Four Two eight... 9Two 11Four six Two HA! SIX!13Two 15Four Two eight...
[ sortwith [ dip [ 1 peek ] 1 peek > ] $ "" swap rot times [ i^ 1+ over $ "" unrot witheach [ dip dup do dip swap mod iff drop else [ rot swap join swap ] ] over $ "" = iff [ number$ join ] else drop rot swap join space join swap ] drop -1 split drop ] is generalfizzbuzz ( n [ --> $ ) 105 ' [ [ $ "fizz" 3 ] [ $ "baxx" 7 ] [ $ "buzz" 5 ] ] generalfizzbuzz nest$ 60 wrap$ cr
1 2 fizz 4 buzz fizz baxx 8 fizz buzz 11 fizz 13 baxxfizzbuzz 16 17 fizz 19 buzz fizzbaxx 22 23 fizz buzz 26 fizzbaxx 29 fizzbuzz 31 32 fizz 34 buzzbaxx fizz 37 38 fizz buzz41 fizzbaxx 43 44 fizzbuzz 46 47 fizz baxx buzz fizz 52 53fizz buzz baxx fizz 58 59 fizzbuzz 61 62 fizzbaxx 64 buzzfizz 67 68 fizz buzzbaxx 71 fizz 73 74 fizzbuzz 76 baxx fizz79 buzz fizz 82 83 fizzbaxx buzz 86 fizz 88 89 fizzbuzz baxx92 fizz 94 buzz fizz 97 baxx fizz buzz 101 fizz 103 104fizzbuzzbaxx
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.
genFizzBuzz<-function(n,...){args<-list(...)#R doesn't like vectors of mixed types, so c(3, "Fizz") is coerced to c("3", "Fizz"). We must undo this.#Treating "[[" as if it is a function is a bit of R's magic. You can treat it like a function because it actually is one.factors<-as.integer(sapply(args,"[[",1))words<-sapply(args,"[[",2)sortedPermutation<-sort.list(factors)#Required by the task: We must go from least factor to greatest.factors<-factors[sortedPermutation]words<-words[sortedPermutation]for(iin1:n){isFactor<-i%%factors==0print(if(any(isFactor))paste0(words[isFactor],collapse="")elsei)}}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"))
If we deviate from the task's example of how to input parameters and instead use R's names facilities to make our (number, name) pairs, we get a much cleaner solution.
namedGenFizzBuzz<-function(n,namedNums){factors<-sort(namedNums)#Required by the task: We must go from least factor to greatest.for(iin1:n){isFactor<-i%%factors==0print(if(any(isFactor))paste0(names(factors)[isFactor],collapse="")elsei)}}namedNums<-c(Fizz=3,Buzz=5,Baxx=7)#Notice that we can name our inputs without a function call.namedGenFizzBuzz(105,namedNums)shuffledNamedNums<-c(Buzz=5,Prax=9,Fizz=3,Baxx=7)namedGenFizzBuzz(105,shuffledNamedNums)
#langracket/base(define(get-matchesnumfactors/words)(for*/list([factor/word(in-listfactors/words)][factor(in-value(carfactor/word))][word(in-value(cadrfactor/word))]#:when(zero?(remaindernumfactor)))word))(define(gen-fizzbuzzfromtofactors/words)(for([num(in-rangefromto)])(definematches(get-matchesnumfactors/words))(displayln(if(null?matches)(number->stringnum)(applystring-appendmatches)))))(gen-fizzbuzz121'((3"Fizz")(5"Buzz")(7"Baxx")))
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
#langracket(requireracket/match)(define(fizz-buzz-individualx.args)(match(string-append*(map(lambda(i)(matchi[(consab)(if(=0(moduloxa))b"")]))args))[""x][fizz-buzz-stringfizz-buzz-string]))(define(fizz-buzzx.args)(map(curryr(composedisplayln(curryapplyfizz-buzz-individual))args)(range1(add1x)))(void))(fizz-buzz20'(3."Fizz")'(5."Buzz")'(7."Baxx"))
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
(formerly Perl 6)
# General case implementation of a "FizzBuzz" class.# Defaults to standard FizzBuzz unless a new schema is passed in.classFizzBuzz {has$.schemaisrw = <3Fizz5Buzz >.hash;methodfilter (Int$this) {my$fb;for$.schema.sort: { +.key } ->$p {$fb ~=$this %% +$p.key ??$p.value !!''};return$fb ||$this; }}# Sub implementing the specific requirements of the task.subGeneralFizzBuzz (Int$upto,@schema?) {my$ping =FizzBuzz.new;$ping.schema =@schema.hashif@schema;map {$ping.filter:$_ },1 ..$upto;}# The tasksay'Using: 20 ' ~<3 Fizz 5 Buzz 7 Baxx>;.sayforGeneralFizzBuzz(20,<3 Fizz 5 Buzz 7 Baxx>);say'';# And for funsay'Using: 21 ' ~<2 Pip 4 Squack 5 Pocketa 7 Queep>;sayjoin', ',GeneralFizzBuzz(21,<2 Pip 4 Squack 5 Pocketa 7 Queep>);
Using: 20 3 Fizz 5 Buzz 7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19BuzzUsing: 21 2 Pip 4 Squack 5 Pocketa 7 Queep1, Pip, 3, PipSquack, Pocketa, Pip, Queep, PipSquack, 9, PipPocketa, 11, PipSquack, 13, PipQueep, Pocketa, PipSquack, 17, Pip, 19, PipSquackPocketa, Queep
Here's the same program in a more functional idiom:
subgenfizzbuzz($n, +@fb) { [Z~](dofor@fb ||<3 fizz 5 buzz> ->$i,$s {flat (''xx$i-1,$s)xx *; } )Z||1..$n}.sayforgenfizzbuzz(20,<3 Fizz 5 Buzz 7 Baxx>);
Following Red code is fully compatible with Rebol.
Red["FizzBuzz"]nmax:to-integerask"Max number: "while[""<>trimrule:ask"New rule (empty to end): "][appendrules:[]loadrule]repeatnnmax[res:copy""foreach[xblah]rules[ifn%x=0[appendresblah]]printeitherempty?res[n][res]]halt
Max number: 21New rule (empty to end): 3 FizzNew rule (empty to end): 5 BuzzNew rule (empty to end): 7 BaxxNew rule (empty to end): 12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19BuzzFizzBaxx(halted)
$ENTRY Go { , <Numb <Card>>: s.Max , <ReadFactors>: e.Factors , <Iota 1 s.Max>: e.Nums = <Each Fizz (e.Factors) e.Nums>;}; Fizz { s.I e.Facs, <Each Fac (s.I) e.Facs>: { = <Prout <Symb s.I>>; e.X = <Prout e.X>; };}Fac { (s.Fac e.FacWord) s.I, <Mod s.I s.Fac>: { 0 = e.FacWord; s.X = ; };};ReadFactors { , <Card>: { 0 = ; = ; e.Line = (<Line e.Line>) <ReadFactors>; };};Line { e.X, <Split ' ' e.X>: (e.Num) e.Word = <Numb e.Num> <Trim ' ' e.Word>;}; Split { s.C e.X s.C e.Y = (e.X) e.Y; s.C e.X = (e.X);};Trim { s.C = ; s.C s.C e.X = <Trim s.C e.X>; s.C e.X s.C = <Trim s.C e.X>; s.C s.I e.X = s.I <Trim s.C e.X>;};Iota { s.End s.End = s.End; s.Start s.End = s.Start <Iota <+ 1 s.Start> s.End>;};Each { s.F (e.Arg) = ; s.F (e.Arg) t.I e.X = <Mu s.F t.I e.Arg> <Each s.F (e.Arg) e.X>;};20
3 Fizz
5 Buzz
7 Baxx
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
/*REXX program shows a generalized FizzBuzz program: #1 name1 #2 name2 ··· */parseargh$/*obtain optional arguments from the CL*/ifh=''|h=","thenh=20/*Not specified? Then use the default.*/if$=''|$=","then$="3 Fizz 5 Buzz 7 Baxx"/* " " " " " " */factors=words($)%2/*determine number of factors to use. */doi=1by2forfactors/*parse the number factors to be used. */#.i=word($,i);@.i=word($,i+1)/*obtain the factor and its "name". */end/*i*/doj=1forh;z=/*traipse through the numbers to H. */dok=1by2forfactors/* " " " factors in J. */ifj//#.k==0thenz=z||@.k/*Is it a factor? Then append it to Z.*/end/*k*//* [↑] Note: the factors may be zero.*/sayword(zj,1)/*display the number or its factors. */end/*j*//*stick a fork in it, we're all done. */
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
/*REXX program shows a generalized FizzBuzz program: #1 name1 #2 name2 ··· */parseargh$/*obtain optional arguments from the CL*/ifh=''|h=","thenh=20/*Not specified? Then use the default.*/if$=''|$=","then$="3 Fizz 5 Buzz 7 Baxx"/* " " " " " " */doj=1forh;z=/*traipse through the numbers to H. */dok=1by2forwords($)%2/* " " " factors in J. */ifj//word($,k)==0thenz=z||word($,k+1)/*Is it a factor? Then append it to Z.*/end/*k*//* [↑] Note: the factors may be zero.*/sayword(Zj,1)/*display the number or its factors. */end/*j*//*stick a fork in it, we're all done. */
limit = 20for n = 1 to limit if n % 3 = 0 see "" + n + " = " + "Fizz"+ nl but n % 5 = 0 see "" + n + " = " + "Buzz" + nl but n % 7 = 0 see "" + n + " = " + "Baxx" + nl else see "" + n + " = " + n + nl oknext
defgeneral_fizzbuzz(text)num,*nword=text.splitnum=num.to_idict=nword.each_slice(2).map{|n,word|[n.to_i,word]}(1..num).eachdo|i|str=dict.map{|n,word|wordifi%n==0}.joinputsstr.empty??i:strendendtext=<<EOS203 Fizz5 Buzz7 BaxxEOSgeneral_fizzbuzz(text)
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
usestd::io;usestd::io::BufRead;fnparse_entry(l:&str)->(i32,String){letparams:Vec<&str>=l.split(' ').collect();letdivisor=params[0].parse::<i32>().unwrap();letword=params[1].to_string();(divisor,word)}fnmain(){letstdin=io::stdin();letmutlines=stdin.lock().lines().map(|l|l.unwrap());letl=lines.next().unwrap();lethigh=l.parse::<i32>().unwrap();letmutentries=Vec::new();forlinlines{if&l==""{break}letentry=parse_entry(&l);entries.push(entry);}foriin1..(high+1){letmutline=String::new();for&(divisor,refword)in&entries{ifi%divisor==0{line=line+&word;}}ifline==""{println!("{}",i);}else{println!("{}",line);}}}
This solution stores the Fizz Buzz state in a struct, leveraging types and the standard library for a more general solution:
usestd::collections::BTreeMap;usestd::fmt::{self,Write};usestd::io::{self,Stdin};#[derive(Debug, PartialEq)]pubstructFizzBuzz{end:usize,factors:Factors,}implFizzBuzz{fnfrom_reader(rdr:&Stdin)->Result<FizzBuzz,Box<dynstd::error::Error>>{letmutline=String::new();rdr.read_line(&mutline)?;letend=line.trim().parse::<usize>()?;letmutfactors=Factors::new();loop{letmutline=String::new();rdr.read_line(&mutline)?;ifline.trim().is_empty(){break;}letmutsplit=line.trim().splitn(2,' ');letfactor=matchsplit.next(){Some(f)=>f.parse::<usize>()?,None=>break,};letphrase=matchsplit.next(){Some(p)=>p,None=>break,};factors.insert(factor,phrase.to_string());}Ok(FizzBuzz{end,factors})}}implfmt::DisplayforFizzBuzz{fnfmt(&self,f:&mutfmt::Formatter)->fmt::Result{fornin1..=self.end{letmuthad_factor=false;// check for factorsfor(factor,phrase)inself.factors.iter(){ifn%factor==0{f.write_str(&phrase)?;had_factor=true;}}if!had_factor{f.write_str(n.to_string().as_str())?;}f.write_char('\n')?;}Ok(())}}typeFactors=BTreeMap<usize,String>;fnmain()->Result<(),Box<dynstd::error::Error>>{letinput=io::stdin();letfizz_buzz=FizzBuzz::from_reader(&input)?;println!("{}",fizz_buzz);Ok(())}#[cfg(test)]modtests{usesuper::*;#[test]fnfizz_buzz_prints_expected_format(){letexpected_factors={letmutmap=Factors::new();map.insert(3,"Fizz".to_string());map.insert(5,"Buzz".to_string());map.insert(7,"Baxx".to_string());map};letexpected_end=20;letfizz_buzz=FizzBuzz{end:expected_end,factors:expected_factors,};letexpected=r#"12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz"#;letprinted=format!("{}",fizz_buzz);assert_eq!(expected,&printed);}}
$ scala GeneralFizzBuzz.scala203 Fizz5 Buzz7 Baxx^D12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
importscala.io.{Source,StdIn}objectGeneralFizzBuzzextendsApp{valmax=StdIn.readInt()valfactors=Source.stdin.getLines().toSeq.map(_.split(" ",2)).map(f=>f(0).toInt->f(1)).sorted(1tomax).foreach{i=>valwords=factors.collect{case(k,v)ifi%k==0=>v}println(if(words.nonEmpty)words.mkStringelsei)}}
importscala.io.{Source,StdIn}objectGeneralFizzBuzzextendsApp{deffizzBuzzTerm(n:Int,factors:Seq[(Int,String)]):String={valwords=factors.collect{case(k,v)ifn%k==0=>v}if(words.nonEmpty)words.mkStringelsen.toString}deffizzBuzz(factors:Seq[(Int,String)]):LazyList[String]=LazyList.from(1).map(fizzBuzzTerm(_,factors))valmax=StdIn.readInt()valfactors=Source.stdin.getLines().toSeq.map(_.split(" ",2)).map{caseArray(k,v)=>k.toInt->v}.sortedfizzBuzz(factors).take(max).foreach(println)}
importscala.io.{Source,StdIn}deffizzBuzzTerm(n:Int,factors:Seq[(Int,String)]):String|Int=valwords=factors.collect{case(k,v)ifn%k==0=>v}ifwords.nonEmptythenwords.mkStringelsendeffizzBuzz(factors:Seq[(Int,String)]):LazyList[String|Int]=LazyList.from(1).map(i=>fizzBuzzTerm(i,factors))@maindefrun():Unit=valmax=StdIn.readInt()valfactors:Seq[(Int,String)]=Source.stdin.getLines().toSeq.map(_.split(" ",2)).map{caseArray(k,v)=>k.toInt->v}.sortedfizzBuzz(factors).take(max).foreach(println)
program general_fizzbuzz; fizzbuzz(20, {[3,"Fizz"], [5,"Buzz"], [7,"Baxx"]}); proc fizzbuzz(maxno, factors); loop for i in [1..maxno] do print(+/[word : word = factors(f) | i mod f=0] ? str i); end loop; end proc;end program;12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
classFizzBuzz(schema=Hash(<3Fizz5Buzz>...)){methodfilter(this){varfb=''schema.sort_by{|k,_|k.to_i}.each{|pair|fb+=(pair[0].to_i`divides`this?pair[1] :'')}fb.len>0 ?fb :this}} funcGeneralFizzBuzz(upto,schema){varping=FizzBuzz()if(nil !=schema){ping.schema=schema.to_hash}(1..upto).map{|i|ping.filter(i)}} GeneralFizzBuzz(20,<3Fizz5Buzz7Baxx>).each{.say}
12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
This is not a particularly efficient solution, but it gets the job done.
/*This code is an implementation of "General FizzBuzz" in SQL ORACLE 19c*/selectlpad(nvl(casewhenmod(level,3)=0then'Fizz'end||casewhenmod(level,5)=0then'Buzz'end||casewhenmod(level,7)=0then'Baxx'end,level),12)asoutputfromdualconnectbylevel<=107;/
1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz FizzBaxx ... 101 Fizz 103 104FizzBuzzBaxx 106 107
import Foundationprint("Input max number: ", terminator: "")guard let maxN = Int(readLine() ?? "0"), maxN > 0 else { fatalError("Please input a number greater than 0")}func getFactor() -> (Int, String) { print("Enter a factor and phrase: ", terminator: "") guard let factor1Input = readLine() else { fatalError("Please enter a factor") } let sep1 = factor1Input.components(separatedBy: " ") let phrase = sep1.dropFirst().joined(separator: " ") guard let factor = Int(sep1[0]), factor != 0, !phrase.isEmpty else { fatalError("Please enter a factor and phrase") } return (factor, phrase)}let (factor1, phrase1) = getFactor()let (factor2, phrase2) = getFactor()let (factor3, phrase3) = getFactor()for i in 1...maxN { let factors = [ (i.isMultiple(of: factor1), phrase1), (i.isMultiple(of: factor2), phrase2), (i.isMultiple(of: factor3), phrase3) ].filter({ $0.0 }).map({ $0.1 }).joined() print("\(factors.isEmpty ? String(i) : factors)")}Input max number: 20Enter a factor and phrase: 3 fizzEnter a factor and phrase: 5 buzzEnter a factor and phrase: 7 baxx12fizz4buzzfizzbaxx8fizzbuzz11fizz13baxxfizzbuzz1617fizz19buzz
def input: {N: 110"1", words: [ { mod: 3"1", word: 'Fizz' }, { mod: 5"1", word: 'Buzz'}, {mod:7"1", word: 'Baxx'}]};templates sayWords def i: $; templates maybeSay def word: $.word; $i mod $.mod -> \(<=0"1"> $word !\) ! end maybeSay '$input.words... -> maybeSay;' -> # when <=''> do $i ! otherwise $ !end sayWords1"1"..$input.N -> sayWords -> '$;' -> !OUT::writev0.5
input is {N: 110"1", words: [ { mod: 3"1", word: 'Fizz' }, { mod: 5"1", word: 'Buzz'}, {mod:7"1", word: 'Baxx'}]};sayWords templates i is $; maybeSay templates word is $(word:); $i mod $(mod:) -> if <|=0"1"> -> $word ! end maybeSay '$input(words:)... -> maybeSay;' -> # ! when <|=''> do $i ! otherwise $ !end sayWords1"1"..$input(N:) -> sayWords -> '$;' ![1, 2, Fizz, 4, Buzz, Fizz, Baxx, 8, Fizz, Buzz, 11, Fizz, 13, Baxx, FizzBuzz, 16, 17, Fizz, 19, Buzz, FizzBaxx, 22, 23, Fizz, Buzz, 26, Fizz, Baxx, 29, FizzBuzz, 31, 32, Fizz, 34, BuzzBaxx, Fizz, 37, 38, Fizz, Buzz, 41, FizzBaxx, 43, 44, FizzBuzz, 46, 47, Fizz, Baxx, Buzz, Fizz, 52, 53, Fizz, Buzz, Baxx, Fizz, 58, 59, FizzBuzz, 61, 62, FizzBaxx, 64, Buzz, Fizz, 67, 68, Fizz, BuzzBaxx, 71, Fizz, 73, 74, FizzBuzz, 76, Baxx, Fizz, 79, Buzz, Fizz, 82, 83, FizzBaxx, Buzz, 86, Fizz, 88, 89, FizzBuzz, Baxx, 92, Fizz, 94, Buzz, Fizz, 97, Baxx, Fizz, Buzz, 101, Fizz, 103, 104, FizzBuzzBaxx, 106, 107, Fizz, 109, Buzz]
Tcl excels at metaprogramming, so this task is trivial. For fun, the below implementation is a compatible extension ofFizzBuzz#Tcl:
procfizzbuzz{nargs}{if{$argseq""}{setargs{{3Fizz}{5Buzz}}}while{[incri]<=$n}{setout""foreachrule$args{lassign$rulemechoif{$i%$m==0}{appendout$echo}}if{$outeq""}{setout$i}puts$out}}fizzbuzz20{3Fizz}{5Buzz}{7Baxx}
This program reads a max number, then reads factors until the user enters a blank line.
## general fizzbuzz#decl int<> factorsdecl string<> wordsdecl int max# get the max numberout ">" consoleset max (in int console)# get the factorsdecl string inputset input " "while (not (= input "")) out ">" console set input (in string console) if (not (= input "")) append (int (split input " ")<0>) factors append (split input " ")<1> words end ifend while# output all the numbersdecl int ifor (set i 1) (< i (+ max 1)) (inc i) decl boolean foundfactor set foundfactor false for (decl int j) (< j (size factors)) (inc j) if (= (mod i factors<j>) 0) set foundfactor true out words<j> console end if end for set j 0 if (not foundfactor) out i console end if out endl consoleend for
Output:
>20>3 Fizz>5 Buzz>7 Baxx>12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
Input"Maximum number: ";mInput"Number of factors: ";nPrintFori=0Ton-1@(i*2)=Val(Ask("Input value: "))@(i*2+1)=Ask("ENTER-word : ")NextPrintFori=1Tome=0Forj=0Ton-1If(i%@(j*2))=0Thene=1:PrintShow(@(j*2+1));NextPrintShow(Iif(e=0,Str(i),""))Next
OptionExplicitPrivateTypeChoiceNumberAsIntegerNameAsStringEndTypePrivateMaxNumberAsIntegerSubMain()DimU(1To3)AsChoice,iAsInteger,jAsInteger,t$MaxNumber=Application.InputBox("Enter the max number : ","Integer please",Type:=1)Fori=1To3U(i)=UserChoiceNextFori=1ToMaxNumbert=vbNullStringForj=1To3IfiModU(j).Number=0Thent=t&U(j).NameNextDebug.PrintIIf(t=vbNullString,i,t)NextiEndSubPrivateFunctionUserChoice()AsChoiceDimokAsBooleanDoWhileNotokUserChoice.Number=Application.InputBox("Enter the factors to be calculated : ","Integer please",Type:=1)UserChoice.Name=InputBox("Enter the corresponding word : ")IfStrPtr(UserChoice.Name)<>0AndUserChoice.Number<MaxNumberThenok=TrueLoopEndFunction
With the entry :Max : 120;3 : Fizz;5 : Buzz;7 : Baxx
1 2 Fizz 4 BuzzFizzBaxx 8 FizzBuzz 11 Fizz 13 BaxxFizzBuzz 16 17 Fizz 19 BuzzFizzBaxx 22 23 ......Buzz 101 Fizz 103 104 FizzBuzzBaxx 106 107 Fizz 109 BuzzFizzBaxx 113 FizzBuzz 116 Fizz 118 BaxxFizzBuzz
'The FunctionFunctionFizzBuzz(range,mapping)data=Array()'Parse the mapping and put to "data" arraytemp=Split(mapping,",")ReDimdata(UBound(temp),1)Fori=0ToUBound(temp)map=Split(temp(i)," ")data(i,0)=map(0)data(i,1)=map(1)Next'Do the loopFori=1torangenoMatch=TrueForj=0toUBound(data,1)If(iModdata(j,0))=0ThenWScript.StdOut.Writedata(j,1)noMatch=FalseEndIfNextIfnoMatchThenWScript.StdOut.WriteiWScript.StdOut.WritevbCrLfNextEndFunction'The Main ThingWScript.StdOut.Write"Range? "x=WScript.StdIn.ReadLineWScript.StdOut.Write"Mapping? "y=WScript.StdIn.ReadLineWScript.StdOut.WriteLine""FizzBuzzx,y
\Desktop>cscript /nologo fizzbuzz.vbsRange? 20Mapping? 3 Fizz,5 Buzz,7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz\Desktop>
ImportsSystem.GlobalizationModuleProgramSubMain()Console.Write("Max: ")Dimmax=Integer.Parse(Console.ReadLine(),CultureInfo.InvariantCulture)DimfactorsAsNewSortedDictionary(OfInteger,String)ConstNUM_FACTORS=3Fori=1ToNUM_FACTORSConsole.Write("Factor {0}: ",i)Diminput=Console.ReadLine().Split()factors.Add(Integer.Parse(input(0),CultureInfo.InvariantCulture),input(1))NextFori=1TomaxDimanyMatches=FalseForEachfactorInfactorsIfiModfactor.Key=0ThenConsole.Write(factor.Value)anyMatches=TrueEndIfNextIfNotanyMatchesThenConsole.Write(i)Console.WriteLine()NextEndSubEndModule
Max: 20Factor 1: 7 BaxxFactor 2: 3 FizzFactor 3: 5 Buzz12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
import os fn main() { max := os.input('Max: ').int() f1 := os.input('Starting factor (#) and word: ').fields() f2 := os.input('Next factor (#) and word: ').fields() f3 := os.input('Next factor (#) and word: ').fields() //using the provided data words := { f1[0].int(): f1[1], f2[0].int(): f2[1], f3[0].int(): f3[1], } keys := words.keys() mut divisible := false for i := 1; i <= max; i++ { for n in keys { if i % n == 0 { print(words[n]) divisible = true } } if !divisible { print(i) } println('') divisible = false }}Max: 20Starting factor: 3 FizzNext factor: 5 BuzzNext factor: 7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
import"io"forStdin,Stdoutimport"./sort"forSortvarnwhile(true){System.write("Maximum number : ")Stdout.flush()n=Num.fromString(Stdin.readLine())if(!n||!n.isInteger||n<3){System.print("Must be an integer > 2, try again.")}else{break}}varfactors=[]varwords={}for(iin0..2){while(true){System.write("Factor%(i+1) : ")Stdout.flush()varfactor=Num.fromString(Stdin.readLine())if(!factor||!factor.isInteger||factor<2||factors.contains(factor)){System.print("Must be an unused integer > 1, try again.")}else{factors.add(factor)varouter=falsewhile(true){System.write(" Word%(i+1) : ")Stdout.flush()varword=Stdin.readLine()if(word.count==0){System.print("Must have at least one character, try again.")}else{words[factor]=wordouter=truebreak}}if(outer)break}}}Sort.insertion(factors)System.print()for(iin1..n){vars=""for(jin0..2){varfactor=factors[j]if(i%factor==0)s=s+words[factor]}if(s=="")s=i.toStringSystem.print(s)}
Maximum number : 20Factor 1 : 3 Word 1 : FizzFactor 2 : 5 Word 2 : BuzzFactor 3 : 7 Word 3 : Bazz12Fizz4BuzzFizzBazz8FizzBuzz11Fizz13BazzFizzBuzz1617Fizz19Buzz
string 0; \use zero-terminated stringsproc GetString(S); \Get string (S) from userchar S;[loop [S(0):= ChIn(0); if S(0) = $0D \CR\ then quit; S:= S+1; ];S(0):= 0; \replace CR with terminator];int Limit, I, Factor(3), Str(3,40), F(3), N;[Limit:= IntIn(0);for I:= 0 to 2 do [Factor(I):= IntIn(0); GetString(Str(I)); F(I):= 0; ];for N:= 1 to Limit do [for I:= 0 to 2 do [F(I):= F(I)+1; if F(I) >= Factor(I) then [Text(0, Str(I)); F(I):= 0; ]; ]; if F(0)*F(1)*F(2) # 0 then IntOut(0, N); CrLf(0); ];]
203 Fizz5 Buzz7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
stop:=ask("Count: ").toInt();fizzBuzzers:=List(); do(3){ n,txt:=ask(">").split(); fizzBuzzers.append(T(n.toInt(),txt)) }foreach n in ([1..stop]){ s:=fizzBuzzers.filter('wrap([(fb,txt)]){ n%fb==0 }).apply("get",1).concat(); println(s or n);}$ zkl bbbCount: 20>3 Fizz >5 Buzz>7 Baxx12Fizz4BuzzFizzBaxx8FizzBuzz11Fizz13BaxxFizzBuzz1617Fizz19Buzz
10INPUT"Maximum number: ";max20INPUT"Number of factors: ";n30DIMf(n):DIMw$(n,4)40FORi=1TOn50INPUT"Input value-ENTER-word: ";f(i);w$(i)60NEXTi70FORi=1TOmax80LETmatched=090FORj=1TOn100IFFNm(i,f(j))=0THENLETmatched=1:PRINTw$(j);110NEXTj120IFNOTmatchedTHENPRINT;i:GOTO140130PRINT140NEXTi150DEF FNm(a,b)=a-INT(a/b)*b