-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11.cs
125 lines (99 loc) · 2.53 KB
/
11.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using System;
using System.Collections.Generic;
using System.Linq;
namespace Application
{
class Day11
{
public static void Main(string[] args)
{
System.Console.WriteLine (String.Join(
",",
new PasswordGenerator ("hxbxwxba").Take (2).ToArray()
));
}
}
class PasswordGenerator : IEnumerable<String> {
String basePassword;
public PasswordGenerator(String basePassword) {
this.basePassword = basePassword;
}
public IEnumerator<String> GetEnumerator ()
{
String password = basePassword;
while (true) {
password = NextString (password);
if (!IsValid(password)) {
continue;
}
yield return password;
}
}
private static bool IsValid(String password) {
System.Console.Write ("Next candidate " + password + " ");
var valid = ContainsNoAmbiguousChars (password) &&
ContainsRisingSequence (password) &&
ContainsTwoPairs (password);
System.Console.WriteLine ();
return valid;
}
private static bool ContainsNoAmbiguousChars (string password)
{
var valid = !password.Contains ("i") &&
!password.Contains ("o") &&
!password.Contains ("l");
System.Console.Write (valid ? "Y" : "N");
return valid;
}
private static bool ContainsRisingSequence (string password)
{
var chars = password.ToCharArray();
var sequenceLength = 1;
char previousChar = chars[0];
for (int i = 1; i < chars.Length; i++) {
if (chars [i] == previousChar + 1) {
sequenceLength++;
if (sequenceLength == 3) {
System.Console.Write ("Y");
return true;
}
} else {
sequenceLength = 1;
}
previousChar = chars [i];
}
System.Console.Write ("N");
return false;
}
private static bool ContainsTwoPairs (string password)
{
var chars = password.ToCharArray();
char previousChar = chars[0];
var pairCount = 0;
for (int i = 1; i < chars.Length; i++) {
if (chars [i] == previousChar) {
pairCount++;
i++;
if (i == chars.Length) {
break;
}
}
previousChar = chars [i];
}
System.Console.Write (pairCount > 1 ? "Y" : "N");
return pairCount > 1;
}
private static String NextString(String password) {
int length = password.Length;
char c = password[length - 1];
if (c == 'z') {
return NextString (password.Substring (0, length - 1)) + 'a';
}
return String.Format("{0}{1}", password.Substring (0, length - 1), (char)((int) c + 1));
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
}
}