lots of exercises in java... from https://github.com/exercism/java

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class Crypto {
  4. private String normalizedPlaintext;
  5. private int squareSize;
  6. public Crypto(String text) {
  7. this.normalizedPlaintext = normalizeText(text);
  8. this.squareSize = calculateSquareSize(normalizedPlaintext);
  9. }
  10. public String getNormalizedPlaintext() {
  11. return normalizedPlaintext;
  12. }
  13. public int getSquareSize() {
  14. return squareSize;
  15. }
  16. private static String normalizeText(String text) {
  17. return text.toLowerCase().codePoints()
  18. .filter(x -> Character.isLetterOrDigit(x))
  19. .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
  20. .toString();
  21. }
  22. private static int calculateSquareSize(String text) {
  23. return (int) Math.ceil(Math.sqrt(text.length()));
  24. }
  25. public List<String> getPlaintextSegments() {
  26. return getSegmentText(normalizedPlaintext, squareSize);
  27. }
  28. private static List<String> getSegmentText(String text, int squareSize) {
  29. List<String> segments = new ArrayList<>();
  30. int index = 0;
  31. while (index < text.length()) {
  32. if (index + squareSize < text.length()) {
  33. segments.add(text.substring(index, index + squareSize));
  34. } else {
  35. segments.add(text.substring(index));
  36. }
  37. index += squareSize;
  38. }
  39. return segments;
  40. }
  41. public String getCipherText() {
  42. StringBuilder cipherText = new StringBuilder(normalizedPlaintext.length());
  43. for (int index = 0; index < squareSize; index++) {
  44. for (String segment : getPlaintextSegments()) {
  45. if (index < segment.length()) {
  46. cipherText.append(segment.charAt(index));
  47. }
  48. }
  49. }
  50. return cipherText.toString();
  51. }
  52. public String getNormalizedCipherText() {
  53. String cipher = getCipherText();
  54. return String.join(" ", getSegmentText(cipher, squareSize - 1));
  55. }
  56. }