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

Crypto.java 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. return getNormalizedCipherText().replaceAll("\\s", "");
  43. }
  44. public String getNormalizedCipherText() {
  45. StringBuilder cipherText = new StringBuilder(normalizedPlaintext.length());
  46. for (int index = 0; index < squareSize; index++) {
  47. for (String segment : getPlaintextSegments()) {
  48. if (index < segment.length()) {
  49. cipherText.append(segment.charAt(index));
  50. }
  51. }
  52. if (index < squareSize - 1) {
  53. cipherText.append(" ");
  54. }
  55. }
  56. return cipherText.toString();
  57. }
  58. }