in reply to number of unique characters in a string
Updated To correct error introduced whilst sanitising for public consumption.
It would be interesting to see how this would compare with merlyn's Inline::C version for performance. Unfortunately, I still don't have that ability (yet).
One point to note, this version should also work for unicode strings. If you don't need that, then swapping the unpack template from 'U*' to 'C*' should do the trick and might be a tad quicker.
#! perl -slw use strict; sub nUniqC{ my @uniq; ## Updated. @uniq[unpack 'U*',$_[0]] = (1)x length $_[0]; scalar (grep defined $_, @uniq); } print nUniqC '1010101010'; print nUniqC '1234567812';
For speed in perl and assuming no utf-8, this seems a bit quicker.
sub nUniqC{ my @uniq; scalar grep{ ++$uniq[$_] == 1 } unpack('C*',$_[0]); }
Update Trimmed another 15% of fat. No I didn't. I misread bad data, the version above is quickest.
sub nUniqC{ scalar grep{ ++$_[$_] == 1 } unpack('C*',$_[0]); }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: number of unique characters in a string
by Limbic~Region (Chancellor) on Mar 01, 2003 at 04:59 UTC | |
by BrowserUk (Patriarch) on Mar 01, 2003 at 05:10 UTC |