Created
September 30, 2015 13:38
-
-
Save gunr2171/9860b0b6715d86b91298 to your computer and use it in GitHub Desktop.
A solution to the problem in the comment of Main
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace TameWildWordChain | |
{ | |
class Program | |
{ | |
private static List<string> fourLetterWords; | |
static void Main(string[] args) | |
{ | |
/* | |
* Tuesday, September 29, 2015 | |
* In this word ladder, go from TAME to WILD in four steps, | |
* changing one letter at a time to form a common English word | |
* at each step. We found three solutions | |
* | |
* TAME | |
* ---- | |
* ---- | |
* ---- | |
* WILD | |
*/ | |
fourLetterWords = GetFourLetterWords(); | |
foreach (var solution in EnumSolutions()) | |
{ | |
foreach (var word in solution) | |
{ | |
Console.WriteLine(word); | |
} | |
Console.WriteLine(); | |
} | |
Console.ReadLine(); | |
} | |
private static IEnumerable<List<string>> EnumSolutions() | |
{ | |
var firstWord = "tame"; | |
var fifthWord = "wild"; | |
foreach (var secondWord in EnumNextWordsInLadder(firstWord)) | |
{ | |
foreach (var thirdWord in EnumNextWordsInLadder(secondWord)) | |
{ | |
foreach (var forthWord in EnumNextWordsInLadder(thirdWord)) | |
{ | |
//check if the forth word can be transformed into the fifth word | |
var forthWordValid = EnumNextWordsInLadder(forthWord) | |
.Any(x => x == fifthWord); | |
if (forthWordValid) | |
{ | |
yield return new List<string>() | |
{ | |
firstWord, | |
secondWord, | |
thirdWord, | |
forthWord, | |
fifthWord | |
}; | |
} | |
} | |
} | |
} | |
} | |
private static IEnumerable<string> EnumNextWordsInLadder(string baseWord) | |
{ | |
var indexPositionsToModify = Enumerable.Range(0, 4); | |
foreach (var index in indexPositionsToModify) | |
{ | |
foreach (var possibleNextWord in EnumWordsThatMatchIndexModification(baseWord, index).Distinct()) | |
{ | |
yield return possibleNextWord; | |
} | |
} | |
} | |
private static IEnumerable<string> EnumWordsThatMatchIndexModification(string baseWord, int modificationIndex) | |
{ | |
var matchingWords = fourLetterWords.Select(x => x); | |
foreach (var index in Enumerable.Range(0, 4)) | |
{ | |
var i = index; | |
matchingWords = matchingWords | |
.Where(x => | |
{ | |
if (modificationIndex == i) | |
return true; | |
else | |
return x[i] == baseWord[i]; | |
}); | |
} | |
return matchingWords; | |
} | |
private static List<string> GetFourLetterWords() | |
{ | |
return File.ReadAllLines("wordsEn.txt") | |
.Where(x => x.Count() == 4) | |
.ToList(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment