Compute in one pass 3 tokens position
bioinfornatics
bioinfornatics at fedoraproject.org
Thu May 3 08:44:54 PDT 2012
Le lundi 30 avril 2012 à 14:52 +0200, bioinfornatics a écrit :
> Hi,
> I would like to know how compute in on pass 3 tokens position in a
> sequence.
> curently i do:
> File f = File( "reader.d", "r" );
> scope(exit) f.close();
> char[1024] buffer;
> char[] content = f.rawRead(buffer);
> char[sizediff_t] token = ['(', '{', ';'];
> auto position = map!( a => content.countUntil( a ) )( [ ['('], ['{'],
> [';'] ] );
>
>
> if i use reduce instead map the build fail
>
update code for add attribute poure notrhow nd safe :)
------------------
import std.string;
import std.stdio;
import std.conv;
import std.c.process;
/**
* searchIndex
* search at wich index is located each token in given sequence.
* It compute it in one pass.
* Returns:
* An ssociative array:
* key = token and value first index where is found
* value take -1 if not found in given sequence.
*/
@safe nothrow pure
sizediff_t[char[]] searchIndex( in char[] sequence, in char[][]
token...)
in{
assert(sequence !is null, "Error given sequence is null");
}
body{
bool isComputing = true;
size_t index = 0;
size_t flag = 0;
sizediff_t[char[]] result;
foreach( tok; token)
result[tok] = -1;
while(isComputing){
if( index >= sequence.length )
isComputing = false;
else if( flag == token.length )
isComputing = false;
else{
foreach( tok; token){
if( sequence.length - index >= tok.length ){
const(char)[] currentToken = (tok.length > 1) ?
sequence[index .. index + tok.length] : [sequence[index]];
if( currentToken in result && result[currentToken] == -1 ){
result[currentToken] = index;
flag++;
}
}
}
index++;
}
}
return result;
}
void main( string[] args ){
if( args.length == 1 ){
writefln( "Usage %s <token1> <token2> <token3> <token4>...", args[0]
);
exit(0);
}
writeln( searchIndex( "This a cool statement such as D is fun. Use it
and got the D power. Oh yeah! Are you ready? Try it!! Have fun.",
args[1..$]) );
}
More information about the Digitalmars-d-learn
mailing list