Created
June 5, 2016 12:17
-
-
Save oz-code/66350b40784fe2d315a9784970a736a8 to your computer and use it in GitHub Desktop.
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.Collections.Generic; | |
using System.Linq; | |
using static System.String; | |
namespace Soundex | |
{ | |
public class Encoder | |
{ | |
private const int MaxEncodedLength = 4; | |
private const string InvalidDigit = "*"; | |
class EncodingResult | |
{ | |
public EncodingResult(string curr, string prev) | |
{ | |
Curr = curr; | |
Prev = prev; | |
} | |
public string Curr { get; } | |
public string Prev { get; } | |
public bool IsValidEncoding => Curr != InvalidDigit; | |
} | |
private readonly Dictionary<char, int> _digitValues = new Dictionary<char, int>{ | |
{'b', 1}, {'f', 1}, {'p', 1}, {'v', 1}, | |
{'c', 2}, {'g', 2}, {'j', 2}, {'k', 2}, {'q', 2}, | |
{'d', 3}, {'t', 3}, | |
{'l', 4}, | |
{'m', 5}, {'n', 5}, | |
{'r', 6} | |
}; | |
private string ConvertCharcterToNumber(char c) | |
{ | |
c = char.ToLower(c); | |
return !_digitValues.ContainsKey(c) ? InvalidDigit : _digitValues[c].ToString(); | |
} | |
private EncodingResult EncodeCharacter(string word, char ch, int index) | |
{ | |
if (index == 0) | |
{ | |
return new EncodingResult(char.ToUpper(ch).ToString(), InvalidDigit); | |
} | |
return new EncodingResult(ConvertCharcterToNumber(ch), ConvertCharcterToNumber(word[index - 1])); | |
} | |
public string Encode(string word) | |
{ | |
if (IsNullOrEmpty(word)) | |
{ | |
return Empty; | |
} | |
return word | |
.Select((ch, index) => EncodeCharacter(word, ch, index)) | |
.Where((encodedChar, index) => | |
encodedChar.IsValidEncoding && encodedChar.Curr != encodedChar.Prev) | |
.Select(arg => arg.Curr) | |
.Concat(Enumerable.Repeat("0", MaxEncodedLength)) | |
.Take(MaxEncodedLength) | |
.Aggregate((i, j) => i + j); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Soundex algorithm using LINQ. Used to test LINQ debuggin with OzCode