Skip to content

Instantly share code, notes, and snippets.

@gunr2171
Created September 30, 2015 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunr2171/9860b0b6715d86b91298 to your computer and use it in GitHub Desktop.
Save gunr2171/9860b0b6715d86b91298 to your computer and use it in GitHub Desktop.
A solution to the problem in the comment of Main
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