Can this implementation of Damm algorithm be optimized?

Cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 9 10:32:25 PST 2017


On Thursday, 9 February 2017 at 17:36:11 UTC, Nestor wrote:
> Hi,
>
> I was trying to port C code from the article in Wikiversity [1] 
> to D, but I'm not sure this implementation is the most 
> efficient way to do it in D, so suggestions to optimize it are 
> welcome:
>
> import std.stdio;
>
> static immutable char[] QG10Matrix =
>   "03175986427092154863420687135917509834266123045978" ~
>   "36742095815869720134894536201794386172052581436790";
>
> char checkDigit(string str) {
>   char tmpdigit = '0';
>   foreach(chr; str) tmpdigit = QG10Matrix[(chr - '0') + 
> (tmpdigit - '0') * 10];
>   return tmpdigit;
> }
>
> enum {
>   EXIT_SUCCESS = 0,
>   EXIT_FAILURE = 1,
> }
>
> int main(string[] args) {
>   scope(failure) {
>     writeln("Invalid arguments. You must pass a number.");
>     return EXIT_FAILURE;
>   }
>   assert(args.length == 2);
>   char digit = checkDigit(args[1]);
>   if(digit == '0') writefln("%s is a valid number.", args[1]);
>   else {
>     writefln("%s is not a valid number (but it would be, 
> appending digit %s).",
>       args[1], digit);
>   }
>
>   return EXIT_SUCCESS;
> }
>
> [1] https://en.wikiversity.org/wiki/Damm_algorithm

I can't see how to make it more efficient than it is (aside from 
finding a better algorithm which isn't a language concern). You 
are using C style and will get the same machine code as if you'd 
written it with C. The only difference would be boundchecking 
that you can disable by using the -boundscheck=off compiler 
switch.

By the way note that you can use the -profile switch to see where 
the bottlenecks are, in your case writting the result to stdout 
is *by far* what takes the most time (and I'm quite certain the 
bottleneck is the same in the C version for it's a fact that I/O 
is slow).


More information about the Digitalmars-d-learn mailing list