How to check if Dictionary contains letters from string

So, i wanted to create some sort of algorithm that will change letters inside string into a int, so lets just say if the string is ABCD the output will be 1234, this will make sure that the same message will be the same every single time, my idea was to create Dictionary that will have char as Key and int as value, then it will loop through the string and inside that loop it wwill loop through everything in the Dictionary, something like this

for(int i = 0; i < SeedS.Length; i++) {

    for(int j = 0; j < AlphabetDictionary.Count; j++) {

        //Do something

    }

}

and then my idea was to check if what is inside SeedS (with index of i) is equal to what Key is in the dictionary (with index if j) and then just assign value of that location to the output, i tried searching internet for how to do this but i didn’t found anything that could help, (i could use array or list but i think that’s just lazy and not very good if i can use Dictionary) i used Dictionaries for like 1-2 times and i don’t know how to do something like this, i have in mind everything else but i stopped at this point because i don’t know what to do now. i would like any help atm because i’m working on this “algorithm” for the past week i guess

PS: i also tried looking at Unity YT tutorial and reading Unity Documentation and i found nothing.

Answer

Answering the actual problem

You say all you actually want is a random seed based on the string input.

It couldn’t be easier! If you only need a “seed” which is always the same for same string inputs you could also just use string.GetHashCode();

var randomSeed = SeedS.GetHashCode();

Answering the title

If you really need a custom map you could use Dictionary<Tk, Tv>.TryGetValue and use two dictionaries to go forth and back

private Dictionary<int, char> indexToChar;
private Dictionary<char, int> charToIndex;

public string GetString(IReadonlyList<int> indices)
{
    var sb = new StringBuilder();
    foreach(var id = indices)
    {
        if(indexToChar.TryGetValue(id, out var c)
        {
            sb.Append(c);
        }
    }

    return sb.ToString();
}

public IReadonlyList<int> GetIndices(string input)
{
    var ids = new List<int>();

    for(var i = 0; i < input.Length; i++)
    {
        if(charToIndex.TryGetValue(input[i], out var id)
        {
            ids.Add(id);
        }
    }

    return ids;
}

otherwise you could also just use

var intValue = (int) someChar;

and

var charValue = (char) someInt;

Leave a Reply

Your email address will not be published. Required fields are marked *