With let, let*, named-let, and, or, cond clause with arrow notation, internal definitions, varargs, and load support.
Source code is on GitHub
With let, let*, named-let, and, or, cond clause with arrow notation, internal definitions, varargs, and load support.
Source code is on GitHub
I came across this programming exercise on GitHub.
Test 1: FizzBuzzBasic: Write some code that prints out the following for a contiguous range of numbers:
the number
‘fizz’ for numbers that are multiples of 3
‘buzz’ for numbers that are multiples of 5
‘fizzbuzz’ for numbers that are multiples of 15
e.g. if I run the program over a range from 1-20 I should get the following output:
#!console
1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz
The Java solution I’ve found at the same location is listed below.
package codingtests.fizzbuzz; import com.google.common.base.Preconditions; import java.io.PrintStream; import java.util.*; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; public class FizzBuzzBasic { public static void main(String... arguments) { FizzBuzzBasic fb = new FizzBuzzBasic(); fb.checkCommandLineArguments(arguments); fb.convertToFizzBuzzAndOut(Integer.valueOf(arguments[0]), System.out); } public void convertToFizzBuzzAndOut(int upperBound, PrintStream out){ getFizzBuzzValuesForNumbers(1,upperBound).stream().forEach(out::println); } public void checkCommandLineArguments(String... arguments){ Preconditions.checkArgument(arguments.length == 1, "Program must get exactly one argument"); try{ Integer.valueOf(arguments[0]); } catch (NumberFormatException ex){ throw new IllegalArgumentException("Argument must be a valid number"); } } public List<String> getFizzBuzzValuesForNumbers(int firstNumber, int lastNumber){ return IntStream.range(firstNumber,lastNumber+1).mapToObj(this::convertNumberToFizzBuzz).collect(Collectors.toList()); } public String convertNumberToFizzBuzz(int number){ Preconditions.checkArgument(number > 0,"Number should be greater than 0!"); if (number % 15 == 0) return "fizzbuzz"; if (number % 3 == 0) return "fizz"; if (number % 5 == 0) return "buzz"; return String.valueOf(number); } }
The Ruby solution I’ve came up with is cited below.
(1..20).lazy.map {|n| if (n % 15) == 0; 'fizzbuzz' elsif (n % 5) == 0; 'buzz' elsif (n % 3) == 0; 'fizz' else n end}.each {|x| print "#{x} "}
Expressing the solution in Ruby is easy and straightforward. It’s actually a one-liner. Easy to read and understand. The Java solution is way more verbose and obscure.