Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Fizzbuzz Without Ifs in 90 Characters -- I'll Buy You a Beer if You Can Beat It

DZone's Guide to

Fizzbuzz Without Ifs in 90 Characters -- I'll Buy You a Beer if You Can Beat It

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Yesterday I got nerd-sniped into solving the FizzBuzz problem without using if sentences.

Unfortunately, a more careful inspection of the problem specification reveals this solution was incorrect.

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Luckily, that’s a very simple fix:

# codegolf version (90 characters):
[{0:"fizzbuzz"}.get(x%(3*5),{0:"fizz"}.get(x%3,{0:"buzz"}.get(x%5,x)))for x in range(101)]
 
# slightly more readable:
[{0: "fizzbuzz"}.get(x%(3*5), 
                     {0: "fizz"}.get(x%3, 
                                     {0: "buzz"}.get(x%5, x))) 
 for x in range(101)]

There you have it, a solution to the fizzbuzz problem that relies on python’s interactive command line interpreter thingy to do the printing, shaving off 4 characters for print.

The “trick”, if it can be called that, is relying on the native get method to return the correct string or fall back to the default value, which checks for the next string in the if-then-else chain.

I wish never to see code like that in something I have to maintain. Ever.

The challenge

Your challenge, should you choose to accept it, is to produce a shorter fizzbuzz solution without using if sentences. I will buy a bottle of beer for the winner.

The best Scala solution so far is 106 characters, by @HairyFotr:

1 to 100 map(a=>println((a%3,a%5)match{case(0,0)=>"fizzbuzz"case(0,_)=>"fizz"case(_,0)=>"buzz"case _=>a})) /cc

No really, I will send a bottle of beer anywhere in the world if you write a shorter solution. Of course, if feasible, I would prefer to take you out for a beer than use snail mail :)

Beer bottles by photos for fun
 
 

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
\r\n

Unfortunately, a more careful inspection of the problem specification reveals this solution was incorrect.

\r\n

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

\r\n

Luckily, that’s a very simple fix:

# codegolf version (90 characters):\r\n[{0:"fizzbuzz"}.get(x%(3*5),{0:"fizz"}.get(x%3,{0:"buzz"}.get(x%5,x)))for x in range(101)]\r\n \r\n# slightly...","authors":[{"realName":"Swizec Teller","isMVB":true,"isStaff":false,"aboutAuthor":"I'm a writer, programmer, web developer, and entrepreneur. Preona is my current startup that began its life as the team developing Twitulater. Our goal is to create a set of applications for the emerging Synaptic Web, which would rank real-time information streams in near real time, all along reading its user behaviour and understanding how to intelligently react to it. twitter: @Swizec","claimed":"Michael_Tharrington","name":"Swizec","tagline":null,"company":"preona","id":364999,"avatar":"https://secure.gravatar.com/avatar/11069ea4526454fab5398554dce6571f?d=identicon&r=PG","isClaimed":true,"url":"/users/364999/Swizec.html"}]}];
        TH.installWidgetController('article.content', 'articleContent5', WMODEL_DATA, typeof controller == 'function' ? controller : null, [{name: 'partners', data: true},{name: 'DEFAULT', data: true}], ' oUhbblYOaqbcblYOaqbcC', null);
        })();
        (function() {
            function controller($scope, $service, $location, SideBarService, $timeout) {

    if ($scope.edition) {
        $scope.date = moment($scope.editionDate).utc().format('MMM DD, YYYY');
    }

    SideBarService.ctx.pageSize = $scope.pageSize;
    SideBarService.ctx.isPreview = $scope.isPreview;
    SideBarService.ctx.mode = $scope.mode;

    SideBarService.fn.loader = $service;

    var $window = $(window);

    function checkWidth() {
        var windowsize = $window.width();
        $scope.width = windowsize;
    }
    // Execute on load
    checkWidth()
    // Bind event listener
    $(window).resize(checkWidth);


    if ($scope.edition) {
        SideBarService.ctx.edition = $scope.edition;
    }

    SideBarService.fn.scrollCheck = function() {
        $scope.$emit('thIfScrollCheck');
    };

    var currentFilter;

    $scope.$on('$locationChangeSuccess', function() {

        if (!$location.search().filter) {
            $scope.filter = 'latest';
        } else {
            $scope.filter = $location.search().filter;

            if ($scope.filter == 'latest') {
                $location.search('filter', null);
            }
        }

        if (currentFilter == $scope.filter) {
            return;
        }

        currentFilter = $scope.filter;

        SideBarService.ctx.filter = $scope.filter;
    });

    $scope.display = SideBarService.getList();

    $scope.$watchCollection(function() {
        return SideBarService.getList();
    }, function (n) {
        $scope.display = n;
    });

    $scope.isActive = SideBarService.isActive;

    $scope.isExcluded = SideBarService.isExcluded;

    $scope.loadMore = SideBarService.load;

    $scope.loading = function() {
        return SideBarService.ctx.loading;
    };

    TH.on('TapBarStatusChange', function(expanded) {
        if (expanded) {
            SideBarService.unblock();
        }
    })

}
            var WMODEL_DATA = {};
            WMODEL_DATA.mode = null;
        WMODEL_DATA.isPreview = false;
        WMODEL_DATA.editionName = "";
        WMODEL_DATA.editionDate = null;
        WMODEL_DATA.pageSize = 20;
        WMODEL_DATA.edition = null;
        WMODEL_DATA.OPTIONS = {};
        TH.installWidgetController('sidebar.content.list', 'sidebarContentList8', WMODEL_DATA, typeof controller == 'function' ? controller : null, [{name: 'DEFAULT', data: true}], ' oUhbkSMaaqbcdvVkcC', null);
        })();
        (function() {
            function controller($scope) {
    var $window = $(window);

    function checkWidth() {
        var windowsize = $window.width();
        var $element = $('div.sidebar.sidebarTapBar');
        $scope.width = windowsize;
        if(windowsize <= 1024 && $scope.edition){
            $('.fixContentRight').removeClass('fixContentRight');
            // $element.removeClass('expanded');
            // $element.addClass('tapNotExpanded');
            $('.tap').show();
        }else if($scope.edition){
            $('.tap').hide();
            $('.mainContentRow').addClass('fixContentRight');
            $element.removeClass('tapNotExpanded');
            $element.addClass('expanded');
        }
    }
    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(checkWidth);
}
            var WMODEL_DATA = {};
            WMODEL_DATA.edition = null;
        WMODEL_DATA.slot = null;
        WMODEL_DATA.OPTIONS = {};
        TH.installWidgetController('sidebar.tapBar', 'sidebar', WMODEL_DATA, typeof controller == 'function' ? controller : null, null, ' oUhbkSMadabfWVcC oUhbkSMadabbWQbVkcC', null);
        })();
        (function() {
            function controller($scope,  shareThis, TH$Dialog, TH$Service, $location) {
    $scope.getEditUrl = function(id, type) {
        if (!type || type == 'article') {
            return '/content/' + id + '/edit.html';
        } else {
            return '/dzone/staff/' + type + (type == 'refcard' ? 'z' : 's') + '/' + id + '/edit.html';
        }
    };

    $scope.share = function(socialNet, url, title){
        shareThis.shareThis(socialNet, url, title);
    };

//    $scope.mailShareLink = function(article) {
//        return 'mailto:?subject=' + encodeURIComponent(article.header.title) +  '&body=Article: ' + encodeURIComponent('https://dzone.com/' + article.header.link);
//    };

    $scope.canDelete = function(article) {
        return article.canDelete;
    };

    $scope.canPublish = function(article) {
        return article.canPublish;
    };

    $scope.canEdit = function(article) {
        return article.canEdit;
    };

    $scope.toggleComments = function(article) {
        if(!article.isLocked) {
            TH$Service.action('articles.lockNode', {type: 'node', id: article.id}).then(function(result) {
                if(result){
                    article.isLocked = true;
                    TH$Dialog.success('You have disabled all comments for this Article');
                }else{
                    TH$Dialog.error('error','Your requested was denied')
                }
            });
        }else {
            TH$Service.action('articles.unlockNode', {type: 'node', id: article.id}).then(function(result) {
                if(result){
                    article.isLocked = false;
                    TH$Dialog.success('You have enabled all comments for this Article');
                }else{
                    TH$Dialog.error('error','Your requested was denied')
                }
            });
        }
    };

    $scope.toggleLimitComments = function (article) {
        if (!article.isLimited) {
            TH$Service.action('articles.limitNode', {type: 'node', id: article.id}).then(function (result) {
                if (result) {
                    article.isLimited = true;
                    TH$Dialog.success('You have limited comments for this Article. Now all comments will go through moderation.');
                } else {
                    TH$Dialog.error('error', 'Your requested was denied')
                }
            });
        } else {
            TH$Service.action('articles.unlimitNode', {type: 'node', id: article.id}).then(function (result) {
                if (result) {
                    article.isLimited = false;
                    TH$Dialog.success('You removed the limits for comments on this Article');
                } else {
                    TH$Dialog.error('error', 'Your requested was denied')
                }
            });
        }
    };

    $scope.shareTwitter = function($event, title, url){

        $event.preventDefault();
        $event.stopPropagation();
        var twitter = 'https://twitter.com/intent/tweet';
        var link = $location.protocol() + '://' + location.host + url;
        var ref = location.host;
        var params = '?text='+title+'&url='+link+'&ref=dzone.com&via=DZone';
        var win = window.open(twitter+params, '_blank');
        win.focus();
    };

    $scope.edit = function(link) {
        TH$Dialog.open({
            loadWidget: 'links.postPreview',
            widgetArgs: {
                edit: link.id
            },
            size: 'xbig'
        }).then(function (result) {
            $scope.link.title = result.title;
            $scope.link.linkDescription = result.content;
            $scope.link.thumb = result.thumb;
            $scope.link.tags = result.topics;
        });
    };

    $scope.deleteLink = function(article) {
        var title = article.title;
        var type = 'link';
        if(article.header){
            title = (article.header.type == 'article') ? article.header.title : article.title;
            type = (article.header.type == 'article') ? 'article' : 'link';
        }
        TH$Dialog.confirm('Do you want to delete "' + title + '"?').then(function() {
            return TH$Service.action('delete', {type: type, id: article.id});
        }).then(function() {
            article.deleted = true;
        });
    };
}


            var WMODEL_DATA = {};
            WMODEL_DATA.OPTIONS = {};
        TH.installWidgetController('content.commentsSlider', 'contentCommentsSlider7', WMODEL_DATA, typeof controller == 'function' ? controller : null, null, ' oUhbaqbcaibvnWffWVcC', null);
        })();
        (function() {
            
            var WMODEL_DATA = {};
            WMODEL_DATA.name = "commentsSlider";
        WMODEL_DATA.slot = null;
        WMODEL_DATA.OPTIONS = {"name":"commentsSlider"};
        TH.installWidgetController('components.slider', 'componentsSlider6', WMODEL_DATA, typeof controller == 'function' ? controller : null, null, ' oUhballbvbdSaoUhM', null);
        })();