I've been tasked with taking a string and returning a dictionary that has a map of characters to a list of their indices in a given string. The output should show which characters occur where in the given string. I am currently stumped on where to go from the code I will post below.
public Dictionary<string, List<int>> returnDictionary(string s)
{
Dictionary<string, List<int>> newDictionary = new Dictionary<string, List<int>>();
char[] strArray = s.ToCharArray();
List<char> strList = strArray.ToList();
List<int> charIndex;
for (int i = 0; i < strList.Count(); i )
{
if (!newDictionary.TryGetValue(strList[i].ToString(), out charIndex))
{
newDictionary.Add(strList[i].ToString(), charIndex);
}
}
return newDictionary;
}
I have tests being ran in another file, when the test is ran, it should pass. Test related below:
public void TestConcordanceForGoodString()
{
var input = "engineering";
var eIndices = new int[3] { 0, 5, 6 };
var nIndices = new int[3] { 1, 4, 9 };
var gIndices = new int[2] { 2, 10 };
var iIndices = new int[2] { 3, 8 };
var rIndices = new int[1] { 7 };
var actual = csharpLogic.ConcordanceForString(input);
Assert.Equal(5, actual.Count); //Ensure 5 total keys
Assert.Equal(eIndices, actual["e"]); //Ensure the correct indices in the correct order
Assert.Equal(nIndices, actual["n"]);
Assert.Equal(gIndices, actual["g"]);
Assert.Equal(iIndices, actual["i"]);
Assert.Single(actual["r"]);
CodePudding user response:
This code passes the test:
public class CharacterIndexDictionary
{
public static Dictionary<string, List<int>> ConcordanceForString(string input)
{
var result = new Dictionary<string, List<int>>();
for (var index = 0; index < input.Length; index )
{
// Get the character positioned at the current index.
// We could just use input[index] everywhere, but
// this is a little easier to read.
string currentCharacter = input[index].ToString();
// If the dictionary doesn't already have an entry
// for the current character, add one.
if (!result.ContainsKey(currentCharacter))
{
result.Add(currentCharacter, new List<int>());
}
// Add the current index to the list for
// the current character.
result[currentCharacter].Add(index);
}
return result;
}
}
If I wanted to index characters I'd use a Dictionary<char, List<int>> instead of using a string as the key, but this uses string because the test requires it.
CodePudding user response:
This code block is like your code and in a way that you can understand
public Dictionary<string, List<int>> ConcordanceForString(string s)
{
Dictionary<string, List<int>> newDictionary = new Dictionary<string, List<int>>();
List<char> charList = new List<char>();
foreach (var item in s)
{
if (!charList.Any(x => x == item))
{
charList.Add(item);
List<int> itemInds = new List<int>();
for (int i = 0; i< s.Length; i )
{
if (s[i] == item)
{
itemInds.Add(i);
}
}
newDictionary.Add(item.ToString(), itemInds);
}
}
return newDictionary;
}
