General FizzBuzz: Difference between revisions

Add SETL
(Add SETL)
 
(72 intermediate revisions by 39 users not shown)
Line 53:
</pre>
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">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))</syntaxhighlight>
 
{{out}}
<pre>
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">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)
OD
RETURN
 
BYTE 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^=1
RETURN (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)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/General_FizzBuzz.png Screenshot from Atari 8-bit computer]
<pre>
Max number (1-200): 105
Number of rules (1-5): 3
Rule #1 (number space text):3 Fizz
Rule #2 (number space text):5 Buzz
Rule #3 (number space text):7 Baxx
 
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
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Containers.Generic_Array_Sort;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
 
procedure Main is
type map_element is record
Num : Positive;
Word : Unbounded_String;
end record;
 
type map_list is array (Positive range <>) of map_element;
 
function "<" (Left, Right : map_element) return Boolean is
begin
return Left.Num < Right.Num;
end "<";
 
procedure list_sort is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive, Element_Type => map_element,
Array_Type => map_list);
procedure general_fizz_buzz (max : Positive; words : in out map_list) is
found : Boolean;
begin
list_sort (words);
 
for i in 1 .. max loop
found := False;
for element of words loop
if i mod element.Num = 0 then
found := True;
Put (element.Word);
end if;
end loop;
if not found then
Put (Item => i, Width => 1);
end if;
New_Line;
end loop;
end general_fizz_buzz;
 
fizzy : map_list :=
((3, To_Unbounded_String ("FIZZ")), (7, To_Unbounded_String ("BAXX")),
(5, To_Unbounded_String ("BUZZ")));
 
begin
general_fizz_buzz (20, fizzy);
end Main;
</syntaxhighlight>
{{output}}
<pre>
1
2
FIZZ
4
BUZZ
FIZZ
BAXX
8
FIZZ
BUZZ
11
FIZZ
13
BAXX
FIZZBUZZ
16
17
FIZZ
19
BUZZ
</pre>
 
=={{header|ALGOL 68}}==
Uses a modified version of the Algol 68 Quicksort task sample.
<syntaxhighlight lang="algol68">BEGIN # generalised FizzBuzz #
# prompts for an integer, reads it and returns it #
PROC read integer = ( STRING prompt )INT:
BEGIN
print( ( prompt ) );
INT result;
read( ( result, newline ) );
result
END; # read integer #
# prompts for a string, reads it and returns it #
PROC read string = ( STRING prompt )STRING:
BEGIN
print( ( prompt ) );
STRING result;
read( ( result, newline ) );
result
END; # read 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 uicksort #
# 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 integer( "Numbers reuired: " );
# number of factors reuired #
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 integer( "Factor " + whole( i, 0 ) + ": " );
text OF factors [ i ] := read 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 ) )
OD
END</syntaxhighlight>
{{out}}
<pre>
Numbers reuired: 20
Factor 1: 7
Text for 7: Baxx
Factor 2: 3
Text for 3: Fizz
Factor 3: 5
Text for 5: Buzz
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">--------------------- GENERAL FIZZBUZZ -------------------
{{Trans|JavaScript}}
<lang AppleScript>-- GENERAL FIZZBUZZ ----------------------------------------------------------
 
-- fizzfizzEtc :: [[(Int, String])] -> Int -> String[Symbol]
on fizzEtc(rules)
on fizz(lstRules, intMax)
-- A non-finite sequence of fizzEtc symbols,
-- fizzLineas ::defined Stringby ->the Intgiven ->list Stringof rules.
script fizzlinenumberOrNoise
on |λ|(strSeries, n)
script ruleMatch
-- Multiple rule matches ->on |λ|(a, single or concatenated wordsmk)
-- wordIfRuleMatch :: String -> (Int set {m, String)k} ->to Stringmk
script wordIfRuleMatch
on |λ|(str, rulePair)
set {factor, noiseWord} to rulePair
cond(n mod factor >if 0, str,= str(n &mod noiseWordm) then
if integer is class of a then
k
else
a & k
end if
else
a
end if
end |λ|
end script
set strPhrase to foldl(wordIfRuleMatchruleMatch, ""n, lstRulesrules)
strSeries & cond(strPhrase ≠ "", strPhrase, n as string) & linefeed
end |λ|
end script
foldlfmapGen(fizzlinenumberOrNoise, "", enumFromToenumFrom(1, intMax))
end fizzfizzEtc
 
 
-- TEST ----------------------------------------------------------------------
--------------------------- TEST -------------------------
on run
unlines(take(20, ¬
fizz([[3, "Fizz"], [5, "Buzz"], [7, "Baxx"]], 20)
fizzEtc({{3, "Fizz"}, {5, "Buzz"}, {7, "Baxx"}})))
end run
 
-- GENERIC FUNCTIONS ---------------------------------------------------------
 
------------------------- GENERIC ------------------------
-- cond :: Bool -> a -> a -> a
 
on cond(bool, x, y)
-- enumFrom :: Enum a => a -> [a]
if bool then
on enumFrom(x)
x
elsescript
yproperty v : missing value
end if on |λ|()
if missing value is not v then
end cond
set v to 1 + v
else
set v to x
end if
return v
end |λ|
end script
end enumFrom
 
 
-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
on fmapGen(f, gen)
script
property g : mReturn(f)
on |λ|()
set v to gen's |λ|()
if v is missing value then
v
else
g's |λ|(v)
end if
end |λ|
end script
end fmapGen
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 129 ⟶ 477:
end foldl
 
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: HandlerFirst-class m => (a -> b) -> m (a -> Scriptb)
on mReturn(f)
if-- 2nd class ofhandler ffunction islifted into 1st class script thenwrapper.
if script is class of f then
f
else
Line 139 ⟶ 488:
end script
end if
end mReturn</lang>
 
 
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
end take
 
 
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines</syntaxhighlight>
{{Out}}
<pre>1
Line 161 ⟶ 538:
19
Buzz</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">maxNum: to :integer strip input "Set maximum number: "
facts: map 1..3 'x -> split.words strip input ~"Enter factor |x|: "
loop 1..maxNum 'i [
printNum: true
loop facts 'fact ->
if zero? i % to :integer fact\0 [
prints fact\1
printNum: false
]
print (printNum)? -> i -> ""
]</syntaxhighlight>
 
{{out}}
 
<pre>Set maximum number: 20
Enter factor 1: 3 Fizz
Enter factor 2: 5 Buzz
Enter factor 3: 7 Baxx
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">; Test parameters
max := 20, fizz := 3, buzz := 5, baxx := 7
 
Loop % 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, *
else
FileAppend %output%`n, *
}
</syntaxhighlight>
{{Out}}
<pre>
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|AWK}}==
Line 177 ⟶ 637:
 
;Usage:
<langsyntaxhighlight lang="bash">awk -f fizzbuzzGenerate.awk input.txt > fizzbuzzCustom.awk
awk -f fizzbuzzCustom.awk numbers.txt</langsyntaxhighlight>
 
;Program:
<!-- http://ideone.com/fACMfK -->
<!-- (!!) Note: the sandbox at ideone.com does not allow output to files -->
<langsyntaxhighlight lang="awk"># usage: awk -f fizzbuzzGen.awk > fizzbuzzCustom.awk
#
function Print(s) {
Line 215 ⟶ 675:
print "END {print " q2 "# Done." q2 "}"
Print( "# Done." )
}</langsyntaxhighlight>
 
Example output see [[FizzBuzz/AWK#Custom_FizzBuzz]]
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
rem input range
setlocal enabledelayedexpansion
set /p "range=> "
::Range variable
set range=20
 
::Therem input data [will(no not be validated]error-checking)
set "data_ctr=0"
::This is the strictly the data format...
:input_loop
set "data=3:Fizz 5:Buzz 7:Baxx"
set "data="
 
set /p "data=> "
::Parsing the data into 1-based pseudo-arrays...
if "%data%" equ "" goto count
set "data_cnt=0"
rem parsing data into 1-based pseudo-array
for %%A in (!data!) do (
set /a "data_cntdata_ctr+=1"
for /f "tokens=1-2 delims=: " %%D in ("%data%A") do (
set "fact!data_cnt!facto%data_ctr%=%%D"
set "prnt!data_cnt!print%data_ctr%=%%E"
)
)
goto input_loop
 
rem perform fizzbuzz now
::Do the count...
:count
for /l %%C in (1,1,!range!) do (
setlocal enabledelayedexpansion
set "out="
for /l %%.C in (1,1,!data_cnt!%range%) do (
set "out="
set /a "mod=%%C %% fact%%."
for /l %%X in (1,1,%data_ctr%) do (
if !mod! equ 0 (
set /a "outmod=!out!!prnt%%.!C %% facto%%X"
if !mod! equ 0 set "out=!out!!print%%X!"
)
)
if not defined out (echo. %%C) else (echo. !out!)
)
pause
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>1> 20
> 3 Fizz
> 5 Buzz
> 7 Baxx
>
1
2
Fizz
Line 274 ⟶ 738:
Buzz
Press any key to continue . . .</pre>
 
 
=={{header|BBC BASIC}}==
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.
<langsyntaxhighlight lang="bbcbasic">REM >genfizzb
INPUT "Maximum number: " max%
INPUT "Number of factors: " n%
Line 297 ⟶ 760:
NEXT
IF matched% THEN PRINT ELSE PRINT;i%
NEXT</langsyntaxhighlight>
Output:
<pre>Maximum number: 20
Line 324 ⟶ 787:
19
Buzz</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">GenFizzBuzz ← {factors‿words ← <˘⍉>𝕨 ⋄ (∾´∾⟜words/˜·(¬∨´)⊸∾0=factors|⊢)¨1+↕𝕩}</syntaxhighlight>
Example usage:
<syntaxhighlight lang="text"> ⟨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" ⟩</syntaxhighlight>
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 380 ⟶ 849:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 404 ⟶ 873:
Buzz
</pre>
 
=={{header|C sharp}}==
Not extremely clever and doesn't use anything too fancy.
<syntaxhighlight lang="csharp">
using System;
 
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
 
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(int n = 1; n<= limit; n++)
{
bool flag = 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();
}
}
}
</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <algorithm>
#include <iostream>
Line 444 ⟶ 978:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 469 ⟶ 1,003:
</pre>
 
=={{header|CCaché sharpObjectScript}}==
<syntaxhighlight lang="caché objectscript">GENFIZBUZZ(MAX,WORDS,NUMBERS)
Not extremely clever and doesn't use anything too fancy.
; loop until max, casting numeric to avoid errors
<lang csharp>
for i=1:1:+MAX {
using System;
set j = 1
 
set descr = ""
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
; assumes NUMBERS parameter is comma-delimited
int limit;
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
string iString;
stringwrite jString;" "_$case(descr,"":i,:descr)
} ; next value until MAX
string kString;
quit</syntaxhighlight>
 
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(int n = 1; n<= limit; n++)
{
bool flag = 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();
}
}
}
</lang>
 
=={{header|Caché ObjectScript}}==
<lang Caché ObjectScript>GENFIZBUZZ(MAX,WORDS,NUMBERS)
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
quit</lang>
 
{{out}}<pre>SAMPLES>do ^GENFIZBUZZ(12,"FIN,FANG,FOOM","2,3,4")
Line 561 ⟶ 1,032:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
print("enter the max value");
Line 600 ⟶ 1,071:
}
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(defn fix [pairs]
(map second pairs))
 
Line 617 ⟶ 1,088:
(apply str
(fix f)))))
numbers)))</langsyntaxhighlight>
 
'''Usage:'''
Line 648 ⟶ 1,119:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
<lang Lisp>
(defun fizzbuzz (limit factor-words)
(loop for i from 1 to limit
Line 676 ⟶ 1,147:
(not (zerop (parse-integer input :junk-allowed t))))
finally (fizzbuzz (parse-integer input :junk-allowed t) (read-factors))))
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">
counter = 0
 
puts "Enter a maximum number:"
limit = gets
 
puts "Enter the first integer for factoring:"
first_int = gets
puts "Enter the name of the first integer:"
first_int_name = gets
 
puts "Enter the second integer for factoring:"
second_int = gets
puts "Enter the name of the second integer:"
second_int_name = gets
 
puts "Enter the third integer for factoring:"
third_int = gets
puts "Enter the name of the third integer:"
third_int_name = gets
 
if (limit &&
first_int &&
second_int &&
third_int &&
first_int_name &&
second_int_name &&
third_int_name)
limit = limit.chomp.to_i
first_int = first_int.chomp.to_i
second_int = second_int.chomp.to_i
third_int = third_int.chomp.to_i
while limit > counter
counter += 1
if (counter % first_int) == 0 && (counter % second_int) == 0 && (counter % third_int) == 0
puts first_int_name + second_int_name + third_int_name
elsif (counter % first_int) == 0 && (counter % second_int) == 0
puts first_int_name + second_int_name
elsif (counter % first_int) == 0
puts first_int_name
elsif (counter % second_int) == 0
puts second_int_name
elsif (counter % third_int) == 0
puts third_int_name
else
puts counter
end
end
else
exit
end
</syntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import core.stdc.stdlib;
import std.stdio;
 
Line 727 ⟶ 1,252:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 755 ⟶ 1,280:
19
Buzz</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
max = 20
words$[] = [ "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 ""
.
</syntaxhighlight>
{{out}}
<pre>
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule General do
def fizzbuzz(input) do
[num | nwords] = String.split(input)
Line 776 ⟶ 1,345:
7 Baxx
"""
General.fizzbuzz(input)</langsyntaxhighlight>
 
{{out}}
Line 811 ⟶ 1,380:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
%%% @doc Implementation of General FizzBuzz
%%% @see https://rosettacode.org/wiki/General_FizzBuzz
Line 837 ⟶ 1,406:
[fizzbuzz(X, Factors, []) || X <- lists:seq(1, N)]
).
</syntaxhighlight>
</lang>
'''Usage:'''
<pre>
Line 871 ⟶ 1,440:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs combinators.extras io kernel math math.parser
math.ranges prettyprint sequences splitting ;
IN: rosetta-code.general-fizzbuzz
Line 891 ⟶ 1,460:
: main ( -- ) get-input [ fizzbuzz ] with each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 923 ⟶ 1,492:
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 ..'
<langsyntaxhighlight Forthlang="forth">\ gfb.fs - generalized fizz buzz
: times ( xt n -- )
BEGIN dup WHILE
Line 948 ⟶ 1,517:
\ Example:
\ 1 fb[ 3 s" fizz" ]+[ 5 s" buzz" ]+[ 7 s" dizz" ]+[ ]fb 40 times drop
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 956 ⟶ 1,525:
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
</pre>
 
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="freebasic">' version 01-03-2018
' compile with: fbc -s console
 
Line 1,016 ⟶ 1,586:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>Enter maximum number, if number < 1 then the program wil end 110
Line 1,044 ⟶ 1,614:
109
Buzz</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
_mfile = 1
begin enum
_iNewGame
_
_iClose
end enum
_mEdit = 2
 
_window = 1
begin enum 1
_maxNumLabel
_maxNumFld
_f1Label
_f1Fld
_wd1Label
_wd1Fld
_f2Label
_f2Fld
_wd2Label
_wd2Fld
_f3Label
_f3Fld
_wd3Label
_wd3Fld
_playBtn
end enum
 
void local fn BuildMenu
menu _mFile,,, @"File"
menu _mFile, _iNewGame,, @"New Game"
menu _mFile, _iClose,, @"Close", @"w"
MenuItemSetAction( _mFile, _iClose, @"performClose:" )
editmenu _mEdit
end fn
 
void 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 fn
 
void 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)
next
end fn
 
 
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _btnClick
select ( tag )
case _playBtn : fn PlayFizzBuzz
end select
end select
end fn
 
fn BuildMenu
fn BuildWindow
 
on dialog fn DoDialog
 
HandleEvents
</syntaxhighlight>
[[file:General FizzBuzz2 FB.png]]
 
=={{header|Go}}==
<syntaxhighlight lang="go">
<lang Go>
package main
 
Line 1,080 ⟶ 1,763:
}
 
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight Groovylang="groovy">def log = ''
(1..40).each {Integer value -> 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'
Line 1,089 ⟶ 1,772:
:(value+'\n')}
println log
</syntaxhighlight>
</lang>
<pre>
1
Line 1,132 ⟶ 1,815:
BUZZ
</pre>
 
''' or (inspired by normal FizzBuzz in Groovy: https://rosettacode.org/wiki/FizzBuzz#Groovy '''
<syntaxhighlight lang="groovy">
def fizzBuzz = { i -> [[3,'Fizz'],[5,'Buzz'],[7,'Baxx']].collect{i%it[0]?'':it[1]}.join()?:i}
1.upto(100){println fizzBuzz(it)}
</syntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">fizz :: (Integral a, Show a) => a -> [(a, String)] -> String
fizz a xs
| null result = show a
Line 1,151 ⟶ 1,840:
mapM_ (\ x -> putStrLn $ fizz x multiples) [1..n]
where convert [x, y] = (read x, y)
</syntaxhighlight>
</lang>
 
Or, as a function which takes a list of rules as an argument:
 
<langsyntaxhighlight lang="haskell">type Rule = (Int, String)
 
----------------- FIZZETC (USING RULE SET) ---------------
testFizz :: Int -> [String]
testFizz = fizz [(3, "Fizz"), (5, "Buzz"), (7, "Baxx")]
 
fizzfizzEtc :: [Rule(Int, String)] -> Int -> [String]
fizzfizzEtc rules n = foldr nextLine [] [1 .. n]
where
nextLine x a =
(if| null noise = show x : a
| otherwise = thennoise show: xa
else noise) :
a
where
noise = foldl reWrite [] rules
reWrite s (m, k) =
| 0 == rem x m = s ++<> k
(if| remotherwise x m == 0s
 
then k
 
else [])
------------------- TEST OF SAMPLE RULES -----------------
fizzTest :: [String]
fizzTest = fizzEtc [(3, "Fizz"), (5, "Buzz"), (7, "Baxx")]
 
main :: IO ()
main = mapM_ putStrLn (testFizz$ take 20)</lang> fizzTest
</syntaxhighlight>
{{Out}}
<pre>1
Line 1,204 ⟶ 1,894:
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:
 
<langsyntaxhighlight Jlang="j">genfb=:1 :0
:
b=. * x|/1+i.y
>,&":&.>/(m#inv"_1~-.b),(*/b)#&.>1+i.y
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> 3 5 7 ('Fizz';'Buzz';'Baxx')genfb 20
1
2
Line 1,232 ⟶ 1,922:
Fizz
19
Buzz </langsyntaxhighlight>
 
For our example, b looks like this:
 
<langsyntaxhighlight Jlang="j">1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1
1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0
1 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1</langsyntaxhighlight>
 
<code>*/b</code> gives us 1s where we want numbers and 0s where we want to plug in the strings:
 
<langsyntaxhighlight Jlang="j"> */*3 5 7|/1+i.20
1 1 0 1 0 0 0 1 0 0 1 0 1 0 0 1 1 0 1 0</langsyntaxhighlight>
 
<code>m</code> is our strings, and #inv expands values out to match a selection. So, in our example, <code>m#inv"_1~-.b</code> looks like this:
 
<langsyntaxhighlight Jlang="j">┌┬┬────┬┬────┬────┬────┬┬────┬────┬┬────┬┬────┬────┬┬┬────┬┬────┐
│││Fizz││ │Fizz│ ││Fizz│ ││Fizz││ │Fizz│││Fizz││ │
├┼┼────┼┼────┼────┼────┼┼────┼────┼┼────┼┼────┼────┼┼┼────┼┼────┤
Line 1,253 ⟶ 1,943:
├┼┼────┼┼────┼────┼────┼┼────┼────┼┼────┼┼────┼────┼┼┼────┼┼────┤
│││ ││ │ │Baxx││ │ ││ ││Baxx│ │││ ││ │
└┴┴────┴┴────┴────┴────┴┴────┴────┴┴────┴┴────┴────┴┴┴────┴┴────┘</langsyntaxhighlight>
 
All that remains is to assemble these pieces into the final result...
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class FizzBuzz {
 
public static void main(String[] args) {
Line 1,286 ⟶ 1,976:
}
 
}</langsyntaxhighlight>
 
 
'''For a more complete example see [[/jFizzBuzz|jFizzBuzz]]'''
 
''' Or using a lot of Lambdas ... '''
 
<syntaxhighlight lang="java">
import java.util.stream.*;
import java.util.function.*;
import java.util.*;
public class fizzbuzz_general {
/**
* To run: java fizzbuzz_general.java 3=Fizz 5=Buzz 7=Baxx 100
*
*/
public static void main(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);
}
}
</syntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,299 ⟶ 2,023:
 
First as compacted by Google's Closure compiler:
<langsyntaxhighlight JavaScriptlang="javascript">function fizz(d, e) {
return function b(a) {
return a ? b(a - 1).concat(a) : [];
Line 1,307 ⟶ 2,031:
}, "") || a.toString()) + "\n";
}, "");
}</langsyntaxhighlight>
 
and then in the original expanded form, for better legibility:
 
<langsyntaxhighlight JavaScriptlang="javascript">function fizz(lstRules, lngMax) {
 
return (
Line 1,336 ⟶ 2,060:
}
 
fizz([[3, 'Fizz'], [5, 'Buzz'], [7, 'Baxx']], 20);</langsyntaxhighlight>
 
{{out}}
Line 1,363 ⟶ 2,087:
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">// range :: Int -> Int -> [Int]
const range = (min, max) =>
Array.from({ length: max - min }, (_, i) => min + i)
Line 1,381 ⟶ 2,105:
).join('\n')
 
console.log(fizzBuzz(20))</langsyntaxhighlight>
 
{{Out}}
Line 1,409 ⟶ 2,133:
=={{header|Julia}}==
For simplicity, assume that the user will enter valid input.
<langsyntaxhighlight Julialang="julia">function fizzbuzz(triggers :: Vector{Tuple{Int, ASCIIString}}, upper :: Int)
for i = 1 : upper
triggered = false
Line 1,437 ⟶ 2,161:
 
println("EOF\n")
fizzbuzz(triggers, upper)</langsyntaxhighlight>
 
{{out}}
Line 1,471 ⟶ 2,195:
=={{header|Kotlin}}==
 
<langsyntaxhighlight Kotlinlang="kotlin">fun main(args: Array<String>) {
 
//Read the maximum number, set to 0 if it couldn't be read
Line 1,498 ⟶ 2,222:
println(i)
}
}</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function generalisedFizzBuzz m, f1, f2, f3
put f1 & cr & f2 & cr & f3 into factors
sort factors ascending numeric
Line 1,522 ⟶ 2,246:
end repeat
return fizzbuzz
end generalisedFizzBuzz</langsyntaxhighlight>Example<langsyntaxhighlight LiveCodelang="livecode">put generalisedFizzBuzz(20,"7 baxx","3 fizz","5 buzz")</langsyntaxhighlight>
 
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function genFizz (param)
local response
print("\n")
Line 1,545 ⟶ 2,268:
param.factor[i], param.word[i] = io.read("*number", "*line")
end
genFizz(param)</langsyntaxhighlight>
 
=== Without modulo ===
{{trans|Python}}
<langsyntaxhighlight Lualang="lua">local function fizzbuzz(n, mods)
local res = {}
 
Line 1,584 ⟶ 2,307:
print(fizzbuzz(n, mods))
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,602 ⟶ 2,325:
7
broccoli </pre>
 
===Fast Version without Modulo===
<syntaxhighlight lang="lua">#!/usr/bin/env luajit
 
local num = arg[1] or tonumber(arg[1]) or 110
local t = {
{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 output
local cnt = setmetatable({}, {__index = function() return 0 end})
 
for i = 1,num do
for i = 1,#t do
cnt[i] = cnt[i]+1
end
local match = false
for i=1,#t do
if cnt[i] == t[i][1] then
io.write(t[i][2])
cnt[i] = 0
match = true
end
end
if not match then
io.write(i)
end
io.write(", ")
end
</syntaxhighlight>
{{out}}
<pre>
> ./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,
</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">findNum := proc(str) #help parse input
local i;
i := 1:
Line 1,635 ⟶ 2,396:
if (not factored) then printf("%d", i): end if:
printf("\n");
end do:</langsyntaxhighlight>
{{Out|Output}}
<pre>1
Line 1,658 ⟶ 2,419:
Buzz</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">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}
]</langsyntaxhighlight>
 
<pre>1
Line 1,680 ⟶ 2,441:
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz</pre>
 
=={{header|MiniScript}}==
 
This implementation improves slightly over the proposed task, making the prompts a little friendlier.
 
<syntaxhighlight lang="miniscript">factorWords = {}
 
maxNr = val(input("Max number? "))
 
while true
factorInput = input("Factor? ")
if factorInput == "" then break
// Split input
parts = factorInput.split(" ")
factor = val(parts[0])
word = parts[1]
// Assign factor/word
factorWords[factor] = word
end while
 
for nr in range(1,maxNr)
matchingWords = ""
for factor in factorWords.indexes
if nr % factor == 0 then
matchingWords = matchingWords + factorWords[factor]
end if
end for
if matchingWords then print matchingWords else print nr
end for</syntaxhighlight>
 
Sample session:
 
<pre>Max number? 20
Factor? 3 Fizz
Factor? 5 Buzz
Factor?
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
Line 1,688 ⟶ 2,505:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE GeneralFizzBuzz;
FROM Conversions IMPORT StrToInt;
FROM FormatString IMPORT FormatString;
Line 1,790 ⟶ 2,607:
 
ReadChar
END GeneralFizzBuzz.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Ursa}}
<syntaxhighlight lang="nanoquery">factors = {}
words = {}
 
// get the max number
print ">"
max = int(input())
 
// get the factors
inp = " "
while inp != ""
print ">"
inp = input()
if " " in inp
factors.append(int(split(inp, " ")[0]))
words.append(split(inp, " ")[1])
end
end
 
// output all the numbers
for i in range(1, max)
foundfactor = false
for j in range(0, len(factors) - 1)
if (i % factors[j]) = 0
foundfactor = true
print words[j]
end
end
j = 0
 
if !foundfactor
print i
end
println
end</syntaxhighlight>
 
{{out}}
<pre>>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</pre>
 
=={{header|Nim}}==
This solution has no input validation
<langsyntaxhighlight lang="nim">
import parseutils, strutils, algorithm
 
Line 1,840 ⟶ 2,721:
 
 
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Original version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
<syntaxhighlight lang="ocaml">
(* Task : General_FizzBuzz *)
 
(*
The FizzBuzz problem, but
generalized to have any strings, at any steps,
up to any number of iterations.
*)
 
let gen_fizz_buzz (n : int) (l : (int * string) list) : unit =
let fold_f i (acc : bool) (k, s) =
if i mod k = 0
then (print_string s; true)
else acc
in
let rec helper i =
if i > n
then ()
else
let any_printed = List.fold_left (fold_f i) false l in
begin
(if not any_printed
then print_int i);
print_newline ();
helper (succ i)
end
in
helper 1
;;
 
(*** Output ***)
 
gen_fizz_buzz 20 [(3, "Fizz"); (5, "Buzz"); (7, "Baxx")] ;;
</syntaxhighlight>
{{out}}
<pre>
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.8.0+}}
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 call <code>fizz(20,[[3,"Fizz"],[5,"Buzz"],[7,"Baxx"]])</code>) or to support exactly factors (keeping the call the same).
<langsyntaxhighlight lang="parigp">fizz(n,v[..])=
{
v=vecsort(v,1);
Line 1,859 ⟶ 2,800:
);
}
fizz(20,[3,"Fizz"],[5,"Buzz"],[7,"Baxx"])</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,883 ⟶ 2,824:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">
#!bin/usr/perl
use 5.020;
Line 1,935 ⟶ 2,876:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,969 ⟶ 2,910:
</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">-->
{{works with|rakudo|2015-09-20}}
<span style="color: #008080;">procedure</span> <span style="color: #000000;">general_fizz_buzz</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">lim</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">facts</span><span style="color: #0000FF;">)</span>
<lang perl6># General case implementation of a "FizzBuzz" class.
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">lim</span> <span style="color: #008080;">do</span>
# Defaults to standard FizzBuzz unless a new schema is passed in.
<span style="color: #004080;">string</span> <span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
class FizzBuzz {
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">facts</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
has $.schema is rw = < 3 Fizz 5 Buzz >.hash;
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">facts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
method filter (Int $this) {
<span style="color: #000000;">word</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">words</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
my $fb;
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
for $.schema.sort: { +.key } -> $p { $fb ~= $this %% +$p.key ?? $p.value !! ''};
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return $fb || $this;
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">word</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
}
<span style="color: #000000;">word</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
}
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">word</span><span style="color: #0000FF;">})</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
# Sub implementing the specific requirements of the task.
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
sub GeneralFizzBuzz (Int $upto, @schema?) {
<span style="color: #000000;">general_fizz_buzz</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Fizz"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Buzz"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Baxx"</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">})</span>
my $ping = FizzBuzz.new;
<!--</syntaxhighlight>-->
$ping.schema = @schema.hash if @schema;
{{out}}
map { $ping.filter: $_ }, 1 .. $upto;
<pre>
}
 
# The task
say 'Using: 20 ' ~ <3 Fizz 5 Buzz 7 Baxx>;
.say for GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>);
 
say '';
 
# And for fun
say 'Using: 21 ' ~ <2 Pip 4 Squack 5 Pocketa 7 Queep>;
say join ', ', GeneralFizzBuzz(21, <2 Pip 4 Squack 5 Pocketa 7 Queep>);</lang>
{{Out}}
<pre>Using: 20 3 Fizz 5 Buzz 7 Baxx
1
2
Line 2,021 ⟶ 2,950:
19
Buzz
</pre>
 
=={{header|PHP}}==
Using: 21 2 Pip 4 Squack 5 Pocketa 7 Queep
<syntaxhighlight lang="php"><?php
1, Pip, 3, PipSquack, Pocketa, Pip, Queep, PipSquack, 9, PipPocketa, 11, PipSquack, 13, PipQueep, Pocketa, PipSquack, 17, Pip, 19, PipSquackPocketa, Queep</pre>
 
$max = 20;
Here's the same program in a more functional idiom:
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
<lang perl6>sub genfizzbuzz($n, +@fb) {
 
[Z~](
for ($i = 1 ; do for @fb ||$i <3= fizz$max 5 buzz> ->; $i, $s++) {
$matched = false;
flat ('' xx $i-1, $s) xx *;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
) Z|| 1..$n}
echo ($matched ? '' : $i), PHP_EOL;
}
 
?></syntaxhighlight>
.say for genfizzbuzz(20, <3 Fizz 5 Buzz 7 Baxx>);</lang>
{{out}}
<pre>1
2
Fizz
4
Buzz
Fizz
Jazz
8
Fizz
Buzz
11
Fizz
13
Jazz
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|PhixPicat}}==
<syntaxhighlight lang="picat">interactive =>
<lang Phix>procedure general_fizz_buzz(integer lim, sequence words, sequence facts)
print("> "),
for i=1 to lim do
MaxNum = read_int(),
string word = ""
Map for j=1 to lengthnew_map(facts) do,
print("> "),
if remainder(i,facts[j])=0 then
while (Line = read_line(), Line != "")
word &= words[j]
[N,V] = end ifsplit(Line),
Map.put(N.to_int,V),
end for
print("> ")
if length(word)=0 then
end,
word = sprintf("%d",i)
general_fizzbuzz(MaxNum,Map.to_list.sort),
end if
nl.
printf(1,"%s\n",{word})
 
end for
general_fizzbuzz(N,L) =>
end procedure
FB = [I.to_string : I in 1..N],
general_fizz_buzz(20, {"Fizz","Buzz","Baxx"}, {3,5,7})</lang>
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(" ")).</syntaxhighlight>
 
Testing:
<pre>$ echo "106\n3 Fizz\n5 Buzz\n7 Bazz\n" | picat -g interactive general_fizzbuzz.pi</pre>
 
Here's an interactive session:
{{out}}
<pre>> 106
> 3 Fizz
> 5 Buzz
> 7 Baxx
>
1
2
Line 2,060 ⟶ 3,033:
Buzz
Fizz
Bazz
Baxx
8
Fizz
Line 2,067 ⟶ 3,040:
Fizz
13
Bazz
Baxx
FizzBuzz
16
Line 2,074 ⟶ 3,047:
19
Buzz
FizzBazz
</pre>
22
...
Bazz
Fizz
Buzz
101
Fizz
103
104
FizzBuzzBazz
106</pre>
 
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de general (N Lst)
(for A N
(prinl
Line 2,087 ⟶ 3,073:
A ) ) ) )
 
(general 20 '((3 . Fizz) (5 . Buzz) (7 . Baxx)))</langsyntaxhighlight>
 
{{out}}
Line 2,112 ⟶ 3,098:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$limit = 20
$data = @("3 Fizz","5 Buzz","7 Baxx")
#An array with whitespace as the delimiter
Line 2,130 ⟶ 3,116:
Write-HoSt $outP
}
}</langsyntaxhighlight>
{{Out}}
<pre>PS> ./GENFB
Line 2,154 ⟶ 3,140:
Buzz
PS></pre>
 
=={{header|Prolog}}==
Assuming the user specifies as input two facts of the form:
<syntaxhighlight lang="prolog">maxNumber(105).
factors([(3, "Fizz"), (5, "Buzz"), (7, "Baxx")]).</syntaxhighlight>
 
A simple Prolog solution to the generalised FizzBuzz problem is as follows:
 
<syntaxhighlight lang="prolog">go :- maxNumber(M), factors(Fs), MLast is M+1, loop(1,MLast,Fs).
 
loop(B,B,_).
loop(A,B,Fs) :-
A < B, fizzbuzz(A,Fs,S), ( (S = "", Res is A) ; Res = S ), writeln(Res),
Next is A+1, loop(Next,B,Fs).
 
fizzbuzz(_,[],"").
fizzbuzz(N,[(F,S)|Fs],Res) :-
fizzbuzz(N,Fs,OldRes),
( N mod F =:= 0, string_concat(S,OldRes,Res) ; Res = OldRes ).</syntaxhighlight>
 
The program can be launched by querying the predicate
<syntaxhighlight lang="prolog">?- go.</syntaxhighlight>
 
It is worth noting that
<syntaxhighlight lang="prolog">factors([(3, "Fizz"), (5, "Buzz")]).</syntaxhighlight>
corresponds to basic FizzBuzz and that the proposed solution can handle an arbitrary number of factors.
 
=={{header|Python}}==
 
<lang python>def genfizzbuzz(factorwords, numbers):
===Elegant naive version===
factorwords.sort(key=lambda p: p[0])
 
<syntaxhighlight lang="python">def genfizzbuzz(factorwords, numbers):
# sort entries by factor
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(wrdword for factfactor, wrdword in factorwords if (num % factfactor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
 
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))</langsyntaxhighlight>
 
{{out}}
Line 2,189 ⟶ 3,205:
Buzz</pre>
 
===One-liner using generator expressions===
<syntaxhighlight lang="python">n = 20
mappings = {3: "Fizz", 5: "Buzz", 7: "Baxx"}
for i in range(1, n+1): print(''.join(word * (i % key == 0) for key, word in mappings.items()) or i)</syntaxhighlight>
 
'''Alternative version - generator===Generator using counters instead of modulo'''===
{{works with|Python|3.x}}
<langsyntaxhighlight Pythonlang="python">from collections import defaultdict
 
nN = 100
modsFACTOR_TO_WORD = {
3: "Fizz",
5: "Buzz",
}
 
def fizzbuzz(n=nN, modsfactor_to_word=modsFACTOR_TO_WORD):
 
factors = defaultdict(list)
for mod in mods:
factors[mod].append(mod)
 
for ifactor in range(1,n+1)factor_to_word:
factors[factor].append(factor)
 
for i in range(1, n+1):
res = ''
for modfactor in sorted(factors[.pop(i], ())):
factors[i+modfactor].append(modfactor)
res += modsfactor_to_word[modfactor]
delyield res or factors[i]
yield res or str(i)
 
if __name__ == '__main__':
 
n = int(input())
modsn = { int(k): v for k,v in (input().split(maxsplit=1)'Enter fornumber: _ in range(3')) }
 
mods = {
int(k): v
for k, v in (
input('Enter "<factor> <word>" (without quotes): ').split(maxsplit=1)
for _ in range(3)
)
}
 
for line in fizzbuzz(n, mods):
print(line)
</syntaxhighlight>
</lang>
 
 
===Sieve of Eratosthenes===
'''Another version, using ranges with step 3, 5, etc. Preserves order and duplicate moduli.'''
'''This variant uses ranges with step 3, 5, etc. Preserves order and duplicate moduli.'''
<lang Python>from collections import defaultdict
<syntaxhighlight lang="python">from collections import defaultdict
 
n = 100
Line 2,254 ⟶ 3,284:
 
print(fizzbuzz(n, mods))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,284 ⟶ 3,314:
</pre>
 
=={{header|Quackery}}==
'''First contribution to rosettacode, uses list comprehension to join the lists and args to allow for arbitrary range'''
<lang python>def genfizzbuzz(numberlist, wordlist, *args):
nml = [[numberlist[i], wordlist[i]] for i in range(len(numberlist))]
for z in range(*args):
res = ""
for j in nml:
if z % j[0] == 0:
res += j[1]
print(res or z)
 
<syntaxhighlight lang="Quackery"> [ 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
genfizzbuzz([3, 5, 7], ['Fizz', 'Buzz', 'Baxx'], 1, 21)
' [ [ $ "fizz" 3 ]
</lang>
[ $ "baxx" 7 ]
[ $ "buzz" 5 ] ] generalfizzbuzz
nest$ 60 wrap$ cr</syntaxhighlight>
{{out}}
 
<pre>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</pre>
 
=={{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.
<syntaxhighlight lang="rsplus">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(i in 1:n)
{
isFactor <- i %% factors == 0
print(if(any(isFactor)) paste0(words[isFactor], collapse = "") else i)
}
}
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"))</syntaxhighlight>
 
===Names solution===
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.
<syntaxhighlight lang="rsplus">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
print(if(any(isFactor)) paste0(names(factors)[isFactor], collapse = "") else i)
}
}
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)</syntaxhighlight>
 
=={{header|Racket}}==
{{trans|Python}}
<syntaxhighlight lang="racket">#lang racket/base
 
(define (get-matches num factors/words)
(for*/list ([factor/word (in-list factors/words)]
[factor (in-value (car factor/word))]
[word (in-value (cadr factor/word))]
#:when (zero? (remainder num factor)))
word))
 
(define (gen-fizzbuzz from to factors/words)
(for ([num (in-range from to)])
(define matches (get-matches num factors/words))
(displayln (if (null? matches)
(number->string num)
(apply string-append matches)))))
 
(gen-fizzbuzz 1 21 '((3 "Fizz")
(5 "Buzz")
(7 "Baxx")))</syntaxhighlight>
{{out}}
<pre>1
1
2
Fizz
Line 2,319 ⟶ 3,434:
Fizz
19
Buzz</pre>
</pre>
 
===Alternate Solution===
'''One liner using generator expressions'''
<syntaxhighlight lang="racket">#lang racket
<lang python>n = 20
(require racket/match)
mappings = {3: "Fizz", 5: "Buzz", 7: "Baxx"}
for i in range(1, n+1): print(''.join(word*(i%key==0) for key, word in mappings.items()) or i) </lang>
 
(define (fizz-buzz-individual x . args)
=={{header|Racket}}==
(match (string-append*
{{trans|Python}}
(map (lambda (i)
<lang Racket>#lang racket/base
(match i
[(cons a b) (if (= 0 (modulo x a)) b "")])) args))
["" x]
[fizz-buzz-string fizz-buzz-string]))
 
(define (getfizz-matchesbuzz numx factors/words. args)
(map (curryr (compose displayln (curry apply fizz-buzz-individual)) args)
(for*/list ([factor/word (in-list factors/words)]
(range [factor1 (in-valueadd1 (car factor/wordx)))]
(void))
[word (in-value (cadr factor/word))]
#:when (zero? (remainder num factor)))
word))
 
(fizz-buzz 20 '(3 . "Fizz") '(5 . "Buzz") '(7 . "Baxx"))</syntaxhighlight>
(define (gen-fizzbuzz from to factors/words)
(for ([num (in-range from to)])
(define matches (get-matches num factors/words))
(displayln (if (null? matches)
(number->string num)
(apply string-append matches)))))
 
(gen-fizzbuzz 1 21 '((3 "Fizz")
(5 "Buzz")
(7 "Baxx")))</lang>
{{out}}
<pre>1
Line 2,369 ⟶ 3,476:
19
Buzz</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-20}}
<syntaxhighlight lang="raku" line># General case implementation of a "FizzBuzz" class.
# Defaults to standard FizzBuzz unless a new schema is passed in.
class FizzBuzz {
has $.schema is rw = < 3 Fizz 5 Buzz >.hash;
method filter (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.
sub GeneralFizzBuzz (Int $upto, @schema?) {
my $ping = FizzBuzz.new;
$ping.schema = @schema.hash if @schema;
map { $ping.filter: $_ }, 1 .. $upto;
}
 
# The task
say 'Using: 20 ' ~ <3 Fizz 5 Buzz 7 Baxx>;
.say for GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>);
 
say '';
 
# And for fun
say 'Using: 21 ' ~ <2 Pip 4 Squack 5 Pocketa 7 Queep>;
say join ', ', GeneralFizzBuzz(21, <2 Pip 4 Squack 5 Pocketa 7 Queep>);</syntaxhighlight>
{{Out}}
<pre>Using: 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
 
Using: 21 2 Pip 4 Squack 5 Pocketa 7 Queep
1, Pip, 3, PipSquack, Pocketa, Pip, Queep, PipSquack, 9, PipPocketa, 11, PipSquack, 13, PipQueep, Pocketa, PipSquack, 17, Pip, 19, PipSquackPocketa, Queep</pre>
 
Here's the same program in a more functional idiom:
<syntaxhighlight lang="raku" line>sub genfizzbuzz($n, +@fb) {
[Z~](
do for @fb || <3 fizz 5 buzz> -> $i, $s {
flat ('' xx $i-1, $s) xx *;
}
) Z|| 1..$n
}
 
.say for genfizzbuzz(20, <3 Fizz 5 Buzz 7 Baxx>);</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red ["FizzBuzz"]
 
nmax: to-integer ask "Max number: "
while ["" <> trim rule: ask "New rule (empty to end): "][
append rules: [] load rule
]
repeat n nmax [
res: copy ""
foreach [x blah] rules [
if n % x = 0 [append res blah]
]
print either empty? res [n] [res]
]
halt</syntaxhighlight>
{{Out}}
<pre>Max number: 21
New rule (empty to end): 3 Fizz
New rule (empty to end): 5 Buzz
New rule (empty to end): 7 Baxx
New rule (empty to end):
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
FizzBaxx
(halted)</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$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>;
};</syntaxhighlight>
{{out}}
<tt><i>20<br>
3 Fizz<br>
5 Buzz<br>
7 Baxx<br></i>
<br>
1<br>
2<br>
Fizz<br>
4<br>
Buzz<br>
Fizz<br>
Baxx<br>
8<br>
Fizz<br>
Buzz<br>
11<br>
Fizz<br>
13<br>
Baxx<br>
FizzBuzz<br>
16<br>
17<br>
Fizz<br>
19<br>
Buzz</tt>
 
=={{header|REXX}}==
=== idiomatic version ===
<langsyntaxhighlight lang="rexx">/*REXX program shows a generalized FizzBuzz program: #1 name1 #2 name2 ··· */
parse arg h $ /*obtain optional arguments from the CL*/
if h='' | h="," then h=20 20 /*Not specified? Then use the default.*/
if $='' | $="," then $= "3 Fizz 5 Buzz 7 Baxx" /* " " " " " " */
factors= words($) % 2 /*determine number of factors to use. */
 
do ji=1 forby h;2 for factors _= /*traipse throughparse the numbersnumber factors to be Hused. */
do k#.i=1word($, i); by 2 for words@.i=word($, i+1) % 2 /*obtain the factor " and its " name". factors in J. */
end /*i*/
if j//word($,k)==0 then _=_ || word($,k+1) /*Is it a factor? Then append it to _ */
 
end /*k*/ /* [↑] Note: the factors may be zero.*/
say word(_do j,=1) for h; z= /*displaytraipse through the numbernumbers to or its factorsH. */
end /*j*/ do k=1 by 2 for factors /* " /*stick" a fork in it, " we'refactors all donein J. */</lang>
if j//#.k==0 then z= z || @.k /*Is it a factor? Then append it to Z.*/
'''output''' &nbsp; when using the default inputs:
end /*k*/ /* [↑] Note: the factors may be zero.*/
say word(z j, 1) /*display the number or its factors. */
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
1
Line 2,407 ⟶ 3,713:
</pre>
 
=== optimized version ===
<langsyntaxhighlight lang="rexx">/*REXX program shows a generalized FizzBuzz program: #1 name1 #2 name2 ··· */
parse arg h $ /*obtain optional arguments from the CL*/
if h='' | h="," then h=20 20 /*Not specified? Then use the default.*/
if $='' | $="," then $= "3 Fizz 5 Buzz 7 Baxx" /* " " " " " " */
factors=words($) % 2 /*determine number of factors to use. */
 
do ij=1 byfor 2h; for factors z= /*parsetraipse through the number factorsnumbers to be used H. */
#.ido k=word($,1 i); by 2 @.i=word for words($, i+1)%2 /*obtain the factor and" its "name ". factors in J. */
if j//word($,k)==0 then z= z || word($,k+1) /*Is it a factor? Then append it to Z.*/
end /*i*/
end /*k*/ /* [↑] Note: the factors may be zero.*/
 
say doword(Z j=, 1) for h; _= /*traipse throughdisplay the numbersnumber to or H.its factors. */
end /*j*/ do k=1 by 2 for factors /* " "/*stick a fork in it, " factorswe're all in Jdone. */</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
if j//#.k==0 then _=_ || @.k /*Is it a factor? Then append it to _ */
end /*k*/ /* [↑] Note: the factors may be zero.*/
say word(_ j,1) /*display the number or its factors. */
end /*j*/ /*stick a fork in it, we're all done. */</lang>
'''output''' &nbsp; is identical to the 1<sup>st</sup> REXX version. <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
limit = 20
for n = 1 to limit
Line 2,436 ⟶ 3,737:
next
 
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def general_fizzbuzz(text)
num, *nword = text.split
num = num.to_i
Line 2,456 ⟶ 3,757:
EOS
 
general_fizzbuzz(text)</langsyntaxhighlight>
 
{{out}}
Line 2,484 ⟶ 3,785:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">use std::io;
use std::io::BufRead;
 
Line 2,522 ⟶ 3,823:
}
}
}</langsyntaxhighlight>
 
This solution stores the Fizz Buzz state in a struct, leveraging types and the standard library for a more general solution:
 
<langsyntaxhighlight lang="rust">use std::collections::BTreeMap;
use std::fmt::{self, Write};
use std::io::{self, Stdin};
Line 2,650 ⟶ 3,951:
assert_eq!(expected, &printed);
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
 
{{out|Output for all examples}}
<pre>
$ scala GeneralFizzBuzz.scala
20
3 Fizz
5 Buzz
7 Baxx
^D
 
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
===Simple===
 
<syntaxhighlight lang="scala">import scala.io.{Source, StdIn}
 
object GeneralFizzBuzz extends App {
val max = StdIn.readInt()
val factors = Source.stdin.getLines().toSeq
.map(_.split(" ", 2))
.map(f => f(0).toInt -> f(1))
.sorted
 
(1 to max).foreach { i =>
val words = factors.collect { case (k, v) if i % k == 0 => v }
println(if (words.nonEmpty) words.mkString else i)
}
}</syntaxhighlight>
 
===LazyList (f/k/a Stream)===
 
<syntaxhighlight lang="scala">import scala.io.{Source, StdIn}
 
object GeneralFizzBuzz extends App {
def fizzBuzzTerm(n: Int, factors: Seq[(Int, String)]): String = {
val words = factors.collect { case (k, v) if n % k == 0 => v }
if (words.nonEmpty) words.mkString else n.toString
}
 
def fizzBuzz(factors: Seq[(Int, String)]): LazyList[String] =
LazyList.from(1).map(fizzBuzzTerm(_, factors))
 
val max = StdIn.readInt()
val factors = Source.stdin.getLines().toSeq
.map(_.split(" ", 2))
.map { case Array(k, v) => k.toInt -> v }
.sorted
fizzBuzz(factors).take(max).foreach(println)
}</syntaxhighlight>
 
===Scala 3 (Dotty)===
 
{{trans|LazyList (f/k/a Stream)}}
<syntaxhighlight lang="scala">import scala.io.{Source, StdIn}
 
def fizzBuzzTerm(n: Int, factors: Seq[(Int, String)]): String | Int =
val words = factors.collect { case (k, v) if n % k == 0 => v }
if words.nonEmpty then words.mkString else n
 
def fizzBuzz(factors: Seq[(Int, String)]): LazyList[String | Int] =
LazyList.from(1).map(i => fizzBuzzTerm(i, factors))
 
@main def run(): Unit =
val max = StdIn.readInt()
val factors: Seq[(Int, String)] = Source.stdin.getLines().toSeq
.map(_.split(" ", 2))
.map { case Array(k, v) => k.toInt -> v }
.sorted
fizzBuzz(factors).take(max).foreach(println)</syntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">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;</syntaxhighlight>
{{out}}
<pre>1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz</pre>
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class FizzBuzz(schema=Hash(<3 Fizz 5 Buzz>...)) {
method filter(this) {
var fb = ''
Line 2,671 ⟶ 4,094:
}
 
GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>).each { .say }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,696 ⟶ 4,119:
</pre>
 
=={{header|ScalaSQL}}==
{{works with|ORACLE 19c}}
This is not a particularly efficient solution, but it gets the job done.
 
<syntaxhighlight lang="sql">
<lang Scala>object GenericFizzBuzz extends App {
/*
This code is an implementation of "General FizzBuzz" in SQL ORACLE 19c
*/
select lpad( nvl( case when mod(level, 3) = 0 then 'Fizz' end
|| case when mod(level, 5) = 0 then 'Buzz' end
|| case when mod(level, 7) = 0 then 'Baxx' end
, level)
,12) as output
from dual
connect by level <= 107
;
/
</syntaxhighlight>
 
{{out}}
val max = io.StdIn.readInt()
<pre>
val factors = io.Source.stdin.getLines().toSeq.sorted.map(_.split(" ", 2)).map(f => f(0).toInt -> f(1))
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
FizzBaxx
...
101
Fizz
103
104
FizzBuzzBaxx
106
107
</pre>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="text">import Foundation
 
print("Input max number: ", terminator: "")
 
guard let maxN = Int(readLine() ?? "0"), maxN > 0 else {
1 to max foreach { i =>
fatalError("Please input a number greater than 0")
val words = factors collect { case (k, v) if i % k == 0 => v }
}
println(if (words.nonEmpty) words.mkString else i)
 
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: " ")
}</lang>
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)")
}</syntaxhighlight>
 
{{out}}
<pre>
$ scala GenericFizzBuzz.scala
20
3 Fizz
5 Buzz
7 Baxx
^D
 
<pre>Input max number: 20
Enter a factor and phrase: 3 fizz
Enter a factor and phrase: 5 buzz
Enter a factor and phrase: 7 baxx
1
2
fizz
Fizz
4
buzz
Buzz
fizz
Fizz
baxx
Baxx
8
fizz
Fizz
buzz
Buzz
11
fizz
Fizz
13
baxx
Baxx
fizzbuzz
FizzBuzz
16
17
fizz
Fizz
19
buzz</pre>
Buzz
</pre>
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
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 !
end sayWords
 
[ 1"1"..$input.N -> '$->sayWords;' ] -> \[i](<=''> $i ! <> $ !\) -> '$;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,767 ⟶ 4,265:
For fun, the below implementation is a compatible extension of [[FizzBuzz#Tcl]]:
 
<langsyntaxhighlight Tcllang="tcl">proc fizzbuzz {n args} {
if {$args eq ""} {
set args {{3 Fizz} {5 Buzz}}
Line 2,781 ⟶ 4,279:
}
}
fizzbuzz 20 {3 Fizz} {5 Buzz} {7 Baxx}</langsyntaxhighlight>
 
=={{header|Ursa}}==
This program reads a max number, then reads factors until the user enters a blank line.
<langsyntaxhighlight lang="ursa">#
# general fizzbuzz
#
Line 2,825 ⟶ 4,323:
end if
out endl console
end for</langsyntaxhighlight>
Output:
<pre>>20
Line 2,852 ⟶ 4,350:
19
Buzz</pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 2,887 ⟶ 4,386:
If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True
Loop
End Function</langsyntaxhighlight>
{{out}}
With the entry :
Line 2,941 ⟶ 4,440:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">'The Function
Function FizzBuzz(range, mapping)
data = Array()
Line 2,974 ⟶ 4,473:
y = WScript.StdIn.ReadLine
WScript.StdOut.WriteLine ""
FizzBuzz x, y</langsyntaxhighlight>
{{Out|Sample Run}}
<pre>\Desktop>cscript /nologo fizzbuzz.vbs
Line 3,004 ⟶ 4,503:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Imports System.Globalization
 
Module Program
Line 3,032 ⟶ 4,531:
Next
End Sub
End Module</langsyntaxhighlight>
 
{{out}}
Line 3,059 ⟶ 4,558:
19
Buzz</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">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
}
}</syntaxhighlight>
{{out}}
<pre>Max: 20
Starting factor: 3 Fizz
Next factor: 5 Buzz
Next factor: 7 Baxx
1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout
import "./sort" for Sort
 
var n
 
while (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
}
}
 
var factors = []
var words = {}
for (i in 0..2) {
while (true) {
System.write("Factor %(i+1) : ")
Stdout.flush()
var factor = 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)
var outer = false
while (true) {
System.write(" Word %(i+1) : ")
Stdout.flush()
var word = Stdin.readLine()
if (word.count == 0) {
System.print("Must have at least one character, try again.")
} else {
words[factor] = word
outer = true
break
}
}
if (outer) break
}
}
}
 
Sort.insertion(factors)
System.print()
for (i in 1..n) {
var s = ""
for (j in 0..2) {
var factor = factors[j]
if (i % factor == 0) s = s + words[factor]
}
if (s == "") s = i.toString
System.print(s)
}</syntaxhighlight>
 
{{out}}
<pre>
Maximum number : 20
Factor 1 : 3
Word 1 : Fizz
Factor 2 : 5
Word 2 : Buzz
Factor 3 : 7
Word 3 : Bazz
 
1
2
Fizz
4
Buzz
Fizz
Bazz
8
Fizz
Buzz
11
Fizz
13
Bazz
FizzBuzz
16
17
Fizz
19
Buzz
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">string 0; \use zero-terminated strings
 
proc GetString(S); \Get string (S) from user
char 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);
];
]</syntaxhighlight>
{{out}}
<pre>
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
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">stop:=ask("Count: ").toInt();
fizzBuzzers:=List();
do(3){ n,txt:=ask(">").split(); fizzBuzzers.append(T(n.toInt(),txt)) }
Line 3,067 ⟶ 4,774:
s:=fizzBuzzers.filter('wrap([(fb,txt)]){ n%fb==0 }).apply("get",1).concat();
println(s or n);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,099 ⟶ 4,806:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 INPUT "Maximum number: ";max
20 INPUT "Number of factors: ";n
30 DIM f(n): DIM w$(n,4)
Line 3,113 ⟶ 4,820:
130 PRINT
140 NEXT i
150 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
2,115

edits