Akıllı Kişinin Mirage'ı


29

Bir zamanlar Quora'da bu soruyu / cevabı okuyordum.

Gerçekten FizzBuzz testini geçemeyen bilgisayar bilimleri derecesine sahip programcılar var mı

Bu kod bariz cevap olarak verilmiştir

for i in range(1, 100):
    if i % 3 == 0 and i % 5 == 0:
        print "FizzBuzz"
    elif i % 3 == 0:
        print "Fizz"
    elif i % 5 == 0:
        print "Buzz"
    else:
        print i

Elbette FizzBuzz ölümüne golf oldu, ancak bu sorunun ne olduğu değil. Yorumlarda, birileri bu açık cevabın harika olduğunu söylemektedir, çünkü 4 katları için "Caz" gibi ekstra koşullar eklemek kolaydır. (Katılmıyorum. ) Kod satırları.)

Buradaki zorluk, FizzJazzBuzz'ın en güzel versiyonunu meslektaşlarınca değerlendirildiği şekilde yazmak.

Seçmenlerin dikkate alması gereken bazı şeyler:

  1. KURU
  2. Bölme / modül işlemlerinin etkinliği

Quora'daki cevapların çoğu Python kullanıyordu, ancak burada böyle bir dil kısıtlaması yok.

Bir ay sonra en çok oyu alan cevabı kabul edeceğim

Örnek çıktı:

1
2
Fizz
Jazz
Buzz
Fizz
7
Jazz
Fizz
Buzz
11
FizzJazz
13
14
FizzBuzz
Jazz
17
Fizz
19
JazzBuzz
Fizz
22
23
FizzJazz
Buzz
26
Fizz
Jazz
29
FizzBuzz
31
Jazz
Fizz
34
Buzz
FizzJazz
37
38
Fizz
JazzBuzz
41
Fizz
43
Jazz
FizzBuzz
46
47
FizzJazz
49
Buzz
Fizz
Jazz
53
Fizz
Buzz
Jazz
Fizz
58
59
FizzJazzBuzz
61
62
Fizz
Jazz
Buzz
Fizz
67
Jazz
Fizz
Buzz
71
FizzJazz
73
74
FizzBuzz
Jazz
77
Fizz
79
JazzBuzz
Fizz
82
83
FizzJazz
Buzz
86
Fizz
Jazz
89
FizzBuzz
91
Jazz
Fizz
94
Buzz
FizzJazz
97
98
Fizz
JazzBuzz
popularity-contest  code-challenge  word  popularity-contest  string  grid  language-design  code-golf  source-layout  math  fastest-algorithm  assembly  code-golf  json  code-golf  arithmetic  array-manipulation  code-golf  ascii-art  code-golf  crossword  code-golf  string  restricted-complexity  code-golf  ascii-art  kolmogorov-complexity  code-golf  string  decision-problem  balanced-string  syntax  code-golf  grid  puzzle-solver  hexagonal-grid  code-golf  math  number  sequence  code-golf  string  decision-problem  code-golf  cryptography  king-of-the-hill  code-challenge  fastest-code  code-golf  number  code-golf  code-golf  string  code-golf  cryptography  king-of-the-hill  java  code-golf  number-theory  base-conversion  code-golf  code-golf  array-manipulation  code-golf  array-manipulation  sorting  code-challenge  restricted-source  quine  code-golf  tips  python  king-of-the-hill  code-golf  source-layout  fractal  code-golf  tips  game  king-of-the-hill  path-finding  grid  code-golf  kolmogorov-complexity  natural-language  code-golf  tips  python  code-golf  number  arithmetic  sequence  array-manipulation  code-golf  number  combinatorics  random  integer-partitions  code-golf  string  code-golf  vim  comment  code-golf  combinatorics  counting  code-challenge  rosetta-stone  code-golf  combinatorics  sequence  subsequence  code-golf  code-challenge  restricted-source  primes  printable-ascii  popularity-contest  graphical-output  image-processing 

1
İkinci kurşun noktanız biraz belirsiz ... Bölüşümü verimli yapan nedir? Bu meydan okuma için neden bu kadar önemli?
Sanchises,

@ sanchises, hala çok pahalı (döngü / zaman) bölme işlemlerine sahip platformlar, özellikle de mikro denetleyiciler var. Aşağıdaki cevaplardan en az biri, bölme / modülü tamamen önler - fakat okunabilirliği olumsuz yönde etkiler. Seçmenlerin dikkate alması gereken bir şey.
gnibbler

1
@sanchises hiçbir IMHO'da belirsiz değil, nokta hiç bir şekilde bölüm / modül kullanmıyor. Bunu sadece her n = (3,4,5 ...) için bir değişken tutarak ve eşleştiği anda sıfırlayarak bir kelime yazdırabilir ve değilken artan şekilde yapabilirsiniz. Kuru kısım bir işlev / yöntem alan (n, kelime) ve dolayısıyla daha fazla kelime eklemenin "bakımını" yapıyor olabilir
jean


Yanıtlar:


101

En güzel versiyon dedin mi? O zaman, hadi şunu deneyelim ...

Shakespeare Programlama Dili

The Marvelously Insane FizzBuzzJazz Program.

Lady Capulet, an old bossy woman that loves to count.
The Archbishop of Canterbury, an old fart who adores to spit out letters.


          Act I: The only one of them.

          Scene I: The Archbishop of Canterbury is a bastard.

[Enter The Archbishop of Canterbury and Lady Capulet]

The Archbishop of Canterbury:
 You are nothing!

          Scene II: Count, Lady Capulet, count.

The Archbishop of Canterbury:
 You are as beautiful as the sum of yourself and a cat!

Lady Capulet:
 Am I worse than the square of the product of the sum of a warm gentle flower and a rose
 and my pretty angel?

The Archbishop of Canterbury:
 If not, let us proceed to Scene VIII.

          Scene III: Fizzing to no end!

The Archbishop of Canterbury:
 Is the remainder of the quotient between yourself and the sum of a happy cow and a
 chihuahua as good as nothing?

Lady Capulet:
 If not, let us proceed to Scene IV. Thou art as handsome as the sum of the sum of
 the sweetest reddest prettiest warm gentle peaceful fair rose and a happy proud kindgom
 and a big roman. Speak thy mind!

 Thou art as fair as the sum of thyself and a honest delicious cute blossoming peaceful
 hamster. Thou art as cunning as the sum of the sum of an embroidered King and a horse
 and thyself. Speak thy mind!

 Thou art as amazing as the sum of the sum of a good happy proud rich hero and a hair and
 thyself! Speak thy mind.

 Speak your mind!

          Scene IV: Milady, there is jazz in thy robe.

The Archbishop of Canterbury:
 Is the remainder of the quotient between yourself and a proud noble kingdom as good as
 nothing?

Lady Capulet:
 If not, let us proceed to Scene V. You are as charming as the sum of the sum of a noble
 cunning gentle embroidered brave mighty King and a big warm chihuahua and an amazing
 pony! Speak your mind!

 You are as prompt as the sum of yourself and a big black sweet animal. You are as noble
 as the sum of the sum of a gentle trustworthy lantern and yourself and a hog. Speak your
 mind!

 You are as bold as the sum of the sum of yourself and a good delicious healthy sweet
 horse and my smooth cute embroidered purse. You are as peaceful as the sum of a flower
 and yourself. Speak your mind.

 Speak your mind!

          Scene V: Buzz me up, Scotty!

The Archbishop of Canterbury:
 Is the remainder of the quotient between yourself and the sum of a gentle happy cow and a
 chihuahua as good as nothing?

Lady Capulet:
 If not, let us proceed to Scene VI. Thou art as handsome as the sum of the sweetest
 reddest prettiest warm gentle peaceful fair rose and a small town. Speak your mind!

 You are as prompt as the sum of yourself and a big healthy peaceful fair rich kingdom.
 You are as loving as the sum of the sum of an embroidered King and a horse and thyself.
 You are as amazing as the sum of yourself and a cute fine smooth sweet hamster. Speak
 your mind!

 You are as prompt as the sum of the sum of yourself and an amazing cunning Lord and a
 hair. Speak your mind.

 Speak your mind!

The Archbishop of Canterbury:
 Let us proceed to Scene VII.

          Scene VI: Output or die!

The Archbishop of Canterbury:
 Open your heart!

          Scene VII: Oh, to jump the line.

Lady Capulet:
 You are as handsome as the sum of a proud noble rich kingdom and a rural town. Speak your
 mind! You are as gentle as the sum of the sum of yourself and a green mistletoe and my
 father. Speak your mind!

The Archbishop of Canterbury:
 We must return to Scene II.

          Scene VIII: Goodbye, cruel world!

[Exeunt]

Yani, burada SPL ile olan mücadelemden sonra , en azından bir tane yapmam gerektiğini hissettim. herhangi bir sorunu beraberinde teslim. Ve işte bu.

Peki, o zaman bunlar ne?

Bu yüzden, öncelikle, program boyunca kullanacağımız değişkenleri, Shakespeare oyunlarından gelmesi gerektiğini ilan ediyoruz. Romeo, Juliet, Ophelia ve Othello'dan bıkmış , Canterbury Başpiskoposu ve Lady Capulet ile gittim . Acts '/ Scenes' unvanlarının yanı sıra açıklamaları da ayrıştırıcı tarafından reddedilir, böylece oraya istediğiniz herhangi bir şeyi koyabilirsiniz.

Öyleyse, biraz daha az saçma bir şeye çeviri kralı yapalım .

Hareket Ben Sahne I

Begin Lady Capulet = 0;

Hareket I oldukça basit: değişkenimizi 0 ile başlatıyoruz.

Kanun I, Sahne II

Lady Capulet += 1; if(Lady Capulet < Math.pow((2*2*1+1)*(2*1),2)) continue; else goto Scene VIII;

Lady Capulet'in değerini yükseltir ve 100 ile karşılaştırırız (evet, tüm cümle yalnızca 100 sayısını almak için kullanılır); daha küçük değilse, Sahne VIII'e (son) atlarız; Aksi takdirde, bir sonraki sahneye geçiyoruz.

Bölüm I, Sahne III

if(Lady Capulet % (2+1) == 0) continue; else goto Scene IV; The Archbishop of Canterbury = 2*2*2*2*2*2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*2*1; The Archbishop of Canterbury += 2*1+1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*1+1; System.out.print((char)The Archbishop of Canterbury); System.out.print((char)The Archbishop of Canterbury);

İlk önce, bölümün modülünün 3'e kadar olup olmadığını görüyoruz; değilse, Sahne IV'e atlarız; öyleyse, aritmetik işlemler yapmaya ve Archieperson'a kaydetmeye başlıyoruz, aradığımızı bulduktan sonra karakter biçiminde çıkarıyoruz. Evet, sonunda, fikir elde etmektir Fizz.

Kanun I, Sahne IV

if(Lady Capulet % (2*2) == 0) continue; else goto Scene V; The Archbishop of Canterbury = 2*2*2*2*2*2*1+2*2*1+2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*1; The Archbishop of Canterbury += 2*2*1+(-1); System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*1+2*2*2*1; The Archbishop of Canterbury += 1; System.out.print((char)The Archbishop of Canterbury); System.out.print((char)The Archbishop of Canterbury);

İlk önce, bölme modülünün 4 ile 0 olup olmadığını kontrol eder, daha sonra, önceki ile aynı sahneyle devam eder Jazz.

Kanun I, Sahne V

if(Lady Capulet % (2*2+1) == 0) continue; else goto Scene VI; The Archbishop of Canterbury = 2*2*2*2*2*2*1+2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*2*1; The Archbishop of Canterbury += 2*1+1; The Archbishop of Canterbury += 2*2*2*2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2+1; System.out.print((char)The Archbishop of Canterbury); System.out.print((char)The Archbishop of Canterbury); goto Scene VII;

Önceki iki gibi işlev görür, bölme modülünün 5 ile 0 olup olmadığını kontrol eder, sonra yazmaya çalışır. Buzz ; tek fark, sonunda bir Sahneyi atlamamız.

Kanun I, Sahne VI

System.out.print(Lady Capulet);

Bu Sahneye ulaşmak için, Lady Capulet'in varsaydığı sayı ne Fizz ne de Jazz ne de Buzz; öyleyse, sayısal biçimde çıkardık.

Kanun I, Sahne VII

The Archbishop of Canterbury = 2*2*2*1+2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*1+1; System.out.print((char)The Archbishop of Canterbury); goto Scene II;

Yani, bir sonraki satıra atladığım tek yol bu: çıktı, önce bir CR, sonra bir LF; daha sonra programa devam edebilmemiz için Sahne II'ye geri döneriz.

Kanun I, Sahne VIII

End.

Yeterince basit.

Hala bunun çevrimiçi çalıştığını gösterip gösteremediğimi görmeye çalışıyorum, ancak bir çevrimiçi derleyici bulamıyorum - bildiğim bir tane bir program zaten yüklü olanların dışında herhangi bir programla iyi bir şekilde birleşmiyor gibi görünüyor, ya da belki bazı türler var klavye ile sandalye arasındaki arayüzde sorun var ...

Güncelleme 1:

Mathmandan'ın yorumundan sonra, Jazz ve Buzz sahnelerinin sırasını değiştirdim. Yapılması gerekiyordu.


1
DNS sorunlarım var gibi görünüyor. Yanlış alarm için kusura bakmayın.
Rainbolt

17
Biri Shakespeare'in neden kod golf oynamadığını merak ediyor.
Sanchises

5
Sahneler III, IV ve V'nin sırasıyla Fizz, Jazz ve Buzz'a karşılık geleceğini umuyordum. Yine de, güzel bitti!
mathmandan

1
@mathmandan Lanet olsun. Parlak bir şey yapmak için ne kadar boşa bir fırsat. LANET OLSUN!!
Rodolfo Dias

1
Muhteşem, ama bir böcek fark etmiş gibiyim. Bir Fizz veya bir Caz olup olmadığına bakılmaksızın, Buzz değilse sayıyı verir. Koştum, ama bunun için çek bulamıyorum. Belki de Başpiskoposun a olup olmadığını kontrol edebilir zve her döngüden önce onu sıfırlayabilirsiniz.
matega,

45

> <> (Balık)

1 > :9b*)?; 0& v
               \ :3%?v "Fizz" r}oooo &1+& \
               /     <                    /
               \ :4%?v "Jazz" r}oooo &1+& \
               /     <                    /
               \ :5%?v "Buzz" r}oooo &1+& \
               /     <                    /
               \   &?v :n                 \
  ^  +1 oa           <                    /

> <>, talimatların tek karakter olduğu ve talimat işaretçisinin (IP) oklara ^>v<ve aynalara bağlı olarak yukarı, aşağı, sola veya sağa hareket edebileceği 2B programlama dilidir /\. Değişkenleri veya karakterleri yok, bu yüzden kendini tekrar etmemek biraz daha zor, ama bence bu kendi başına güzel.

1Döngüyü itip başlatıyoruz. :9b*)?;sayının 99 ( 9b* = 9*11) ' dan büyük olup olmadığını kontrol eder ve öyleyse program durur ;. Aksi takdirde, kayıt cihazına 0 koyun vve dalgalı kısma doğru aşağı kaydırın .

:3%?Modulo 3 sayısını kontrol eder. Sıfır değilse, vbir satır aşağı inip sola hareket ederiz< . Aksi takdirde, aşağı oku ve itmek atlamak "Fizz", bunu (yazdırmak r}oooo) ve kayıt (artırmaz &1+&bir satır aşağı gitmek doğru duvar aynalar çarparak önce). Her halükarda, sol duvar aynalarından çıkana kadar üçüncü sıra boyunca sola doğru harekete geçiyoruz. Sonra Jazzve için tekrar ederiz Buzz.

Bu, register &değerini kontrol eden 7. satıra kadar devam eder . Sıfır değilse, o zaman aşağı ineriz. Aksi takdirde, naşağı inmeden önce numarayı yazdırırız .

En sonunda, ao (şu an sola doğru hareket ediyoruz!) Bir ASCII yeni satırını yazdırır ve 1+yukarı çıkıp tekrar ^döngü yapmadan önce sayıyı artırır >.

(Şimdi estetik bir Piet cevabı bekliyoruz ...)


3
Bu güzel. Bu, <<> cevapları için şöhret salonuna girmelidir.
Joshpbarron

2
Gözlerim hemen atladı: 3.
EMBLEM

Eh, bu dil okunabilirlik ödülleri kazanmayacak, ama oldukça temiz.
William T Froggard,

40

LOLCODE

Zarif? Hayır! Verimli? Kesinlikle hayır. Güzel? Ne dediklerini bilirsin: güzellik seyircinin gözündedir.

HAI
I HAS A kitty ITZ 1
IM IN YR house UPPIN YR kitty TIL BOTH SAEM kitty AN 100

    BTW, computin yr mods
    I HAS A d00d ITZ NOT MOD OF kitty AN 3
    I HAS A doge ITZ NOT MOD OF kitty AN 4
    I HAS A bro ITZ NOT MOD OF kitty AN 5

    ANY OF d00d bro doge MKAY, O RLY?
    YA RLY
        d00d, O RLY?
        YA RLY
            VISIBLE "Fizz"!
        OIC
        doge, O RLY?
        YA RLY
            VISIBLE "Jazz"! BTW, wow such jazz
        OIC
        bro, O RLY?
        YA RLY
            VISIBLE "Buzz"!
        OIC
    NO WAI
        VISIBLE kitty!
    OIC

    VISIBLE ""
IM OUTTA YR house
KTHXBYE

Bazı açıklamalar:

LOLCODE programları ile başlar HAIve biter KTHXBYE.

Değişkenler dinamik olarak yazılır ve kullanılarak atanır I HAS A <variable> ITZ <value>. Tanımlandıktan sonra değişkenler kullanılarak da atanabilir.<variable> R <value> .

LOLCODE içindeki döngüler adlandırılmıştır. Sözdizimi:

IM IN YR <loop> UPPIN YR <index> TIL BOTH SAEM <index> AN <end>
    <stuff to do>
IM OUTTA YR <loop>

Bu sadece Internet i "bitinceye kadar döngü" içindir. LOLCODE 1.2'de, indeksleme değişkeninin döngüden önce başlatılması gerekir. Burada döngü "ev" olarak adlandırılır, çünkü döngü başlatma sesini komik hale getirir.

VISIBLEstdout'a yazdırır. Varsayılan olarak bir yeni satır eklenir, ancak ekleme !, yeni satırı bastırır.

Şartlı şartlar aşağıdaki gibi belirlenmiştir:

<condition>, O RLY?
YA RLY
    <code to execute if condition is true>
NO WAI
    <code to execute if condition is false>
OIC

Koşullar, bir boole veya boole değerlerine göre değerlendirilen ifadeler olmalıdır. LOLCODE'da, boolean türü çağrılır TROOFve değerleri WIN(true) ve FAIL(false) olur.

Tek satırlı yorumlar ile başlar BTW.

Internetz dili konusunda iyi bilgili değil misiniz? Sadece bana bildirin ve mutlu bir şekilde daha fazla açıklama sağlayacağım.


3
Harika. Bu inanılmaz. Hala gülüyorum
rpax

@ rpax: Mükemmel ... Her şey plana göre gidiyor ...
Alex A.

33

Python3

lst = [('Fizz', 3),
       ('Jazz', 4),
       ('Buzz', 5),
       ]

for i in range(1, 101):  
    print(*[w for w, m in lst if i % m == 0] or [i], sep='')

Geçerli üst cevap arasında, bu, herhangi bir biçimde sadece bir tanesidirEfficiency of division/modulus operations
aross

@ aross Ne demek istiyorsun? Gördüğüm tüm cevaplar, bununla aynı sayıda bölme / modül işlemlerini kullanıyor.
Hjulle

Gerçekten mi? Diğer tüm cevaplar, her biri için bir modül operatörü kullanır (3, 4, 5). Üç kez kopyalandı. Bu sadece tek bir modül operatörü ile tek üst cevaptır.
saat

1
Sadece soru hakkındaki yorumları okudum. Alıntılanan cümleyi yanlış yorumladım. Bunun DRYyerine atıfta bulunmalıydı . Ayrıca, bu cevap OP tarafından oluşturulmuştur.
saat

31

Piet

Bigger ViewActual "Source"

Piet ile oynamaya karar verdim ve ne kadar güzel bir kod yazabileceğime karar verdim . Burada hiçbir şeyi tekrarlamamaya çalışıyorum, dürüst olmak gerekirse, mod hesaplamaları yapmak zorundayım. Ancak, her bir farklı mod (n% 3, n% 4 ve n% 5) kod yineleme başına yalnızca bir kez çalıştırılır.

Daha küçük resim uygun kaynaktır ve buraya yüklenip çalıştırılabilir .

Keyfini çıkarın!


4
"FizzBuzz testi geçemez bilgisayar bilimleri derecesi olan programcılar gerçekten var mıdır Piet de ?"
Sanchises

26

Mathematica

Mathematica'da çok özel parametreler için işlevleri tanımlayabilir ve aşırı yükleyebilirsiniz (yalnızca türüne göre değil, aynı zamanda isteğe bağlı mantıksal koşullara göre). Birkaç işlevi tanımlayalım:

Fizz[n_, s___] := {n, s}
Fizz[n_ /; Divisible[n, 3], s___] := {n, "Fizz" <> s}
Jazz[n_, s___] := {n, s}
Jazz[n_ /; Divisible[n, 4], s___] := {n, "Jazz" <> s}
Buzz[n_, s___] := {n, s}
Buzz[n_ /; Divisible[n, 5], s___] := {n, "Buzz" <> s}
DoThe[n_] := n
DoThe[_, s_] := s

Ve şimdi gerçek program sadece

DoThe @@@ Fizz @@@ Jazz @@@ Buzz /@ Range[100] // TableForm

Şimdi yukarıdakiler sadece bölenlerin sayısı ile doğrusal olarak büyürken, hala çok kuru değil. Fakat aslında bu tanımlarda değişkenleri ad olarak kullanabiliriz. Böylece aslında bu fonksiyon tanımlarını üreten bir fonksiyon yazabiliriz:

addFunction[f_, divisor_] := (
  f[n_, s___] := {n, s};
  f[n_ /; Divisible[n, divisor], s___] := {n, ToString[f] <> s}
)
addFunction[Fizz, 3];
addFunction[Jazz, 4];
addFunction[Buzz, 5];
DoThe[n_] := n
DoThe[_, s_] := s

DoThe @@@ Fizz @@@ Jazz @@@ Buzz /@ Range[100] // TableForm

Now all you have to do is add another addFunction call and add your new **zz to the final line.


13
DoThe @@@ Time @@@ Warp @@@ Again /@ Range[100] // TableForm
Sp3000

10
It's just a JMP to the left!
MikeTheLiar

"all you have to do is add another addFunction call."... and add the new function to the final line?
Sparr

@Sparr oh yeah that's true
Martin Ender

22

Haskell

You guys aren't taking the DRY seriously. There are obvious patterns that can be factored out in the "Fizz Jazz Buzz" sequence.

import Control.Applicative

-- All words end with "zz" and the numbers are in a sequence
fizzes = zip [3..] $ (++ replicate 2 'z') <$> words "Fi Ja Bu"

main = putStrLn . unlines $ fizzIt <$> [1..99]

-- Point free style with reader monad ((->) a) to minimize
-- unnecessary repetition of variable names
fizzIt = nonFizzy =<< fizzy

-- Show the number if no fizziness was found. Partially point free
-- with respect to n. But xs is needed to prevent the error:
-- "Equations for ‘nonFizzy’ have different numbers of arguments"
nonFizzy "" = show
nonFizzy xs = const xs

-- (Ab)use the list monad for concatenating the strings

fizzy i = snd =<< filter ((==0).mod i.fst) fizzes
-- Could also be written as:
-- > fizzy i = concat [ str | (n,str) <- fizzes, i`mod`n==0]
-- but that would be way too readable, and not pointless (ahem, point free) enough. ;)

This code is also easily extensible. To solve the "Fizz Jazz Buzz Tizz" problem, all you need to do is add Ti after the Bu in the string. This is much less than what is needed in any of the other solutions.


5
What if you had to solve the Fizz-Jazz-Buzz-Sausage problem?
Anko

@Anko I could either do something like this fizzes = zip [3..] $ ((++ replicate 2 'z') <$> words "Fi Ja Bu") ++ ["Sausage"], or just revert to fizzes = zip [3..] $ words "Fizz Jazz Buzz Sausage".
Hjulle

3
replicate 2 z is stretching it a bit . . .
Soham Chowdhury

3
@octatoan I couldn't resist. ;)
Hjulle

16

Excel VBA

             Sub scopeeeeeeeeeeeeeeee()
                     '   ||
               For u = 1 To 100
   If u Mod 3 = 0 Then yell = "Fizz"
If u Mod 4 = 0 Then yell = yell & "Jazz" '---------------------------------------------|
If u Mod 5 = 0 Then yell = yell & "Buzz" '---------------------------------------------|
            'made in USA
            If yell = "" Then yell = u
             Debug.Print yell      '\\
             yell = ""              '\\
            Next                     '\\
           End Sub                    '\\

It might sounds stupid, but it's a 2D sniper rifle!


Half of it.!!!!
Optimizer

2
Also, this is funny - "If you mode 3"
Optimizer

Thank you!! I didn't expect someone realize the u mode 3 part so quick
Alex

I don't understand why half of it!
Alex

Sniper is only half. The scope is usually at the middle of the sniper.
Optimizer

15

Java

void fizzy(int limit){
    String[] output = new String[limit];
    Arrays.fill(output,"");

    List<SimpleEntry<Integer,String>> tests = new ArrayList<SimpleEntry<Integer,String>>();
    tests.add(newEntry(3,"Fizz"));      
    tests.add(newEntry(4,"Jazz"));      
    tests.add(newEntry(5,"Buzz"));      

    for(SimpleEntry<Integer,String> test : tests)
        for(int i=test.getKey();i<limit;i+=test.getKey())
            output[i] += test.getValue();           

    for(int i=1;i<limit;i++)
        System.out.println(output[i].length()<1 ? i : output[i]);
}   

SimpleEntry<Integer,String> newEntry(int key, String value){
    return new SimpleEntry<Integer,String>(key,value);
}

So Java isn't really considered "beautiful" by most, but that's crazy subjective so I went by the guidelines in the question:

  • Don't Repeat Yourself: No problem. You only need to add one line for each number. I even made a helper function so you don't have to type as much when you do (Java can be a bit verbose sometimes, if you didn't know).
  • Efficiency of division/modulus operations: Perfect efficiency, since there is no modulus or division at all.

That's not to say that the algorithm as a whole is the most efficient (it's not), but I think it hits the bulleted points well.


2
It wouldn't be Java if you didn't define a class. :D
Adrian Leonhard

I wanted to like a Java answer and I like this approach, but I feel like embedding code in for-statements is unnecessary obfuscation. Beautiful Java is readable Java!
Alex Pritchard

@AlexPritchard I consider that a side effect of code golfing. Will fix when at a PC :)
Geobits

11

Inform 7

Inform 7 is a rule based programming language designed for interactive fiction. It is notable for being one of the most successful natural language based programming languages. See the Inform 7 language showcase for other examples and a few bits of trivia.

The number printing rules are a number based rulebook.

Definition: a number is fizzy if the remainder after dividing it by 3 is 0.
Definition: a number is jazzy if the remainder after dividing it by 4 is 0.
Definition: a number is buzzy if the remainder after dividing it by 5 is 0.

A number printing rule for a fizzy number:
    say "Fizz";

A number printing rule for a jazzy number:
    say "Jazz";

A number printing rule for a buzzy number:
    say "Buzz";

A number printing rule for a number (called N):
    unless a paragraph break is pending:
        say N;
    say conditional paragraph break;

To print a series of numbers from (min - a number) to (max - a number):
    repeat with N running from min to max:
        follow the number printing rules for N;

This code has the advantage that each of the FizzBuzz rules are completely independent: additional rules can be added at any point without needing to change the general framework. Unfortunately it's a little repetitive, especially with the definition phrases. I could define a % operator, but then it wouldn't be English. ;)

This code can be run online using Playfic.


7

Dyalog APL

∇FizzJazzBuzz;list;items;names
   items ← ⍳100    
   list  ← ↑('Fizz' 3) ('Jazz' 4) ('Buzz' 5)   

   names ← (,/ ↑(↓0=⍉list[;2]∘.|items) /¨ ⊂list[;1]) ~¨ ' '
   ⎕← ↑,/↑names ,¨ (∊0=⍴¨names) ⍴¨ ⊂¨⍕¨items
∇
  • DRY: there is no double code
  • Easy to change conditions: the names are taken from a list, in order, per divisor, with minimal change needed
  • Easy to change range: items can be changed to an arbitrary list of numbers
  • Efficient: makes use of easily parallelized list-based algorithm consisting only of side-effect free primitives.
  • Simple code flow: not only are there no gotos, there are no whiles or ifs either. The code is completely linear.
  • Secures your job: barely anybody else will be able to work on it...

What are the values of ⎕ML and ⎕IO?
FUZxxl

They are both 1, which is the default.
marinus

7

C#

for(int i = 1; i <= 99; i++){
    string s = "";
    if (i % 3 == 0) s += "Fizz";
    if (i % 4 == 0) s += "Jazz";
    if (i % 5 == 0) s += "Buzz";
    System.Console.WriteLine(s == "" ? "" + i : s);
}

Check mod, build string, print number if blank or string if not. No repeats. Only need to add condition & output for new requirements.


2
"No repeats"? (OK, at least the code size grows linearly with additional words.)
Anko

I took the challenge of no repeats a bit further with my C# answer, but sacrificed any flexibility when it comes to which numbers to modulus on. I think the best result would be a datastructure relating number and word.
sydan

@Anko Not sure what you are getting at, no function is repeated. I'm not doing the same thing twice anywhere in the code.
rapjr11

@rapjr11 The code checks i-%-something many times, as well as appending to s many times. (Lots of the syntax is repetitive too, but that's probably C#'s fault.)
Anko

7

Python 2.7

I tried to make it poetic...

I'm not very good at love poetry...

of = 1
my_love = 100
youre = "ever"

#You are
for ever in range(of, my_love) :
    never = "out my mind"
    for I,am in[#audibly
                (3, "Fizzing"),
                (4, "Jazzing"),
                #and
                (5, "Buzzing")]:
        if( ever % I ==0):# near you
            never += am #I lonely.
    #because
    youre = ever #in my mind.
    if( youre, never == ever,"out my mind" ):
        never += str(youre) #(I gave up with this line...)
    #then our foot-
    print"""s will"""( never [11:3])# part. 

It would also be a lot better without the initial constants :P


Creative, but this doesn't run for me in Python 2.7.9. It says: TypeError: 'str' object is not callable.
Alex A.

Hmmmm... Damn... Not entirely sure how I missed that :/
JamJar00

5

Java with classes

The algorithm:

public static void main(String... args) {

    List<Condition> conditions = new ArrayList<Condition>();
    conditions.add(new TerminatingCondition(100));
    conditions.add(new ModuloCondition(3, "Fizz"));
    conditions.add(new ModuloCondition(4, "Jazz"));
    conditions.add(new ModuloCondition(5, "Buzz"));
    conditions.add(new EchoCondition());

    while (true) {
        for (Condition c : conditions){
            c.apply();
        }
    }

}

The classes:

interface Condition {
    void apply();
}

static class ModuloCondition implements Condition {
    int modulo, count = 0;
    String message;
    ModuloCondition(int modulo, String message){
        this.modulo = modulo;
        this.message = message;
    }
    public void apply() {
        count++;
        if (count == modulo) {
            out.append(message);
            count = 0;
        }
    }
}

static class TerminatingCondition implements Condition {
    int limit, count = 0;
    TerminatingCondition(int limit) {
        this.limit = limit;
    }
    public void apply() {
        count++;
        if (count > limit) {
            System.exit(0);
        }
    }
}

static class EchoCondition implements Condition {
    int count = 0, lastOutCount = 0;
    public void apply() {
        count++;
        out.println((lastOutCount == out.count) ? String.valueOf(count) : "");
        lastOutCount = out.count;
    }
}

static class Out {
    int count = 0;
    void append(String s) {
        System.out.append(s);
        count++;
    }
    void println(String s){
        append(s + System.lineSeparator());
    }
}

static Out out = new Out();

2
+1, you have truly captured the spirit of Java coding with this 70-line FizzBuzzJazz. It's object-oriented and is written in a clearly specified, non-abbreviated, readable style. Very long. But very readable. ;^)
DLosc

4

MATLAB / Octave

Of course, writing your own loops is fun for programmers, but everybody knows how tedious keeping track of indexing really is (who hasn't written for(j=i;j<n;i++) in a nested loop at least once in their lives?)

MATLAB has the solution. Really, this code is not the most efficient, and certainly not code-golfed, but it is by all means a good showcase of MATLAB's more interesting functions. Octave is the GNU version of MATLAB; it is however not suitable for code-golf since it is slightly stricter with variable types, which is detrimental for code-golf.

EDIT: until syntax highlighting for MATLAB exists on SE, I'm posting a version with very little comments, because else it was just a big scary block of plain text.

function out = fizzjazzbuzz(n)
    %Initialization
    numberlist=1:n;
    fizz=cell(1,100);
    jazz=fizz;buzz=jazz;

    %Complex loops - no, wait, easy logical indexing.
    fizz(~mod(numberlist,3))={'Fizz'}; 
    jazz(~mod(numberlist,4))={'Jazz'};
    buzz(~mod(numberlist,5))={'Buzz'};
    out=strcat(fizz,buzz,jazz);
    %Fill with numbers
    out(cellfun(@isempty,out))=num2cell(numberlist(cellfun(@isempty,out)));

    %Pretty output (although the default printing is perfectly acceptable)
    out=cellfun(@num2str,out,'UniformOutput',0);
    strjoin(out,sprintf('\n'));
end

2
for(j=i;j<n;i++)? My question is: who did write this "at least once in their lives"? If you did, I have bad new for you...
Bogdan Alexandru

1
@BogdanAlexandru You have never ever in your life accidentally incremented the wrong variable in a for loop (e.g. when nesting loops)? Are you the guy whose code successfully compiles every first time? If you are, I have god news for you...
Sanchises

2
I'm not talking about incrementing the wrong variable, my code is not god-written. I'm talking about that coding style, it's in itself very error prone. The j name for a loop local variable is fine, but the i name is very bad practice and that is the source of your mistake. It's not purely accidentally :)
Bogdan Alexandru

@BogdanAlexandru Ah yes, I quite agree; the reason I still use this style of loop is when implementing given assignments (I'm a masters student); I rather use the index notation used by the professor in question, than to confuse the poor old man by using my own.
Sanchises

1
It's no problem giving one letter names to indexes of a loop, but the other variables should have more meaningful names.
Bogdan Alexandru

4

Python

from collections import defaultdict

lst = [(3, 'Fizz'),
       (5, 'Buzz'),
       (4, 'Jazz')]

word_list = defaultdict(list)

for d, w in sorted(lst):
    for i in range(d, 100, d):
        word_list[i].append(w)

for i in range(1, 100):
    print(''.join(word_list[i]) or i)

This is of course way too long. gnibbler's solution is much better. (although replacing *..., sep='' with ''.join would be more beautiful)

But this is quite efficient in terms of division/modulus operations.


1
Why do you use sorted(lst), why not just put it in the order you need when you define it?
mbomb007

Or sort it in place before the loop. lst.sort()
Davidmh

4

Ruby

100.times do |n|
  l = [nil, 'Fizz', 'Jazz', 'Buzz'].select.with_index{|x, i| x && (n % (i+2)) == 0 }
  puts l.empty? ? n : l * ''
end

Looks like this is multiples of 2,3 and 4?
gnibbler

@gnibbler Whoops, yes it is. Fixed.
Doorknob

4

Haskell

inp = [(3, "Fizz"), (4, "Jazz"), (5, "Buzz")]

mkList (n, str) = cycle $ replicate (n-1) "" ++ [str]

merge lists = (head =<< lists) : merge (map tail lists)

checkFJB "" n = show n
checkFJB s  _ = s

fjb = zipWith checkFJB (merge $ map mkList inp) [1..]

print100fjb = mapM_ putStrLn $ take 100 fjb

Yet another solution without division or modulus. fjb creates an infinite list of Fizzes, Jazzes, Buzzes and/or numbers. take any amount you want, as seen in print100fjb which prints the first 100 elements.


4

SQL (MySQL)

SELECT COALESCE(GROUP_CONCAT(FizzJazzBuzz.str ORDER BY FizzJazzBuzz.n SEPARATOR ''), I.id)
FROM I
    LEFT JOIN (
        SELECT 3 n,'Fizz' str
        UNION SELECT 4, 'Jazz'
        UNION SELECT 5, 'Buzz'
    ) FizzJazzBuzz ON I.id MOD FizzJazzBuzz.n = 0
GROUP BY I.id
ORDER BY I.id;

where I is a table with one column (id INT) containing the 100 integers.

I don't know an SQL flavor which can generate the table I easily, or can use VALUES as subqueries, which can make it much better and complete.


1
You can use variables in mysql. SELECT @i:= (@i + 1) FROM mysql.help_relation, (SELECT @i:=0) v WHERE @i < 100;
slicedtoad

@slicedtoad SELECT DISTINCT help_keyword_id FROM mysql.help_relation WHERE help_keyword_id>0 AND help_keyword_id<=100 also worked. But if 100 is changed to 10000, both will be broken.
jimmy23013

1
Just self join it if you need more rows.
slicedtoad

As far as I'm aware MySQL is the only SQL dialect that doesn't have an easy row-generator option. Most can just use a recursive common table expression.
Ben

@Ben But recursive ways doesn't always look good. I'll not fix my answer by changing the dialect because there is already an Oracle SQL answer.
jimmy23013

3

Ruby

1.upto(100) do |i|

  rules = { 3 => 'Fizz', 4 => 'Jazz', 5 => 'Buzz' }

  print(i) unless rules.select! { |n,s| i.modulo(n) > 0 or print(s) }

  puts

end

3

JavaScript


Perhaps not the most efficient way, but I think it's simple and pretty <3

(function fizzBuzz(iter){
    var str = '';
    

    if(!(iter % 3)) str += 'Fizz'
    if(!(iter % 4)) str += 'Jazz'
    if(!(iter % 5)) str += 'Buzz'


    console.log(str || iter)


    if(iter >= 100) return

    
    fizzBuzz(++iter)
})(1)


Moar DRY and effin ugly :C

(function fizzBuzz(iter){
    var 
        str,
        fijabu = ['Fi','Ja','Bu']
    ;
    

    (function isMod(_str,val){

        if(!(iter % val)) _str += fijabu[val-3] + 'zz'


        if(val >= 5) return str = _str


        isMod(_str,++val)
    })('',3)


    console.log(str || iter)


    if(iter >= 100) return

    
    fizzBuzz(++iter)
})(1)


8
Why the double-spacing?
Anko

Personal Convention. I think its nicer to read.
soundyogi


I do it only in personal projects and for fun. Most Teams do not like it.
soundyogi

2

JavaScript

DRYish ... ;)

(function FizzJazzBuzz(iter) {
    var output = ["Fi", "Ja", "Bu"];
    var str = "";

    output.map(function(v,i,a) {
        if(!(iter%(i+3))) str += output[i] + "zz";
    });

    console.log(str || iter);

    if(iter < 100) FizzJazzBuzz(++iter);

    return;
})(1);

2

Utterly Stupid C#

Half the brief was 'DON'T REPEAT YOURSELF' so I took that as literally as I could with C# and that accidentally progressed into golfing the code. This is my first golf and I did it in C#, stupid I know but here's the result:

Golfed (240 232 230 chars):

namespace System{using Diagnostics;using i=Int32;using s=String;class P{static void Main(){s[] z=new s[]{"Fi","Ja","Bu"};for(i a=1;a<100;a++){s l="";for(i b=3;b<6;b++)if(a%b==0)l+=z[b-3]+"zz";Trace.WriteLine((l!="")?l:a+"");}}}}

Ungolfed:

namespace System
{
   using Diagnostics;
   using i = Int32;
   using s = String;
   class P 
   { 
      static void Main() 
      {
         s[] z = new s[] { "Fi","Ja","Bu" }; 
         for(i a = 1;a < 100;a++) 
         { 
            s l = ""; 
            for(i b = 3;b < 6;b++)
               if(a % b == 0)
                  l += z[b - 3] + "zz"; 
            Trace.WriteLine((l != "") ? l : a+""); 
         } 
      } 
   }
}

The aim was to shorten any thing I had to use more than once and in general to keep the code short while producing a complete C# program. For this you will need to use VisualStudio and set the StartUp object to 'P' you will also need to look for the output in the debugging output window.

There are some serious limitations here:

  • The code assumes that all words will end in 'zz'
  • The code assumes that the modulus will happen consecutively (3,4,5,6...)
  • The code still favours lack or repetition over true golfling, more characters are added to avoid some repeats

2

Python 2

I wanted to write an answer for this in some tidy Python that would show off the features of the language, comply with the DRY principle, and be fairly readable.

group = range(100)
rules = [('fizz', group[::3]), ('jazz', group[::4]), ('buzz', group[::5])]
for number in group[1:]:
    labelset = ''
    for label, matches in rules:
        if number in matches:
            labelset += label
    print labelset if labelset else number

This little example shows slicing, the in operator, and the verbose but understandable ternary syntax. It does not use the modulo operator at all. It is not designed for run-time efficiency, but that was not the goal. It is designed to be short, understandable and maintainable.


Why not use set(group[...]) in the rules?
gnibbler

I was going for elegance rather than speed. Using set() would be faster in real applications of course.
Logic Knight

2

Python 2.7, 111 byte

This is my first contribution. I tried to apply some Python codegolfing tricks (string interleaving, tuple index access instead of if). If you have any suggestion, please share them!

for i in range(1,101):
 p=""
 for x in 3,4,5:
  if not(i%x):p+="FJBiauzzzzzz"[x-3::3]
 print((p,i)[not len(p)])

Output :

1
2
Fizz
Jazz
Buzz
Fizz
7
Jazz
Fizz
Buzz
11
FizzJazz
13
14
FizzBuzz
Jazz
17
Fizz
19
JazzBuzz
Fizz
22
23
FizzJazz
Buzz
26
Fizz
Jazz
29
FizzBuzz
31
Jazz
Fizz
34
Buzz
FizzJazz
37
38
Fizz
JazzBuzz
41
Fizz
43
Jazz
FizzBuzz
46
47
FizzJazz
49
Buzz
Fizz
Jazz
53
Fizz
Buzz
Jazz
Fizz
58
59
FizzJazzBuzz
61
62
Fizz
Jazz
Buzz
Fizz
67
Jazz
Fizz
Buzz
71
FizzJazz
73
74
FizzBuzz
Jazz
77
Fizz
79
JazzBuzz
Fizz
82
83
FizzJazz
Buzz
86
Fizz
Jazz
89
FizzBuzz
91
Jazz
Fizz
94
Buzz
FizzJazz
97
98
Fizz
JazzBuzz

I also couldn't fully apply the DRY principle, since there are two for loops. There is probably a smarter way to do it!


I can probably also use a tuple in the first for statement. Will update when I can!
Nepho

Okay, so it works with the two variables in the same loop, but I go from 111 bytes to 145 : gist.github.com/Neph0/ddc7a5ad04aa083d44af5cab3f90550f
Nepho

1

Go

The concurrent FizzJazzBuzzer

package main

import (
    "fmt"
    "sort"
    "sync"
)

var hooks map[int]string = map[int]string{
    3: "Fizz",
    4: "Jazz",
    5: "Buzz"}

type candidate struct {
    num     int
    message string
}

func FizzJazzBuzzer(hooks map[int]string) (chan<- int, *sync.WaitGroup) {
    var wg *sync.WaitGroup = new(sync.WaitGroup)
    final := func(c chan candidate) {
        for i := range c {
            if i.message == "" {
                fmt.Println(i.num)
            } else {
                fmt.Println(i.message)
            }
            wg.Done()
        }
    }
    prev := make(chan candidate)
    go final(prev)
    var keys []int = make([]int, 0)
    for k := range hooks {
        keys = append(keys, k)
    }
    sort.Sort(sort.Reverse(sort.IntSlice(keys)))
    for _, mod := range keys {
        c := make(chan candidate)
        s := hooks[mod]
        go (func(in chan candidate, next chan candidate, mod int, s string) {
            for i := range in {
                if i.num%mod == 0 {
                    i.message += s
                }
                next <- i
            }
        })(c, prev, mod, s)
        prev = c
    }
    in := make(chan int)
    go (func(in <-chan int) {
        for i := range in {
            prev <- candidate{i, ""}
        }
    })(in)
    return in, wg
}

func main() {
    in, wg := FizzJazzBuzzer(hooks)
    for i := 1; i < 20; i++ {
        wg.Add(1)
        in <- i
    }
    wg.Wait()
}

Try it here: http://play.golang.org/p/lxaZF_oOax

It only uses one modulus per number checked and can be arbitrarily be extended to any number of, well... numbers.

You only have to make changes 3 different places to extend this, in the hooks map, the FizzJazzBuzzer function name and, of course, the call to the FizzJazzBuzzer function.


1

R

This creates a function which allows a user to specify pairs of words and divisors (and optionally a maximum number, with 100 as the default). The function creates a vector from 1 to the maximum number, then replaces any numbers at "fizzbuzz" positions with "", and finally pastes each word at its desired position. The function orders the list from lowest to highest number so that the lowest number will always be the first part of the "fizzbuzz". The positions are calculated using seq to create a vector starting at a given number and increasing in increments of that number until the maximum desired number is reached.

fizzbuzzer = function(max.num=100, ...){

input = list(...)
input = input[order(unlist(input))] #reorder input list by number
words = names(input)

#vector containing the result
output = seq_len(max.num)

#remove numbers at positions to contain a "fizzbuzz"
sapply(input, function(x) output[seq(x, max.num, x)] <<- "")

#add words at required points
sapply(seq_len(length(input)), function(i) output[seq(input[[i]], max.num, input[[i]])] <<- paste0(output[seq(input[[i]], max.num, input[[i]])], words[i]))

return(output)
}    

I don't think it's very beautiful, but it's easy to re-use with different parameters.

usage examples:

fizzbuzzer(fizz=3, buzz=5)
fizzbuzzer(fizz=3, buzz=5, jazz=4)
fizzbuzzer(max.num=10000, golf=10, stack=100, code=1, exchange=1000)

The output of fizzbuzzer(fizz=3, buzz=5) is:

[1] "1"        "2"        "fizz"     "4"        "buzz"     "fizz"    
[7] "7"        "8"        "fizz"     "buzz"     "11"       "fizz"    
[13] "13"       "14"       "fizzbuzz" "16"       "17"       "fizz"    
[19] "19"       "buzz"     "fizz"     "22"       "23"       "fizz"    
[25] "buzz"     "26"       "fizz"     "28"       "29"       "fizzbuzz"
[31] "31"       "32"       "fizz"     "34"       "buzz"     "fizz"    
[37] "37"       "38"       "fizz"     "buzz"     "41"       "fizz"    
[43] "43"       "44"       "fizzbuzz" "46"       "47"       "fizz"    
[49] "49"       "buzz"     "fizz"     "52"       "53"       "fizz"    
[55] "buzz"     "56"       "fizz"     "58"       "59"       "fizzbuzz"
[61] "61"       "62"       "fizz"     "64"       "buzz"     "fizz"    
[67] "67"       "68"       "fizz"     "buzz"     "71"       "fizz"    
[73] "73"       "74"       "fizzbuzz" "76"       "77"       "fizz"    
[79] "79"       "buzz"     "fizz"     "82"       "83"       "fizz"    
[85] "buzz"     "86"       "fizz"     "88"       "89"       "fizzbuzz"
[91] "91"       "92"       "fizz"     "94"       "buzz"     "fizz"    
[97] "97"       "98"       "fizz"     "buzz"    

(numbers in square brackets are the indices of the vector the function outputs)


1

Haskell

No modular arithmetic is used, except in computing the least common multiple to avoid repeating unnecessary work. The string concatenations only need to be done 60 times, no matter what we set the upper limit to.

-- Don't repeat `transpose` from `Data.List`
import Data.List (transpose)

-- The desired problem
lst = [(3, "Fizz"), (4, "Jazz"), (5, "Buzz")]

-- Map a function over both sides of a tuple.
-- We could also get this from importing Bifunctor (bimap), bit it's not in the core libraries
bimap f g (x, y) = (f x, g y)

-- Make infinite lists with the word occuring only once every n items, starting with the first
fizzify = map (cycle . uncurry take . bimap id (:repeat ""))

-- Reorganize the lists so there's a single infinite list, smash the words together, and drop the first set.
fjb = tail . map concat . transpose . fizzify

-- The following two functions avoid repeating work building the lists
-- Computes the least common multiple of a list of numbers
lcms = foldr lcm 1

-- fjbLcm is just a more efficient version of fjb; they can be used interchangably
fjbLcm lst = cycle . take (lcms . map fst $ lst) . fjb $ lst

-- show the number if there aren't any words
result = zipWith (\x y -> if null x then show y else x) (fjbLcm lst) [1..100]

main = print result

Replacing fjbLcm with fjb does exactly the same thing, with no arithmetic used except in [1..100] and take.


This is essentially the same as Nimi's solution, which I didn't notice before.
Cirdec

1

Python2

Update: New version doesn't use any mod or division operations.

word_dict = {3: 'Fizz', 4: 'Jazz', 5: 'Buzz'}

def fizz_jazz_buzz(n, d):
    counters = {k: k for k in d}
    for i in xrange(1, n + 1):
        u = ''
        for k in d:
            if counters[k] == i:
                u += d[k]
                counters[k] += k
        print u or i

fizz_jazz_buzz(100, word_dict)

If you want to add another word to the test, just throw the key/value pair into the word_dict dictionary:

word_dict[7] = 'Razz'
fizz_jazz_buzz(100, word_dict)

If you want to get rid of a word, just delete it (using del) or alternatively set it to ''.

del word_dict[3]
fizz_jazz_buzz(100, word_dict)

See also the Python answers of Gnibbler and Jakube, which were posted before mine.


1

C#

Maintainability: Just add one line per element
I iterate over each element in the dictionary, to check if it's a divisor of the current number, and adding to the string if it is.
Once finished, print the string, unless it is still null ( using the null coalescing operator ), in which case print the number plus an empty string to make it a string. ( I could use toString, but I guess that's a personal choice )

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    {3, "Fizz"},
    {4, "Jazz"},
    {5, "Buzz"}
};
for (int i = 0; i < 100; i++)
{
    string msg = null;
    foreach (var pair in dict)
        if (i % pair.Key == 0)
            msg += pair.Value;
    Console.WriteLine(msg ?? i + "");
}
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.