General FizzBuzz: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 57:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F genfizzbuzz(factorwords, numbers)
V sfactorwords = sorted(factorwords, key' p -> p[0])
[String] lines
Line 65:
R lines.join("\n")
 
print(genfizzbuzz([(5, ‘Buzz’), (3, ‘Fizz’), (7, ‘Baxx’)], 1..20))</langsyntaxhighlight>
 
{{out}}
Line 92:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE MAX_NUMBERS="200"
DEFINE MAX_LEN="20"
DEFINE MAX_FACTORS="5"
Line 184:
PutE()
PrintResult(max,n,factors,texts)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/General_FizzBuzz.png Screenshot from Atari 8-bit computer]
Line 202:
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
Line 253:
general_fizz_buzz (20, fizzy);
end Main;
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 280:
=={{header|ALGOL 68}}==
Uses a modified version of the Algol 68 Quicksort task sample.
<langsyntaxhighlight lang="algol68">BEGIN # generalised FizzBuzz #
# prompts for an integer, reads it and returns it #
PROC read integer = ( STRING prompt )INT:
Line 356:
print( ( text, newline ) )
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 390:
=={{header|AppleScript}}==
 
<langsyntaxhighlight AppleScriptlang="applescript">--------------------- GENERAL FIZZBUZZ -------------------
 
-- fizzEtc :: [(Int, String)] -> [Symbol]
Line 516:
set my text item delimiters to dlm
s
end unlines</langsyntaxhighlight>
{{Out}}
<pre>1
Line 541:
=={{header|Arturo}}==
 
<langsyntaxhighlight 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 [
Line 551:
]
print (printNum)? -> i -> ""
]</langsyntaxhighlight>
 
{{out}}
Line 581:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">; Test parameters
max := 20, fizz := 3, buzz := 5, baxx := 7
 
Line 597:
FileAppend %output%`n, *
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 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 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
set /p "range=> "
Line 710:
)
pause
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>> 20
Line 741:
=={{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 760:
NEXT
IF matched% THEN PRINT ELSE PRINT;i%
NEXT</langsyntaxhighlight>
Output:
<pre>Maximum number: 20
Line 789:
 
=={{header|BQN}}==
<langsyntaxhighlight BQNlang="bqn">GenFizzBuzz ← {factors‿words ← <˘⍉>𝕨 ⋄ (∾´∾⟜words/˜·(¬∨´)⊸∾0=factors|⊢)¨1+↕𝕩}</langsyntaxhighlight>
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" ⟩</langsyntaxhighlight>
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 849:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 876:
=={{header|C sharp}}==
Not extremely clever and doesn't use anything too fancy.
<langsyntaxhighlight lang="csharp">
using System;
 
Line 937:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <algorithm>
#include <iostream>
Line 978:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,004:
 
=={{header|Caché ObjectScript}}==
<langsyntaxhighlight Cachélang="caché ObjectScriptobjectscript">GENFIZBUZZ(MAX,WORDS,NUMBERS)
; loop until max, casting numeric to avoid errors
for i=1:1:+MAX {
Line 1,025:
} ; next value until MAX
quit</langsyntaxhighlight>
 
 
Line 1,032:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
print("enter the max value");
Line 1,071:
}
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(defn fix [pairs]
(map second pairs))
 
Line 1,088:
(apply str
(fix f)))))
numbers)))</langsyntaxhighlight>
 
'''Usage:'''
Line 1,119:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
<lang Lisp>
(defun fizzbuzz (limit factor-words)
(loop for i from 1 to limit
Line 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">
<lang Crystal>
counter = 0
 
Line 1,201:
exit
end
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import core.stdc.stdlib;
import std.stdio;
 
Line 1,252:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,283:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule General do
def fizzbuzz(input) do
[num | nwords] = String.split(input)
Line 1,301:
7 Baxx
"""
General.fizzbuzz(input)</langsyntaxhighlight>
 
{{out}}
Line 1,336:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
%%% @doc Implementation of General FizzBuzz
%%% @see https://rosettacode.org/wiki/General_FizzBuzz
Line 1,362:
[fizzbuzz(X, Factors, []) || X <- lists:seq(1, N)]
).
</syntaxhighlight>
</lang>
'''Usage:'''
<pre>
Line 1,396:
 
=={{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 1,416:
: main ( -- ) get-input [ fizzbuzz ] with each ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,448:
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 1,473:
\ Example:
\ 1 fb[ 3 s" fizz" ]+[ 5 s" buzz" ]+[ 7 s" dizz" ]+[ ]fb 40 times drop
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,484:
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="freebasic">' version 01-03-2018
' compile with: fbc -s console
 
Line 1,542:
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,572:
 
=={{header|Go}}==
<syntaxhighlight lang="go">
<lang Go>
package main
 
Line 1,606:
}
 
}</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,615:
:(value+'\n')}
println log
</syntaxhighlight>
</lang>
<pre>
1
Line 1,661:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">fizz :: (Integral a, Show a) => a -> [(a, String)] -> String
fizz a xs
| null result = show a
Line 1,677:
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) ---------------
Line 1,704:
main :: IO ()
main = mapM_ putStrLn $ take 20 fizzTest
</syntaxhighlight>
</lang>
{{Out}}
<pre>1
Line 1,731:
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,759:
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,780:
├┼┼────┼┼────┼────┼────┼┼────┼────┼┼────┼┼────┼────┼┼┼────┼┼────┤
│││ ││ │ │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,813:
}
 
}</langsyntaxhighlight>
 
 
Line 1,826:
 
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,834:
}, "") || a.toString()) + "\n";
}, "");
}</langsyntaxhighlight>
 
and then in the original expanded form, for better legibility:
 
<langsyntaxhighlight JavaScriptlang="javascript">function fizz(lstRules, lngMax) {
 
return (
Line 1,863:
}
 
fizz([[3, 'Fizz'], [5, 'Buzz'], [7, 'Baxx']], 20);</langsyntaxhighlight>
 
{{out}}
Line 1,890:
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">// range :: Int -> Int -> [Int]
const range = (min, max) =>
Array.from({ length: max - min }, (_, i) => min + i)
Line 1,908:
).join('\n')
 
console.log(fizzBuzz(20))</langsyntaxhighlight>
 
{{Out}}
Line 1,936:
=={{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,964:
 
println("EOF\n")
fizzbuzz(triggers, upper)</langsyntaxhighlight>
 
{{out}}
Line 1,998:
=={{header|Kotlin}}==
 
<langsyntaxhighlight Kotlinlang="kotlin">fun main(args: Array<String>) {
 
//Read the maximum number, set to 0 if it couldn't be read
Line 2,025:
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 2,049:
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 2,071:
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 2,110:
print(fizzbuzz(n, mods))
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,130:
 
===Fast Version without Modulo===
<langsyntaxhighlight lang="lua">#!/usr/bin/env luajit
 
local num = arg[1] or tonumber(arg[1]) or 110
Line 2,160:
io.write(", ")
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,168:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">findNum := proc(str) #help parse input
local i;
i := 1:
Line 2,199:
if (not factored) then printf("%d", i): end if:
printf("\n");
end do:</langsyntaxhighlight>
{{Out|Output}}
<pre>1
Line 2,223:
 
=={{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 2,255:
This implementation improves slightly over the proposed task, making the prompts a little friendlier.
 
<langsyntaxhighlight MiniScriptlang="miniscript">factorWords = {}
 
maxNr = val(input("Max number? "))
Line 2,278:
end for
if matchingWords then print matchingWords else print nr
end for</langsyntaxhighlight>
 
Sample session:
Line 2,308:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE GeneralFizzBuzz;
FROM Conversions IMPORT StrToInt;
FROM FormatString IMPORT FormatString;
Line 2,410:
 
ReadChar
END GeneralFizzBuzz.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Ursa}}
<langsyntaxhighlight Nanoquerylang="nanoquery">factors = {}
words = {}
 
Line 2,447:
end
println
end</langsyntaxhighlight>
 
{{out}}
Line 2,478:
=={{header|Nim}}==
This solution has no input validation
<langsyntaxhighlight lang="nim">
import parseutils, strutils, algorithm
 
Line 2,524:
 
 
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Original version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
<syntaxhighlight lang="ocaml">
<lang OCaml>
(* Task : General_FizzBuzz *)
 
Line 2,561:
 
gen_fizz_buzz 20 [(3, "Fizz"); (5, "Buzz"); (7, "Baxx")] ;;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,589:
{{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 2,603:
);
}
fizz(20,[3,"Fizz"],[5,"Buzz"],[7,"Baxx"])</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,627:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">
#!bin/usr/perl
use 5.020;
Line 2,679:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,714:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
<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>
Line 2,730:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,756:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
 
$max = 20;
Line 2,772:
}
 
?></langsyntaxhighlight>
{{out}}
<pre>1
Line 2,797:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">interactive =>
print("> "),
MaxNum = read_int(),
Line 2,818:
end
end,
println([F : F in FB].join(" ")).</langsyntaxhighlight>
 
Testing:
Line 2,866:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de general (N Lst)
(for A N
(prinl
Line 2,876:
A ) ) ) )
 
(general 20 '((3 . Fizz) (5 . Buzz) (7 . Baxx)))</langsyntaxhighlight>
 
{{out}}
Line 2,901:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$limit = 20
$data = @("3 Fizz","5 Buzz","7 Baxx")
#An array with whitespace as the delimiter
Line 2,919:
Write-HoSt $outP
}
}</langsyntaxhighlight>
{{Out}}
<pre>PS> ./GENFB
Line 2,946:
=={{header|Prolog}}==
Assuming the user specifies as input two facts of the form:
<langsyntaxhighlight lang="prolog">maxNumber(105).
factors([(3, "Fizz"), (5, "Buzz"), (7, "Baxx")]).</langsyntaxhighlight>
 
A simple Prolog solution to the generalised FizzBuzz problem is as follows:
 
<langsyntaxhighlight lang="prolog">go :- maxNumber(M), factors(Fs), MLast is M+1, loop(1,MLast,Fs).
 
loop(B,B,_).
Line 2,961:
fizzbuzz(N,[(F,S)|Fs],Res) :-
fizzbuzz(N,Fs,OldRes),
( N mod F =:= 0, string_concat(S,OldRes,Res) ; Res = OldRes ).</langsyntaxhighlight>
 
The program can be launched by querying the predicate
<syntaxhighlight lang ="prolog">?- go.</langsyntaxhighlight>
 
It is worth noting that
<langsyntaxhighlight lang="prolog">factors([(3, "Fizz"), (5, "Buzz")]).</langsyntaxhighlight>
corresponds to basic FizzBuzz and that the proposed solution can handle an arbitrary number of factors.
 
Line 2,974:
===Elegant naive version===
 
<langsyntaxhighlight lang="python">def genfizzbuzz(factorwords, numbers):
# sort entries by factor
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
Line 2,984:
 
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))</langsyntaxhighlight>
 
{{out}}
Line 3,009:
 
===One-liner using generator expressions===
<langsyntaxhighlight 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)</langsyntaxhighlight>
 
===Generator using counters instead of modulo===
{{works with|Python|3.x}}
<langsyntaxhighlight Pythonlang="python">from collections import defaultdict
 
N = 100
Line 3,051:
for line in fizzbuzz(n, mods):
print(line)
</syntaxhighlight>
</lang>
 
===Sieve of Eratosthenes===
'''This variant uses ranges with step 3, 5, etc. Preserves order and duplicate moduli.'''
<langsyntaxhighlight Pythonlang="python">from collections import defaultdict
 
n = 100
Line 3,087:
 
print(fizzbuzz(n, mods))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,119:
===... 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.
<langsyntaxhighlight lang="rsplus">genFizzBuzz <- function(n, ...)
{
args <- list(...)
Line 3,136:
}
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"))</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="rsplus">namedGenFizzBuzz <- function(n, namedNums)
{
factors <- sort(namedNums)#Required by the task: We must go from least factor to greatest.
Line 3,152:
namedGenFizzBuzz(105, namedNums)
shuffledNamedNums <- c(Buzz=5, Prax=9, Fizz=3, Baxx=7)
namedGenFizzBuzz(105, shuffledNamedNums)</langsyntaxhighlight>
 
=={{header|Racket}}==
{{trans|Python}}
<langsyntaxhighlight Racketlang="racket">#lang racket/base
 
(define (get-matches num factors/words)
Line 3,174:
(gen-fizzbuzz 1 21 '((3 "Fizz")
(5 "Buzz")
(7 "Baxx")))</langsyntaxhighlight>
{{out}}
<pre>1
Line 3,198:
 
===Alternate Solution===
<langsyntaxhighlight Racketlang="racket">#lang racket
(require racket/match)
 
Line 3,214:
(void))
 
(fizz-buzz 20 '(3 . "Fizz") '(5 . "Buzz") '(7 . "Baxx"))</langsyntaxhighlight>
 
{{out}}
Line 3,241:
(formerly Perl 6)
{{works with|rakudo|2015-09-20}}
<syntaxhighlight lang="raku" perl6line># General case implementation of a "FizzBuzz" class.
# Defaults to standard FizzBuzz unless a new schema is passed in.
class FizzBuzz {
Line 3,268:
# 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>);</langsyntaxhighlight>
{{Out}}
<pre>Using: 20 3 Fizz 5 Buzz 7 Baxx
Line 3,296:
 
Here's the same program in a more functional idiom:
<syntaxhighlight lang="raku" perl6line>sub genfizzbuzz($n, +@fb) {
[Z~](
do for @fb || <3 fizz 5 buzz> -> $i, $s {
Line 3,304:
}
 
.say for genfizzbuzz(20, <3 Fizz 5 Buzz 7 Baxx>);</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red ["FizzBuzz"]
 
nmax: to-integer ask "Max number: "
Line 3,320:
print either empty? res [n] [res]
]
halt</langsyntaxhighlight>
{{Out}}
<pre>Max number: 21
Line 3,352:
=={{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 /*Not specified? Then use the default.*/
Line 3,367:
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. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 3,393:
 
=== 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 /*Not specified? Then use the default.*/
Line 3,403:
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. */</langsyntaxhighlight>
{{out|output|text=&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 3,416:
next
 
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def general_fizzbuzz(text)
num, *nword = text.split
num = num.to_i
Line 3,436:
EOS
 
general_fizzbuzz(text)</langsyntaxhighlight>
 
{{out}}
Line 3,464:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">use std::io;
use std::io::BufRead;
 
Line 3,502:
}
}
}</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 3,630:
assert_eq!(expected, &printed);
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 3,667:
===Simple===
 
<langsyntaxhighlight Scalalang="scala">import scala.io.{Source, StdIn}
 
object GeneralFizzBuzz extends App {
Line 3,680:
println(if (words.nonEmpty) words.mkString else i)
}
}</langsyntaxhighlight>
 
===LazyList (f/k/a Stream)===
 
<langsyntaxhighlight Scalalang="scala">import scala.io.{Source, StdIn}
 
object GeneralFizzBuzz extends App {
Line 3,701:
.sorted
fizzBuzz(factors).take(max).foreach(println)
}</langsyntaxhighlight>
 
===Scala 3 (Dotty)===
 
{{trans|LazyList (f/k/a Stream)}}
<langsyntaxhighlight Scalalang="scala">import scala.io.{Source, StdIn}
 
def fizzBuzzTerm(n: Int, factors: Seq[(Int, String)]): String | Int =
Line 3,721:
.map { case Array(k, v) => k.toInt -> v }
.sorted
fizzBuzz(factors).take(max).foreach(println)</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class FizzBuzz(schema=Hash(<3 Fizz 5 Buzz>...)) {
method filter(this) {
var fb = ''
Line 3,742:
}
 
GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>).each { .say }</langsyntaxhighlight>
{{out}}
<pre>
Line 3,771:
This is not a particularly efficient solution, but it gets the job done.
 
<syntaxhighlight lang="sql">
<lang SQL>
/*
This code is an implementation of "General FizzBuzz" in SQL ORACLE 19c
Line 3,784:
;
/
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,821:
=={{header|Swift}}==
 
<syntaxhighlight lang="text">import Foundation
 
print("Input max number: ", terminator: "")
Line 3,858:
 
print("\(factors.isEmpty ? String(i) : factors)")
}</langsyntaxhighlight>
 
{{out}}
Line 3,888:
 
=={{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'}]};
 
Line 3,902:
[ 1"1"..$input.N -> '$->sayWords;' ] -> \[i](<=''> $i ! <> $ !\) -> '$;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,913:
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 3,927:
}
}
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 3,971:
end if
out endl console
end for</langsyntaxhighlight>
Output:
<pre>>20
Line 4,000:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 4,034:
If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True
Loop
End Function</langsyntaxhighlight>
{{out}}
With the entry :
Line 4,088:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">'The Function
Function FizzBuzz(range, mapping)
data = Array()
Line 4,121:
y = WScript.StdIn.ReadLine
WScript.StdOut.WriteLine ""
FizzBuzz x, y</langsyntaxhighlight>
{{Out|Sample Run}}
<pre>\Desktop>cscript /nologo fizzbuzz.vbs
Line 4,151:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Imports System.Globalization
 
Module Program
Line 4,179:
Next
End Sub
End Module</langsyntaxhighlight>
 
{{out}}
Line 4,208:
 
=={{header|Vlang}}==
<langsyntaxhighlight lang="vlang">import os
fn main() {
Line 4,237:
divisible = false
}
}</langsyntaxhighlight>
{{out}}
<pre>Max: 20
Line 4,267:
=={{header|Wren}}==
{{libheader|Wren-sort}}
<langsyntaxhighlight lang="ecmascript">import "io" for Stdin, Stdout
import "/sort" for Sort
 
Line 4,322:
if (s == "") s = i.toString
System.print(s)
}</langsyntaxhighlight>
 
{{out}}
Line 4,357:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">stop:=ask("Count: ").toInt();
fizzBuzzers:=List();
do(3){ n,txt:=ask(">").split(); fizzBuzzers.append(T(n.toInt(),txt)) }
Line 4,363:
s:=fizzBuzzers.filter('wrap([(fb,txt)]){ n%fb==0 }).apply("get",1).concat();
println(s or n);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,395:
=={{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 4,409:
130 PRINT
140 NEXT i
150 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
10,333

edits