Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- namespace _307_intermediate {
- class ScrabbleProblemSolver {
- static void Main(string[] args) {
- string path = (@"../../enable1.txt");
- string[] lines = File.ReadAllLines(path);
- List<string> longestChain = new List<string>();
- var twoLetterWords = lines.Where(l => l.Length == 2);
- foreach (var word in twoLetterWords) {
- List<string> currentChain = RecursiveCheck(word, lines, longestChain, new List<string>());
- if (currentChain.Count > longestChain.Count) {
- longestChain = currentChain;
- }
- }
- if (longestChain.Count == 0) {
- Console.WriteLine("There don't seem to be any words in this file.");
- } else {
- Console.WriteLine("The longest word we can build using this method is {0} characters long.", longestChain.Last().Length);
- Console.WriteLine("It's {0}.", longestChain.Last());
- if (longestChain.Count > 1) {
- Console.WriteLine("Here's the full chain:");
- foreach (var word in longestChain) {
- Console.WriteLine("{0} - {1}", word.Length, word);
- }
- }
- }
- Console.WriteLine("Press Enter to exit.");
- Console.ReadLine();
- }
- static List<string> RecursiveCheck(string word, string[] words, List<string> longestChain, List<string> previousChain) {
- List<string> currentChain = new List<string>(previousChain);
- currentChain.Add(word);
- var longerWords = words.Where(w => w.Contains(word) && w.Length > word.Length).OrderBy(w => w.Length);
- if (longerWords.Count() == 0) {
- return currentChain;
- }
- if (longerWords.Last().Length <= (longestChain.Count - 1)) {
- // no point in continuing to go down this route
- return currentChain;
- }
- List<string> returnChain = new List<string>(currentChain);
- foreach (var longerWord in longerWords.Where(w => w.Length == word.Length + 1)) {
- List<string> newChain = RecursiveCheck(longerWord, longerWords.ToArray(), longestChain, currentChain);
- if (newChain.Count > returnChain.Count) {
- returnChain = newChain;
- }
- }
- return returnChain;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement