25
\$\begingroup\$

Task

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!

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

20 Answers 20

10
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – Lou
    Aug 11, 2021 at 11:02
  • \$\begingroup\$ @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) \$\endgroup\$ Aug 13, 2021 at 18:57
6
\$\begingroup\$

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:
 {$[              ]}           if:
        x!'y                    the values of x mod y
       ~                        logical NOTed
      &                         filter out keys which have truthy values
    a:                          store in a
            ;,/a                return a if non-empty
                ;y              otherwise return number y
\$\endgroup\$
6
\$\begingroup\$

Haskell, 69 bytes

[]%n=show n
x%_=x>>=id
f a=unlines[[y|(x,y)<-a,mod i x<1]%i|i<-[1..]]

Try it online!

f [(3, "Fizz"), (5, "Buzz"), (10, "Boom")] is an infinite string with newlines in it.

\$\endgroup\$
5
\$\begingroup\$

JavaScript (V8), 59 bytes

Prints the sequence forever.

a=>{for(k=0;++k;)print(a.map(([m,s])=>k%m?'':s).join``||k)}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ print ? what the heck is print? I've never seen that in JS??? \$\endgroup\$
    – Caltor
    Aug 12, 2021 at 21:58
  • 1
    \$\begingroup\$ @Caltor This is a V8 thing, not ECMAScript. \$\endgroup\$
    – Arnauld
    Aug 13, 2021 at 8:10
4
\$\begingroup\$

Vyxal, 8 bytes

ƛ¹Ḋ⁰*∑∴,

Try it Online!

Since y'all complaining about flags, I'll give you a tie with jelly.

Expects Limit, Divisors, Strings

Explained

ƛ¹Ḋ⁰*∑∴,
ƛ        # for each n in the range [1, L]:
 ¹Ḋ      #     Push n % D == 0 (epicly vectorised)
   ⁰*    #     Push ^ * S (which is vectorised python string multiplication) 
     ∑∴  #     Push max(sum(^), n)
       , #     and print ^ with a newline

This would be 7 with the j flag

\$\endgroup\$
3
  • 4
    \$\begingroup\$ +1 for not using j (wait no you went and did it >:|) \$\endgroup\$ Aug 10, 2021 at 3:12
  • 2
    \$\begingroup\$ @RedwolfPrograms get epicly pranked \$\endgroup\$
    – lyxal
    Aug 10, 2021 at 3:13
  • 2
    \$\begingroup\$ @RedwolfPrograms get epicly pranked again \$\endgroup\$
    – lyxal
    Aug 10, 2021 at 3:37
4
\$\begingroup\$

Japt -R, 14 bytes

õ@VËÌpXvDÎìªX

Try it

õ@VËÌpXvDÎìªX     :Implicit input of integer U & array V
õ                  :Range [1,U]
 @                 :Map each X
  VË               :  Map each D in V
    Ì              :    Last element
     p             :    Repeat
      Xv           :      Is X divisible by
        DÎ         :      First element of D
          Ã        :  End map
           ¬       :  Join
            ªX     :  Logical OR with X
                   :Implicit output joined with newlines
\$\endgroup\$
4
\$\begingroup\$

Perl 5, 56 bytes

sub{say join('',map$.%$$_[0]?'':$$_[1],@_)||$.while++$.}

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Charcoal, 19 bytes

Eθ∨⭆η⎇﹪⊕ι§λ⁰ω§λ¹I⊕ι

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

 θ                  Input `n`
E                   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
                I   Cast to string
                    Implicitly print on separate lines

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

Eθ∨⭆η⎇﹪⊕ιμωλI⊕ι

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Or only 64 bytes...? \$\endgroup\$ Aug 11, 2021 at 9:36
  • \$\begingroup\$ @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. \$\endgroup\$
    – pajonk
    Aug 11, 2021 at 10:56
4
\$\begingroup\$

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

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

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.

Credits

\$\endgroup\$
0
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ -1 byte by replacing 0**(n%i) with (n%i<1) \$\endgroup\$
    – MarcMush
    Aug 10, 2021 at 13:03
3
\$\begingroup\$

J, 48 bytes

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

Try it online!

This was bizarrely difficult to golf in J.

\$\endgroup\$
3
\$\begingroup\$

Bash, 100 80 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.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 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 \$\endgroup\$ Aug 11, 2021 at 19:06
  • 1
    \$\begingroup\$ 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) \$\endgroup\$
    – Jonah
    Aug 12, 2021 at 1:37
3
\$\begingroup\$

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
  )
 )
\$\endgroup\$
4
  • \$\begingroup\$ 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) \$\endgroup\$
    – emanresu A
    Aug 13, 2021 at 22:08
  • \$\begingroup\$ @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> \$\endgroup\$
    – user
    Aug 13, 2021 at 22:10
  • \$\begingroup\$ Oh, does Scala not have that? Ok. (By concatenate I meant whatever function scala has to reduce a list by addition.) \$\endgroup\$
    – emanresu A
    Aug 13, 2021 at 22:11
  • \$\begingroup\$ I'm not sure what it doesn't have, but whatever it is, no, it doesn't have it :). \$\endgroup\$
    – user
    Aug 13, 2021 at 22:14
3
\$\begingroup\$

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
           
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ 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 \$\endgroup\$ Aug 29, 2021 at 14:35
  • 1
    \$\begingroup\$ I think that g=eval(input()) should be shorter thatn your current method of getting input. \$\endgroup\$
    – Wheat Wizard
    Aug 30, 2021 at 9:00
  • 1
    \$\begingroup\$ You can also combine all the print statements into one: Try it online! \$\endgroup\$
    – Wheat Wizard
    Aug 30, 2021 at 9:00
2
\$\begingroup\$

CJam, 36 35 bytes

q~{)1${\_@~;%!},_@aa?{1=}%:+oNo}%];

Try it online!

Explanation

q~                                       read the factor array and upper bound in one go
  {)                            }%       for each i from 1 to n
    1${       },                          get all the input factors i contains
       \_@~;%!                              by checking i mod f = 0 for each input factor f
                _@aa?                     if there *are* factors in i,
                                            keep the relevant factors [[f, "Foo"], ...]
                                            otherwise keep the number in the form [[i]]
                     {1=}%                keep the 2nd element in each subarray
                                            this is the texts ["Foo","Bar","Baz",...]
                                            or just [i] if there were no input factors
                          :+              sum them all (concatenating texts together)
                            oNo           print in the required format
                                 ];       clean up

(-1 byte) dropping ,: CJam automatically turns a number n into [0, n) when you map using %


Possible Changes

(-2 bytes) using p instead of oNo but this prints "Foo"/"BarBaz" instead of Foo/BarBaz
(-2 bytes) using n instead of oNo but this feature isn't in any releases (and most likely will never be)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.