in reply to Check if string A and B are made up of same chars

Not sure if it's faster.

It's late and I haven't benchmarked it. ( I suppose it also depends on the length of the strings.)

For multiple strings you'll need to reset %h to the first count.

use strict; use warnings; sub test { my ($str1,$str2) = @_; my %h; $h{$_}++ for split //, $str1; $h{$_}-- for split //, $str2; $_ and return 0 for values %h; return 1; } print test(("Hello World!")x2); # 1 print test("Hello World!","Hello World"); # 0

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Check if string A and B are made up of same chars
by harangzsolt33 (Deacon) on Nov 17, 2024 at 01:57 UTC
    Thank you! That's an interesting solution. In the meanwhile, I also thought of one. This version removes characters one by one from both strings:

    Edit: Here is the latest updated version. I think, this is the fastest so far:

      The performance of those algorithms depends a lot on the quality of the input.

      Like

      • length
      • entropy (randomness)

      For instance a linear approach like mine will most likely dominate for longer strings, which are equal.

      But how likely are a bunch of totally random long strings ever to be equal???

      That's a microscopic chance, and any algorithm which is managing to opt out as early as possible will dominate, little matter the complexity of the approach in total.

      So first task:

      define the problem space and provide a generator to create representative input.

      Second task:

      write a Benchmark suite based on this input.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery