Tuesday, August 13, 2019

FizzBuzz

FizzBuzz is a pretty basic problem yet interesting for different purposes. It has been used in a variety of situations :

1) As a kids game as pointed out by wikipedia article, FizzBuzz

2) As a job interview question for programming related posts as pointed out in a 2007 article on by Mr Imran on Using FizzBuzz to Find Developers who Grok Coding.

3) For online judge contests and challenges like HackerRank

The question may be used in coding interview for good reasons as discussed by CodingHorror article, Why Can't Programmers.. Program?

Some of us might be wondering why a ~ 2007 problem is still relevant in 2019! This question has been answered already by a hackernoon article, Why I’m still using “Fizz Buzz” to hire Software-Developers

Many more approaches along with their variations have been discussed at
a) FizzBuzz Solution Dumping Ground
b) FizzBuzz JavaScript solution
c) HackerNews: What's the shortest FizzBuzz you can write? What language?    (discussion on Anarchy Golf : FizzBuzz)
d) Twenty Ways to FizzBuzz, An exercise in Javascript
e) FizzBuzz In Too Much Detail

The hackerrank challenge specially asks for the shortest code. The ability to write a short code depends on the minimum requirement of boilerplate code. In Java we can reduce length of the codef based on identifier(s), parentheses, ternary operator, line breaks, pre/post increment, re-writing n%3==0 conditions with greater-than (or less-than operators) as follows.
class S{public static void main(String[]a){for(int i=0;++i<101 i="" ystem.out.println="">0?i%5>0?i:"Buzz":i%5>0?"Fizz":"FizzBuzz");}}

Using javascript, we make it even shorter. We may need to remind ourselves that writing unreadable, difficult to maintain, is not recommended. Java, C, C++, C#, Python, Ruby, R, none of the submissions in these languages reached the top score yet which is 16.0. It leads us to the question, which submission led to the top score? The answer is bash script (proof). How? The hint has been kindly provided by the author of the top submission, Byron Formwalt at here.

If we are new to bash scripting, we may wish to get started with few resources mentioned here, here, and here. The Advanced Bash-Scripting (ABS) Guide (HTML, PDF) from The Linux Documentation Project (LDP) may be a good starting point.

Disclaimer: Even though this may be suitable for the purpose of the getting higher score in hackerrank or just for exercise, it may not be a part of best coding practices. There are many scopes for improvement in this post. Suggestions are welcome. .

No comments: