try find the fastest way to convert a group string into index?
Vladimir Panteleev
thecybershadow.lists at gmail.com
Sun Sep 16 10:14:24 UTC 2018
On Sunday, 16 September 2018 at 10:04:09 UTC, learnfirst1 wrote:
> how to make this more fast like with one loop and get the
> results.
This is a more general problem than any specific programming
language; you may want to look into perfect hashing:
https://en.wikipedia.org/wiki/Perfect_hash_function
There exists software to generate perfect hash functions, e.g.
GNU gperf:
https://www.gnu.org/software/gperf/
It looks like Basile wrote one for D:
https://github.com/BBasile/IsItThere
If you don't want to go that far, you can generate a string
switch using string mixins:
void main()
{
static immutable string[] keywords = ["foo", "bar", "baz"];
enum Keyword { foo, bar, baz }
Keyword parseKeyword(string s)
{
switch (s)
{
mixin({
string code;
foreach (keyword; keywords)
code ~= `case "` ~ keyword ~ `": return Keyword.` ~ keyword
~ `;`;
return code;
}());
default:
throw new Exception("No such keyword!");
}
}
assert(parseKeyword("bar") == Keyword.bar);
}
More information about the Digitalmars-d-learn
mailing list