Source. Try the problem first if you want. /// Edited Below Ah. The Fizzbuzz problem. This question has struck a questionable and irrational fear in many programmers by its prevalence in job interview's questionnaires. It's simple question which is designed to make you overthink the problem. It has four simple requirements :
When I wrote the program in Rust (I've written it before in Java without much worries), I wanted it to be easily read and efficient. So, here is my attempt: Edited: Special thanks to reddit user l-arkham, for suggesting the usage of use FizzBuzzOptions::*; to bring the varients of the enumeration into a global scope, which allows for cleaner, more readable code. main.rs
Let us walk through it.
First thing is the enumeration FizzBuzzOptions, which (I think) helps the programmer handle the concepts of the requirements with a little abstraction. FizzBuzzOptions contains four enums, one for each requirement (FizzBuzz, Buzz, Fizz and Neither). Next is the function matching, which returns the appropriate FizzBuzzOption[s]. This is were the ordering of the if statements matters, as well as the fourth requirement's weird wording "multiples of both three and five", which means a multiple of fifteen. Whether x % 15 == 0 is true must be checked first before both x % 5 == 0 and x % 3 == 0. Lastly the main function, which contains the loop for x in 1..101 (Note: Rust lists .. are inclusive on the left, and exclusive on the right, so 1..5 means [1, 2, 3, 4]). The match statement calls matching for each x and compares the return to the list of options, picks the FizzBuzzOption[s] that matches (funny that), and executes the println!(). Nice and simple, and very easy to read. Some notes :
That's it. Thanks for reading. - Gutrix
0 Comments
Leave a Reply. |
ArchivesCategories |