Created
April 22, 2016 05:14
-
-
Save VallaDanger/db1e6dd57de07ac6dbb8703c8914ffd8 to your computer and use it in GitHub Desktop.
FizzBuzz Java (using CharSequence)
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
public class Main { | |
public static void main(String[] args) throws Exception { | |
System.out.println(new StringBuilderFizzBuzz(100).get()); | |
System.out.println(new StringFizzBuzz(100).get()); | |
} | |
private static abstract class FizzBuzz<C extends CharSequence> { | |
private final int limit; | |
private final C appendable; | |
FizzBuzz(int limit, C appendable) { | |
this.limit = limit; | |
this.appendable = build(appendable, 1); | |
} | |
private C build(C appendable, int i) { | |
if(i%3 == 0) { | |
appendable = append(appendable, "Fizz"); | |
} | |
if(i%5 == 0) { | |
appendable = append(appendable, "Buzz"); | |
} else if(i%3 != 0) { | |
appendable = append(appendable, Integer.toString(i,10)); | |
} | |
return (i < this.limit) ? build(append(appendable, ","), ++i) : appendable; | |
} | |
abstract C append(C appendable, String value); | |
C get() { | |
return this.appendable; | |
} | |
} | |
private static class StringBuilderFizzBuzz extends FizzBuzz<StringBuilder> { | |
StringBuilderFizzBuzz(int i) { | |
super(i, new StringBuilder()); | |
} | |
@Override | |
StringBuilder append(StringBuilder appendable, String value) { | |
return appendable.append(value); | |
} | |
} | |
private static class StringFizzBuzz extends FizzBuzz<String> { | |
StringFizzBuzz(int i) { | |
super(i, ""); | |
} | |
@Override | |
String append(String appendable, String value) { | |
appendable = appendable + value; | |
return appendable; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
absolutely unnecessary way to solve the FizzBuzz problem, but yet another way to solve it...