in reply to Reversing Hash

How does dropping numbers from the array help guarentee uniqueness?

On what basis do you decide it is possible to drop numbers?

Because they are duplicates in that array?

You need to clarify this.

Replies are listed 'Best First'.
Re: Re: Reversing Hash
by artist (Parson) on Mar 03, 2003 at 09:50 UTC
    Within single array there are no duplicates. But assume that there are only 4 arrays.
  • [1, 20, 3], [1, 30, 4, 7], [1,9,8] and [1, 9, 17]

    My new hash keys would be

    1. "3"
    2. "4"
    3. "1 8"
    4. "1 17"

    Which I can match one to one with original arrays.

    Thanks, artist.

      Hi.

      This solution assumes that you don't mind duplicate values (i.e. where two unique keys from %hash have the same value) being pushed onto an array.

      Also, feel free to change the value of $; to whatever you like if a space isn't suitable.

      use strict; my %rev_hash = (); my %hash = ( 'key1' => [1, 20, 3], 'key2' => [1, 30, 4, 7], 'key3' => [1, 9, 8], 'key4' => [1, 9, 17], 'key5' => [1, 9, 17], ); { local ($;) = " "; while (my ($k, $v) = each %hash) { push @{$rev_hash{"@{$v}"}}, $k; } while (my ($k, $v) = each %rev_hash) { print qq(\$rev_hash{$k} = "@{$v}"\n); } }

      Cheers,

      -- Dave :-)


      $q=[split+qr,,,q,~swmi,.$,],+s.$.Em~w^,,.,s,.,$&&$$q[pos],eg,print
        Hi Dave
        That doesn't work:
        Your script gives me answer without any 'reduction' in rev_hash keys.
        $rev_hash{1 20 3} = "key1"
        $rev_hash{1 9 17} = "key4 key5"
        $rev_hash{1 9 8} = "key3"
        $rev_hash{1 30 4 7} = "key2"
        
        Which doesn't reduce the keys to its minimum possible. I like to have keys "3" "1 17" "1 8" and "4" . so the answer should be
        $rev_hash{3} = "key1"
        $rev_hash{1 17} = "key4 key5"
        $rev_hash{1 8} = "key3"
        $rev_hash{4} = "key2"
        

        Thanks
        artist
      Huhh, can you explain your algorithm for reducing the arrays a bit further?? I see at the moment plenty of possibilities, e.g. I don't see why
      1. 3
      2. 4
      3. 8
      4. 17
      might not be a valid reduction ...

      -- Hofmator