Last active
February 14, 2018 12:01
-
-
Save aal89/7c2669fc5115ce2a1351f6c2a1392ea8 to your computer and use it in GitHub Desktop.
FizzBuzz Swift 4 + functional solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Single line 84 chars, not really an accepted answer (???). | |
| // It prints an array containing the right answers in the right order, but not each individual number, just this array. | |
| print((1...100).map{$0%3==0 ? $0%5==0 ? "FizzBuzz":"Fizz":$0%5==0 ? "Buzz":"\($0)"}) | |
| // Slightly adjusted version to make it an accepted answer, increasing byte count to 92 | |
| (1...100).map{$0%3==0 ? $0%5==0 ? "FizzBuzz":"Fizz":$0%5==0 ? "Buzz":"\($0)"}.map{print($0)} | |
| // Single line 100 chars, not really a readable solution, but it also prints each individual number. | |
| // One extra map call dissolved into individual print calls. | |
| (1...100).map{$0%3==0 ? $0%5==0 ? print("FizzBuzz"):print("Fizz"):$0%5==0 ? print("Buzz"):print($0)} | |
| // More expanded version of the above version, you can actually see what is going on here now. | |
| // Note that the if statements are also reordered to conceive a somewhat more 'logical' structure. | |
| (1...100).map { (number) in | |
| number % 5 == 0 && number % 3 == 0 ? print("FizzBuzz") : | |
| number % 5 == 0 ? print("Buzz") : | |
| number % 3 == 0 ? print("Fizz") : print(number) | |
| } | |
| // Let's make this a pure functional side-effect free version of the earlier mentioned ones. | |
| // Aside from the ternary if statements this version is way more readable and maintainable. Let alone the | |
| // newly created functional methods which you can also use outside this use case, they don't assume state or | |
| // alter data. The .map is being replaced by a .forEach, this version is no longer trying to compete with the | |
| // smalles (aka fewest bytes) implementation, therefore the .map is useless (it returns an array which is not being | |
| // handled, whereas the forEach won't and it semantically makes more sense). | |
| let multipleOfFive: (Int) -> Bool = { $0 % 5 == 0 } | |
| let multipleOfThree: (Int) -> Bool = { $0 % 3 == 0 } | |
| let multipleOfBoth: (Int) -> Bool = { multipleOfFive($0) && multipleOfThree($0) } | |
| (1...100).forEach { (number) in | |
| multipleOfBoth(number) ? print("FizzBuzz") : | |
| multipleOfFive(number) ? print("Buzz") : | |
| multipleOfThree(number) ? print("Fizz") : print(number) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment