Introducing the Coding Challenge

Welcome to the Coding Challenge.

Here I will post a coding challenge every few days that you can solve. There will be easy ones and hard ones, pretty mixed.

How does it work?

  • Try to solve the challenge in whatever language you find fitting
    • You can use a new language you always wanted to learn or show off your golfing skills
  • Post a comment containing your code (in ```code here```) and some info on how the code works or what is remarkable
  • Optional: Create a post with the tag #coding-solution
    • In that post walk other users through the process of solving your challenge. That way they can learn and try it out on the next one
  • Optional: Read and review other peoples code, try to find bugs, give feedback and learn

Why even bother?

  • Training is everything, the more you train your mind to think in code, the better you are prepared
  • You may learn a few new tricks from reading other solutions
  • I will send tips for really good solutions (and use the liquid rewards of this post for it too)
  • You may get recruited if someone likes your code (f.e. I am looking for talents)

Challenge #1 – FizzBuzz

This challenge is a pretty basic one, but the devil lies in the detail.

Implement a fizzbuzz function taking an integer n that abides to these specifications:

  • if n is a multiple of 3, print Fizz
  • if n is a multiple of 5, print Buzz
  • if n is a multiple of 3 and a multiple of 5, print FizzBuzz
  • in all other cases print the number

Also create a snippet or main function that calls fizzbuzz for all values from 0 to 100, ascending.

Remarks:

  • If you use a pure functional language, try returning a string instead of using a print Monad (both are allowed)
  • Bonus points for:
    • handling edge cases
    • good coding practices and modularity
    • useful and meaningful tests
    • beautiful (readable, self-documenting) code

Please keep the #coding-challenge tag clean of solutions.

Sort:  

Alright, here's my solution: https://jsfiddle.net/jf68mfj1/2/

I went for some solutions that may not be "good coding practices" depending on who you ask, because I wanted to explore JavaScript a bit further than a basic for-loop and if-statement.

Here's the main fizzBuzz function:

function fizzBuzz(num) {
    let returnValue = '';
    if (num % 3 === 0) returnValue += 'Fizz';
    if (num % 5 === 0) returnValue += 'Buzz';
    return returnValue || String(num);
}

Like others I concatenate Fizz and Buzz so I don't need a third if-statement. As a bonus I use JavaScript's type coercion to check if returnValue is truthy, and if it's not (an empty string '' is falsy) I return the original number. Initially I returned it as an integer too, but returning mixed types is bad practice and in fact actually broke my tests, so I return it a as string now too.

Fizzing from 0 to 100 I do with this method:

function fizzTo100() {
    const allFizzBuzzes = [...Array(100).keys()].map(fizzBuzz);
    output(allFizzBuzzes.join('\n'));
}

The first line looks a bit like a hack. What I do is create an array of 100 length and then take the keys from that array. All the values are still undefined, but the keys are 0-100. The result of keys() is an iterable though, so I turn it back into an array using the spread operator in a new array [...x].
Now I have an array of 1-100 that I can map to fizzBuzz.

See and test my code here: https://jsfiddle.net/jf68mfj1/2/

If anyone is interested in more details let me know and I'll write a blog post about it. Not going throught that effort if nobody cares though ;)

This is really neat. Well done

+1 for

Initially I returned it as an integer too, but returning mixed types is bad practice and in fact actually broke my tests, so I return it a as string now too.

and for having a test that breaks when this is not the case, tip! worthy :)

The || is a pretty clean way, I like that!

Your explanation on why you used the spread operator is glorious! Thank you for giving insight into why you used that :)

I would definitely read a blog post about it. But if you want to save your efforts for a harder challenge, a new one will come up pretty soon :)

Hi @pilcrow! You have just received a 0.5 SBD tip from @reggaemuffin!


@tipU quick guide | How to check your pending payouts.

Thank you for the insights.

You're on fire!

You've made my day.

You're a wizard at this!

I learned a lot, thanks!

Great content!

Well explained.

Well crafted.

You've exceeded my expectations.

Well crafted.

You've got a gift for this.

You've got what it takes.

Keep it up!

I'm inspired!

Keep sharing such content.

Warning,

This user was downvoted or is blacklisted likely due to farming, phishing, spamming, ID theft, plagiarism, or any other cybercrime operation. Please do your due diligence before interacting with it.

If anyone believes that this is a false flag or a mistake, consider reaching the watchers on Discord.

Thank you,

Two solutions with Haskell: http://codepad.org/tIR16emr

Screen Shot 2017-08-17 at 9.21.12 PM.png

Thank you for your submission! I really hoped that I get a Haskell one 🐑

Your first solution is pretty concise, not much to say there. The second one is really cool! Abstracting it as rules is smart and that filter reduces logic duplication.

I think you can make this a bit more readable with making rules a constant and extracting the tester in a helper function that has a good name.

Looking forward to you writing a post on how your process was, implementing the second version of it.

Only comment I have is the question asked for 0 to 100 but the solutions are for 1..100. How does either solution work for 0? Dealing with 0 shouldn't be too difficult, though 0/x is going to be 0 and 0 mod x is also 0. I guess it will/should print FizzBuzz for n=0.

True his solution starts at 1, good catch, here is a tip! But yeah it will work with 0, pretty sure.

Hi @ratticus! You have just received a 0.5 SBD tip from @reggaemuffin!


@tipU quick guide | How to check your pending payouts.

I don't know what you mean by

making rules a constant

It's already a constant there.

Since the filter phrase used once and it's a short one, I'd argue it's easier to read it this way.

I implemented/borrowed the second one because I wanted to have a generic solution that is easy to expand or change with new rules. Now, all you need is to update the rules to get a new FizzBuzz.

I'm from a Java background but here is my amateur Python submission. Started learning Python recently and fell in love with it so I thought I'd give this a try.

def fizzbuzz(n):

    string = ""

    try:
        if n%3 == 0:
            string += "Fizz"
        if n%5 == 0:
            string += "Buzz"
        else:
            string = n

        return string

    except TypeError:
        return "Error: Not a Number!"

def main():
    for n in range(101):
        print(fizzbuzz(n))

if __name__ == '__main__':
    main()

Explanation: The modulo operator(%) returns the remainder of a division. For example 8%5 will give us 3. When a number is fully dividable by another number it will return 0 thus checking if the remainder of a division is 0 we know that the number is fully dividable by the other which makes it a multiple of that number.

EDIT After posting my solution which is pretty much my level of Python I decided to do some research to see how the solution could be optimized and this is when I came across this gloriously ugly Python one-liner here that does exactly the same thing as my script of 23 lines so I thought I'd share it:

print('\n'.join("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i) for i in range(0,101)))

This made me a little depressed.

One suggestion I would have is keep the return type of fizzbuzz consistent. So I would probably do a string = str(n) to ensure it is always a string.

I also think you have a bug in there, as the else only counts for the second if, not the first one, so for n=3 is will most likely print 3 and not Fizz ;)

On coding style: I would rename the string variable to something that conveys meaning and not type, maybe return_text

The one-liner is pretty ugly in my opinion, your version is way more maintainable.

Ah man I didn't even pick up on that. Thanks for the feedback though, appreciated. As for the str(n) I actually had that in there and decided to take it out haha, don't know why though. Will keep my original answer as is so other people might learn from my mistakes :) . Here's an updated one after following your advice, not sure if it's very efficient but it doesn't have any bugs anymore lol

def fizzbuzz(n):

    try:
        if n%3 == 0 and n%5 == 0:
            text = "FizzBuzz"
        elif n%3 == 0:
            text = "Fizz"
        elif n%5 == 0:
            text = "Buzz"
        else:
            text = str(n)

        return text

    except TypeError:
        return "Error: Not a Number!"

def main():
    for n in range(101):
        print(fizzbuzz(n))

if __name__ == '__main__':
    main()

That looks pretty efficient to me :) Well done!

I like your try except btw, that is exactly the python way of asking for forgiveness, not for permission.

Here is a tip! for getting back on it and improving it :)

If you want you can look at my solution, I made a few things that make it more maintainable (but it get's longer with it) so I would love to hear your feedback on that.

And I would be glad if you would make a small post about it explaining how you tackeled the task, what your thinking was etc. :)

Thanks again, I'm looking forward to your future challenges and I'll definitely be making a post about this.

Unfortunately I'm a complete Ruby newb but your solution looks nice and self explanatory. I'm pretty sure it can be shortened but as you said, things can get long when you want to keep it maintainable and understandable.

PHP Version:
(lazy and dirty)

https://pastebin.com/q0GqCaG2

<?php

function fizzbuzz($n) {
  if (!($n % 3)) {
    $fizzbuzz .= 'Fizz';
  }
  if (!($n % 5)) {
    $fizzbuzz .= 'Buzz';
  }
  return $fizzbuzz;
}

for ($n = 0; $n <= 100; $n++) {
  echo $n . ': ';
  echo fizzbuzz($n);
  echo "\n";
}

function fizzbuzzTest() {
  echo (fizzbuzz(0) == 'FizzBuzz' ? 'passed' : 'failed') . "\n";
  echo (fizzbuzz(3) == 'Fizz' ? 'passed' : 'failed') . "\n";
  echo (fizzbuzz(6) == 'Fizz' ? 'passed' : 'failed') . "\n";
  echo (fizzbuzz(5) == 'Buzz' ? 'passed' : 'failed') . "\n";
  echo (fizzbuzz(10) == 'Buzz' ? 'passed' : 'failed') . "\n";
  echo (fizzbuzz(15) == 'FizzBuzz' ? 'passed' : 'failed') . "\n";
  echo (fizzbuzz(30) == 'FizzBuzz' ? 'passed' : 'failed') . "\n";
  echo (fizzbuzz(31) == '' ? 'passed' : 'failed') . "\n";
}

fizzbuzzTest();

I think most people will do 3 checks:

if %3 AND %5 ...
else if %3 ...
else if %5 ...

But

if %3 ...
if %5 ...

will have the same result when concatenating the strings.

You don't even have to handle n = 0 as a special case because strictly speaking 0 is a multiple of 3 and 5 because 3 * 0 is 0 and 5 * 0 is 0. Otherwise there's just another if ($n) missing.

I think you made a few errors in it ;) You only print the number if it is no fizz and no buzz :)

the implicit integer to bool conversion is scary !($n % 5) I probably would ask you to switch it if it is code i have to maintain, ($n % 5 === 0) is a bit more readable in my opinion. But you said it was quick and dirty so I won't complain :)

For your tests I would suggest you throw an exception if they fail, as no one will read test logs :)

Oh I really just forgot the "in all other cases" part... :D Actually I never print the number, only in the loop but that was just to check the result.
But I have to say that it is hard to write "good" code without a real use case. In my opinion a one-liner (like @benniebanana suggested) is often a perfect copy/paste solution for simple and unshakable logic. I like code that is confident enough to say "Don't f***ing touch me. I just work! Please do the same!"
Concerning the if-statements I find my version more readable but that's maybe only because I am so used to do it that way. But I don't see any problems with that anyway. Also the function could return null.... maybe that's an issue. But we're in the PHP world here... :P It's like asking your 8 yo child to look after your 4 yo one while you're at work. You get prettily painted walls but the cake doesn't taste that well. :D
Anyway... your competition could become very funny and educational. Keep it on!

PHP certainly is like an 8 year old looking after a 4 year old!

I'm less a fan of such confident code when it's just there without comment. If it's a one line code like the one above, I'd hope it has 2 lines of comments explaining it so you know not to mess with it.

Ooh, this is right up my alley! I'll start out with JavaScript (because I already know it) but I might switch to different languages for future challenges just for the fun of it. I'll be looking forward to these!

Looking forward to your solution :)

My Solution in plain old JS5 :)

function fizzbuzz(value) {
    if (value % 5 == 0 && value % 3 == 0) {
        console.log("FizzBuzz")
    } else if (value % 5 == 0) {
        console.log("Buzz")
    } else if (value % 3 == 0) {
        console.log("Fizz")
    } else {
        console.log(value)
    }
};

function TestNumbers() {
for (var i = 0; i < 101; i++) {
    console.log(fizzbuzz(i));
    }
};

TestNumbers();

Looks good to me ;)

Wow, Really wish I could code lol, I have tried a couple of times to learn but just not making considerable progress. I have found a niche in data analysis I am so passionate about though , I need some coding ability to succeed in this area like R,Python and SQL. Perhaps this would pave a way for me into "core coding" :). Would closely follow this and see what I can learn. Great initiative

I suggest you check out the solutions then and learn from it :) That is what this challenge is about, you can see how it can be done and learn to think that way, till you can do it yourself

Yeah I got my pen and notebook ready. Would try to understand the thought process of each solution.

I resteem your post.I am new on steemit.this is my first post.
https://steemit.com/introduceyourself/@cryptomaker/first-introduceyourself-on-steemit
Please go and upvote my first post.

I suggest you don't hijack other posts and ask for upvotes.

Here is function written in Matlab:

Test Script:

for x = 1:100
    disp(fizzbuzz(x));
end

Function:

function output = fizzbuzz(n)
% fizzbuzz(n) returns 'Fizz' if n is a multiple of 3, 
% 'Buzz' if n is a multiple of 5, 'FizzBuzz' if n is a 
% multiple of 5 and 3, and returns n if it is neither a 
% multiple of 3 or 5.
% Format of Call: fizzbuzz(n);
% Returns: output = 'Fizz', 'Buzz', 'FizzBuzz', or n 
% based on if n is a multiple of 3 or 5
    
    if ~isnumeric(n)
        error('Error: Input must be a number, not a %s.',class(n));
    else
        output = '';
        if rem(n,3) == 0
            output = 'Fizz';
        end
        if rem(n,5) == 0
            output = strcat(output,'Buzz');
        end
        if strcmp(output,'')
            output = num2str(n);
        end
    end

Console Output

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

The general design is to take the input value, check to be sure it's a number, then proceed to construct the output. Since 'FizzBuzz' is the combination of 'Fizz' and 'Buzz' it made sense to me to build the output string starting with an empty string and adding 'Fizz' if n is divisible by 3 followed by 'Buzz' if n is divisible by 5. Since they are concatinated into the empty string, 'FizzBuzz' logically follows if n is divisible by 3 and 5. Finally, if nothing was added to the output string then it must not have been divisible by either, so I assign a string form of n to the output.

I'm curious to see how far off I am from best practices for this challenge.

Interesting choice :) I like your solution.

String compare will probably be a lot slower than doing the reminder again, but if it is an optimized strcmp it will still be pretty fast.

Be sure to check a few other solutions and give feedback :)

Good point. This should be more optimized. New variable 'neither' is a boolean set to true initially and set to false if n is either divisible by 3, 5, or both. Then that becomes the check for if neither is the case.

function output = fizzbuzz(n)
% fizzbuzz(n) returns 'Fizz' if n is a multiple of 3, 
% 'Buzz' if n is a multiple of 5, 'FizzBuzz' if n is a 
% multiple of 5 and 3, and returns n if it is neither a 
% multiple of 3 or 5.
% Format of Call: fizzbuzz(n);
% Returns: output = 'Fizz', 'Buzz', 'FizzBuzz', or n 
% based on if n is a multiple of 3 or 5
    
    if ~isnumeric(n)
        error('Error: Input must be a number, not a %s.',class(n));
    else
        neither = true;
        output = '';
        if rem(n,3) == 0
            output = 'Fizz';
            neither = false;
        end
        if rem(n,5) == 0
            output = strcat(output,'Buzz');
            neither = false;
        end
        if neither
            output = num2str(n);
        end
    end

5 minute C/C++ solution. Taking more time I'd look at getting rid of the trailing ',' in the loop through the function calls, and maybe do some error checking regarding sending wrong type to the function, but for now I think this is pretty simple and the comments make it self explanatory.

Code:

#include <stdio.h>
using namespace std;

//function fizzbuzz takes in an integer and prints out the intended output for that integer
void fizzbuzz (int n) {

    //if the number is divisible by 15
    if (n%15 == 0) {
        printf("FizzBuzz, ");
    }
    //if the number is divisible by 5
    else if (n%5 == 0) {
        printf("Buzz, ");
    }
    //if the number is divisible by 3
    else if (n%3 == 0) {
        printf("Fizz, ");
    }
    //if the number is not divisible by 3 or 5 (or 15)
    else {
        printf("%i, ", n);
    }
} //END fizzbuzz

int main (int argc, char* argv[]) {

    //test casses
    printf("Test Cases: ");
    fizzbuzz(0);    //prints "FizzBuzz"
    fizzbuzz(15);   //prints "FizzBuzz"
    fizzbuzz(5);    //prints "Buzz"
    fizzbuzz(3);    //prints "Fizz"
    fizzbuzz(22);   //prints "22"
    fizzbuzz(-5);   //prints "Buzz"
    fizzbuzz(-98);  //prints "-98"
    
    printf("End Test Cases\n\n");
    
    //loop through numbers 0 to 100 and call fizzbuzz on each
    for (int i = 0; i < 101; i++) {
        fizzbuzz(i);
    }

} //END main

Console Output

Test Cases: FizzBuzz, FizzBuzz, Buzz, Fizz, 22, Buzz, -98, End Test Cases

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

My solution for python:

def fizzbuzz(n):
  multipleOf3 = n % 3
  multipleOf5 = n % 5
  
  if (multipleOf3 == 0 and multipleOf5 == 0):
    return "FizzBuzz"
  elif (multipleOf3 == 0):
    return "Fizz"
  elif (multipleOf5 == 0):
    return "Buzz"
  else:
    return n

for n in range(101):
  print(fizzbuzz(n))

One suggestion I would have is keep the return type of fizzbuzz consistent. So I would probably do a return str(n) to ensure it is always a string. And in python I would follow snake_case with my variables so multiple_of_3 would be the preferred format.

Your solution looks good and I think it it correct, well done :)

lol, snake case for python. I get it! =D
I kinda wonder about these traditions of code styles and methods. It would be cool to tell a story about the history of traditions like "hello world" and such.

Thank you for the feedback. I'm come from Java. Automatically coded in it's coding style. lols

New to Steemit?

Coin Marketplace

STEEM 0.15
TRX 0.27
JST 0.036
BTC 103489.29
ETH 2536.30
USDT 1.00
SBD 0.89