Added Java solutions from Anton
[ou-summer-of-code-2017.git] / anton / SummerOfCode / src / summerofcode / Day3.java
diff --git a/anton/SummerOfCode/src/summerofcode/Day3.java b/anton/SummerOfCode/src/summerofcode/Day3.java
new file mode 100644 (file)
index 0000000..b6f082a
--- /dev/null
@@ -0,0 +1,104 @@
+package summerofcode;\r
+\r
+/**\r
+ *\r
+ * @author Anton Dil\r
+ */\r
+public class Day3\r
+{\r
+   static final String pass = "the traveller in the grey riding-coat, who called himself mr. melville, was contemplating the malice of which the gods are capable.";\r
+\r
+   public static void main(String[] args)\r
+   {\r
+      part1();\r
+      System.out.println("\n PART 2 ");\r
+      part2();\r
+   }\r
+\r
+   static void part2()\r
+   {\r
+      int[] newcode =\r
+      {\r
+         ci('r'), ci('i')\r
+      };\r
+\r
+      final int alpha = 5, beta = 11;\r
+\r
+      System.out.printf("newcode %d %d %n", newcode[0], newcode[1]);\r
+\r
+      for (int i = 0; i < pass.length(); i++)\r
+      {\r
+         char nextCh = pass.charAt(i);\r
+\r
+         if (nextCh >= 'a' && nextCh <= 'z')\r
+         {\r
+            newcode[0] = wrap2(newcode[0] + alpha * newcode[1]);\r
+            newcode[1] = wrap2(newcode[1] + beta * ci(nextCh));\r
+\r
+            System.out.printf("nextchar %c newcode %c %c %n", nextCh, ic(newcode[0]), ic(newcode[1]));\r
+         } //else skip this char\r
+\r
+      }\r
+   }\r
+\r
+   static void part1()\r
+   {\r
+      //assuming string length > 1\r
+      int[] oldcode =\r
+      {\r
+         ci(pass.charAt(0)), ci(pass.charAt(1))\r
+      };\r
+\r
+      System.out.printf("oldcode %d %d %n", oldcode[0], oldcode[1]);\r
+\r
+      for (int i = 2; i < pass.length(); i++)\r
+      {\r
+         char nextCh = pass.charAt(i);\r
+\r
+         if (nextCh >= 'a' && nextCh <= 'z')\r
+         {\r
+            //System.out.printf(" next char %c %d %n", nextCh, ci(nextCh));\r
+            oldcode[0] = wrap(oldcode[0] + oldcode[1]);\r
+            oldcode[1] = wrap(oldcode[1] + ci(nextCh));\r
+\r
+            System.out.printf("next char %c oldcode %c %c %n", nextCh, ic(oldcode[0]), ic(oldcode[1]));\r
+         } //else skip this char\r
+\r
+      }\r
+   }\r
+\r
+   //char conversion to int scale, 1-based\r
+   static int ci(char c)\r
+   {\r
+      return c - 'a' + 1;\r
+   }\r
+\r
+   //for readability, the int in char form\r
+   static char ic(int x)\r
+   {\r
+      return (char) (x + 'a' - 1);\r
+   }\r
+\r
+   //oldwrap only needed adjustment by 26\r
+   static int wrap(int x)\r
+   {\r
+      if (x > 26)\r
+      {\r
+         return x - 26;\r
+      }\r
+\r
+      return x;\r
+   }\r
+\r
+   //new wrap needs a modulus\r
+   static int wrap2(int x)\r
+   {\r
+      if (x > 26)\r
+      {\r
+         return (x - 1) % 26 + 1;\r
+      }\r
+\r
+      return x;\r
+   }\r
+\r
+}\r