using System.Collections.Generic;
public static void Main()
Console.WriteLine("PART 1");
var okPasswords = FindOkPasswords(138307, 654504, false);
foreach (int okPassword in okPasswords)
Console.WriteLine(String.Format("{0,6} is ok", okPassword));
Console.WriteLine("Total ok passwords found (part 1): " + okPasswords.Count);
Console.WriteLine("================================");
Console.WriteLine("PART 2");
okPasswords = FindOkPasswords(138307, 654504, true);
foreach (int okPassword in okPasswords)
Console.WriteLine(String.Format("{0,6} is ok", okPassword));
Console.WriteLine("Total ok passwords found (part 2): " + okPasswords.Count);
private static List<int> FindOkPasswords(int beginRange, int endRange, bool onlyAllowAdjacentsThatAreNotPartOfLargerGroup)
var retval = new List<int>();
for (int i=beginRange; i<=endRange; i++)
if (IsOkPassword(i.ToString(), onlyAllowAdjacentsThatAreNotPartOfLargerGroup)) retval.Add(i);
private static bool IsOkPassword(string password, bool onlyAllowAdjacentsThatAreNotPartOfLargerGroup)
bool foundAnyRepeating = false;
bool foundAdjacentsThatAreNotPartOfLargerGroup = false;
int consecutiveRepeating = 0;
foreach (char character in password)
if (character.Equals(previousChar))
foundAnyRepeating = true;
if (consecutiveRepeating == 1) foundAdjacentsThatAreNotPartOfLargerGroup = true;
consecutiveRepeating = 0;
if (character < previousChar) return false;
previousChar = character;
if (consecutiveRepeating == 1) foundAdjacentsThatAreNotPartOfLargerGroup = true;
return onlyAllowAdjacentsThatAreNotPartOfLargerGroup ? foundAdjacentsThatAreNotPartOfLargerGroup : foundAnyRepeating;