Generalized FizzBuzz

FizzBuzz, but instead of 3 and 5, you'll take the numbers and corresponding strings as input.

You can assume all inputted numbers are coprime (and $$\\ge 2\$$). You'll receive one or more numbers, and a string to print with each of them. The normal FizzBuzz would be something like [[3, "Fizz"], [5, "Buzz"]], but you could also receive something like [[2, "Quux"]] or [[2, "a"], [5, "b"], [7, "c"], [33, "d"], [529, "e"]].

For output, you'll have two options:

• Print this modified FizzBuzz infinitely
• Take a number as input, and return the first $$\n\$$ lines

You must return output with newline separators. An array of lines is not acceptable.

Details

To clarify exactly what this should look like, this is the process to determine what the $$\n\$$th line should look like (first line is always $$\1\$$):

1. For each of the inputted numbers $$\n\$$ is divisble by, append the corresponding string to the output (for example, $$\15\$$ would result in "Fizz" + "Buzz" = "FizzBuzz" for normal FizzBuzz)
2. If $$\n\$$ is not divisble by any of the numbers (i.e., the line is still empty), default to $$\n\$$

For example, the first 100 lines of the sample input [[4, "Foo"], [7, "Bar"], [9, "Baz"]] are:

1
2
3
Foo
5
6
Bar
Foo
Baz
10
11
Foo
13
Bar
15
Foo
17
Baz
19
Foo
Bar
22
23
Foo
25
26
Baz
FooBar
29
30
31
Foo
33
34
Bar
FooBaz
37
38
39
Foo
41
Bar
43
Foo
Baz
46
47
Foo
Bar
50
51
Foo
53
Baz
55
FooBar
57
58
59
Foo
61
62
BarBaz
Foo
65
66
67
Foo
69
Bar
71
FooBaz
73
74
75
Foo
Bar
78
79
Foo
Baz
82
83
FooBar
85
86
87
Foo
89
Baz
Bar
Foo
93
94
95
Foo
97
Bar
Baz
Foo

I/O

You can take input in any reasonable format. This includes dicts of numbers and their strings, a single list of pairs (like in the examples), two lists (one with numbers and ones with pairs), or similar.

For instances where there's two strings being appended, such as FooBar in the example above, any order is acceptable (BarFoo is also fine).

Other

This is , so shortest answer in bytes (per language) wins!

• Welcome to Code Golf Stack Exchange! It’s recommended to post challenges in the Sandbox first in order to get feedback
– rues
Aug 10 at 3:14
• @user You too! Nice to meet ya :p Aug 10 at 3:14
• Is trailing whitepace before the newline acceptable? Aug 11 at 1:44
• @Jonah Sure, that's fine Aug 11 at 3:18

Jelly, 8 bytes

⁴ḍTị⁵ȯ)Y

Try it online!

Full program that takes $$\n\$$, the list of numbers $$\L\$$ and the list of strings $$\S\$$ as command line argument, and returns a newline separated string

How it works

⁴ḍTị⁵ȯ)Y - Main link. Takes n on the left, L as ⁴ and S as ⁵
)  - Over each integer 1 ≤ i ≤ n:
⁴ḍ       -   Map each element in L to 1 if i is divisible by it, else 0
T      -   Indices of 1s
ị⁵    -   Select the elements of S at those indices
ȯ   -   If this is the empty list, replace it with i
Y - Join on newlines
• Golfing languages are majorly impressive and look difficult to use, but I can't help the impression that I've opened a corrupted file whenever I see them.
– Lou
Aug 11 at 11:02
• @Lou And this is what they look like where the creators chose what the bytes look like. If you encode this as UTF-8, it looks even worse: Try it online! (doesn't actually work) Aug 13 at 18:57

K (ngn/k), 29 bytes

{{$[a:&~x!'y;,/a;y]}[x]'1+!y} Try it online! Takes a dict with (string, number) pairs. Explanation {{$[a:&~x!'y;,/a;y]}[x]'1+!y}
1+!y  range 1..y
'      for each number
[x]       with x as constant first argument:

Try it online!

Charcoal, 19 bytes

Ｅθ∨⭆η⎇﹪⊕ι§λ⁰ω§λ¹Ｉ⊕ι

Try it online! Link is to verbose version of code. Prints the first n terms. Explanation:

θ                  Input n
Ｅ                   Map over implicit range
η               Input list of pairs
⭆                Map over pairs and join
ι           Outer index
⊕            Incremented
﹪             Modulo
§λ⁰        First element of pair
⎇              If non-zero then
ω       Empty string
§λ¹    Else second element of pair
∨                 Logical Or
ι Current index
⊕  Incremented
Ｉ   Cast to string
Implicitly print on separate lines

Note: Using trunk Charcoal (not available on TIO) this would be only 15 bytes:

Ｅθ∨⭆η⎇﹪⊕ιμωλＩ⊕ι

Explanation: Takes the input as a dict, which means that iterating over it populates the loop variables directly without having to index into the pairs.

R, 76 64 bytes

-12 bytes thanks to @Dominic

function(N,S)repeat{F=F+1;cat(F[all(k<-F%%N)],S[!k],"
",sep="")}

Try it online!

Takes vectors of Numbers and corresponding Strings.

Outputs infinitely.

• Or only 64 bytes...? Aug 11 at 9:36
• @Dominic, thanks a lot! So I thought that clever indexing could save some bytes, but I couldn't make it work. And repeat is something I always forget about. Aug 11 at 10:56

Python 2, 63 bytes

def f(k,i=1):
print''.join(y*(i%x<1)for x,y in k)or i;f(k,i+1)

Attempt This Online!

-1 bytes thanks to @dingledooper

-3 bytes thanks to @pxeger

• Outputting up to hardcoded 100 is not allowed. (Allowed outputs: output forever, or take n and output first n lines) Aug 10 at 4:20
• @Bubbler edited, outputs forever now Aug 10 at 4:23
• i%x<1 should work too. Aug 10 at 4:51
• -3 bytes with a recursive function Aug 10 at 6:56
• Everything can go on one line.
– xnor
Aug 12 at 8:12

Java (JDK), 109 bytes

l->{for(int i=1;;i++){var s="";for(var e:l)if(i%e.getKey()<1)s+=e.getValue();System.out.println(s==""?i:s);}}

Try it online!

Notes

The s=="" works here because of the constants pool: the two references to the empty string are actually one reference and have the same address in memory. s==new String("") wouldn't have worked for instance.

Julia 0.7, 59 bytes

N\d=1:N.|>n->println((a=prod(p->p[2]^(n%p[1]<1),d))>""?a:n)

Try it online!

Python 3, 65 bytes

f=lambda a,n=1:print(''.join(j*(n%i<1)for i,j in a)or n)+f(a,n+1)

Try it online!

-1 byte thanks to MarcMush

• -1 byte by replacing 0**(n%i) with (n%i<1) Aug 10 at 13:03

J, 48 bytes

1 :'(|:@([:(,0=+/)0=u|/]);@#"1(,"#:<@":"+))1+i.'

Try it online!

This was bizarrely difficult to golf in J.

Bash, 10080 75 bytes

-20 bytes thanks to @Dude coinheringaahing

-5 bytes and extra readability thanks to @Jonah

for((i=1;;i++));{
o=
for a;{((0==i%${a% *}))&&o=$o${a#* };} echo${o:-$i} } Try it online! Takes arguments as strings in the form '$num $str' and uses variable expansion to split them out into their component parts. Outputs infinitely. I'm pretty sure this one has lots of potential for further golfing, but I'll take an even 100 for my first submission. • Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in Bash page for ways you can golf your program Aug 11 at 19:06 • Nice approach, especially the use of default value expansion to handle the i case. -5 bytes by noting that the ((..)) construct returns a true exit status for non-zero numbers and so can be used directly and thereby avoid test [: Try it online! (I also added line breaks for readability when it cost no extra bytes) Aug 12 at 1:37 Scala, 94 bytes b=>1 to _ map(x=>println(Seq(b.collect{case(k,s)if x%k<1=>s},Seq(x))maxBy(_.size)mkString "")) Try it online! Outputs the first n lines of the sequence. b => //A Map with the keys being divisors (4, 7, 9) and the values being strings ("Foo", "Fizz", etc.) 1 to _ //Make a range to n map(x=> //For each x in the range, output either "x" or a string made from its divisors println( //Print with newline Seq( //Make a Seq with the two alternatives ^ b.collect{ //The Fizz, Buzz, FizzBuzz alternative case(k,s) //For every divisor k and its accompanying string s, if x%k<1 //If k divides x =>s}, //Add s to this alternative Seq(x) //The second alternative is just the number itself ) maxBy(_.size) //Find the alternative with more elements (if both have 1, the first is chosen) mkString "" //Join into a single string ) ) • Could you save bytes by using short-circuiting logical or - something like concatenate(b.collect{case(k,s)if x%k<1=>s}) || x)? (With appropriate functions, I don't know scala) Aug 13 at 22:08 • @emanresuA I don't see how that would work? Logical or isn't going to work on a Seq and an Int. <s>Also, what's concatenate?</s> – rues Aug 13 at 22:10 • Oh, does Scala not have that? Ok. (By concatenate I meant whatever function scala has to reduce a list by addition.) Aug 13 at 22:11 • I'm not sure what it doesn't have, but whatever it is, no, it doesn't have it :). – rues Aug 13 at 22:14 05AB1E, 12 bytes ∞ε¹ÖÏJy‚õKн, Integers and strings as two separated input-lists. Outputs the infinite sequence. Try it online. Explanation: ∞ # Push an infinite positive list: [1,2,3,...] ε # Foreach y over these integers: ¹Ö # Check for each integer in the first input-list whether it divides the # current integer Ï # Get the strings of the second (implicit) input-list at the truthy indices J # Join this list of strings (it's now "" if none were divisible) y‚ # Pair it with the current integer y õK # Remove empty strings from this pair н # Pop and leave the first item , # And print it with trailing newline CSASM v2.5.1, 317 bytes func a: .local a : i32 push 1 add pop$3
pop $2 dup len pop$4
pop $1 lda 1 .lbl a push 0 pop a push -1 pop$5
push $a push 1 sub brfalse c .lbl b inc$5
push $5 push$4
sub
brfalse c
push $a push$1
ldelem $5 rem brtrue b push 1 pop a push$2
ldelem $5 print br b .lbl c push a brtrue d push$a
print
.lbl d
push '\n'
print
inc $a push$a
push $3 sub brtrue a ret end A function named a which expects an ~arr:i32 for the values, an ~arr:str for the names and an i32 representing $$\n\$$ on the stack, pushed in that order specifically. Explanation: func a: ; Used as the flag for if a string was printed .local a : i32 ; stack: [ values array, strings array, amount to print ] push 1 add pop$3
pop $2 ; Duplicate "values array", get its length and store it into$4
dup
len
pop $4 pop$1

; $1 = values,$2 = strings, $3 = final number ; Initialize$a to 1
lda 1

.lbl a
; Reset the "string printed" flag
push 0
pop a

; Reset the "numbers array" iteration
push -1
pop $5 ; If$a == 1, skip to the end
push $a push 1 sub brfalse c .lbl b inc$5
push $5 push$4
sub
brfalse c

; Loop through each value in the numbers array and check if a$% them is zero ; If they are, print that string push$a
push $1 ldelem$5
rem
brtrue b

; Modulo was zero
push 1
pop a

push $2 ldelem$5
print
br b
.lbl c
push a
brtrue d
; Print the current number
push $a print .lbl d ; Print the newline push '\n' print ; Loop while$a != $3 inc$a
push $a push$3
sub
brtrue a
ret
end

Sample Program:

func main:
push $i32:[3,5] push 2 newarr str pop$a

push $a push "Fizz" stelem 0 push$a
push "Buzz"
stelem 1

push \$a
push 30

call a

ret
end

; "func a" would be defined here

Python 3, 122 bytes

exec("g="+input())
n=1
while 1:
b=1
for k,v in g:
if n%k<1:
print(v,end='')
b=0
print(n)if b else print()
n+=1

Input:

((4, "Foo"), (7, "Bar"), (9, "Baz"))

Try it online!

Fairly obvious way of going about the challenge. Using a tuple of tuples saves 1 byte over a dict. Looking at the other python submissions, I realize I missed a lot of optimizations. Lessons to bring to the next code golf, I hope.

• Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in Python page for ways you can golf your program. You can save 21 bytes by using a function instead Aug 29 at 14:35
• I think that g=eval(input()) should be shorter thatn your current method of getting input. Aug 30 at 9:00
• You can also combine all the print statements into one: Try it online! Aug 30 at 9:00