Skip to content

Instantly share code, notes, and snippets.

@oz-code
Created June 5, 2016 12:17
Embed
What would you like to do?
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);
}
}
}
@oz-code
Copy link
Author

oz-code commented Jun 5, 2016

Soundex algorithm using LINQ. Used to test LINQ debuggin with OzCode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment