Added Java solutions from Anton
[ou-summer-of-code-2017.git] / anton / SummerOfCode / src / summerofcode / Day3.java
1 package summerofcode;
2
3 /**
4 *
5 * @author Anton Dil
6 */
7 public class Day3
8 {
9 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.";
10
11 public static void main(String[] args)
12 {
13 part1();
14 System.out.println("\n PART 2 ");
15 part2();
16 }
17
18 static void part2()
19 {
20 int[] newcode =
21 {
22 ci('r'), ci('i')
23 };
24
25 final int alpha = 5, beta = 11;
26
27 System.out.printf("newcode %d %d %n", newcode[0], newcode[1]);
28
29 for (int i = 0; i < pass.length(); i++)
30 {
31 char nextCh = pass.charAt(i);
32
33 if (nextCh >= 'a' && nextCh <= 'z')
34 {
35 newcode[0] = wrap2(newcode[0] + alpha * newcode[1]);
36 newcode[1] = wrap2(newcode[1] + beta * ci(nextCh));
37
38 System.out.printf("nextchar %c newcode %c %c %n", nextCh, ic(newcode[0]), ic(newcode[1]));
39 } //else skip this char
40
41 }
42 }
43
44 static void part1()
45 {
46 //assuming string length > 1
47 int[] oldcode =
48 {
49 ci(pass.charAt(0)), ci(pass.charAt(1))
50 };
51
52 System.out.printf("oldcode %d %d %n", oldcode[0], oldcode[1]);
53
54 for (int i = 2; i < pass.length(); i++)
55 {
56 char nextCh = pass.charAt(i);
57
58 if (nextCh >= 'a' && nextCh <= 'z')
59 {
60 //System.out.printf(" next char %c %d %n", nextCh, ci(nextCh));
61 oldcode[0] = wrap(oldcode[0] + oldcode[1]);
62 oldcode[1] = wrap(oldcode[1] + ci(nextCh));
63
64 System.out.printf("next char %c oldcode %c %c %n", nextCh, ic(oldcode[0]), ic(oldcode[1]));
65 } //else skip this char
66
67 }
68 }
69
70 //char conversion to int scale, 1-based
71 static int ci(char c)
72 {
73 return c - 'a' + 1;
74 }
75
76 //for readability, the int in char form
77 static char ic(int x)
78 {
79 return (char) (x + 'a' - 1);
80 }
81
82 //oldwrap only needed adjustment by 26
83 static int wrap(int x)
84 {
85 if (x > 26)
86 {
87 return x - 26;
88 }
89
90 return x;
91 }
92
93 //new wrap needs a modulus
94 static int wrap2(int x)
95 {
96 if (x > 26)
97 {
98 return (x - 1) % 26 + 1;
99 }
100
101 return x;
102 }
103
104 }