in reply to Re: Reversing Hash
in thread Reversing Hash

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.

  • Replies are listed 'Best First'.
    Re: Re: Re: Reversing Hash
    by DaveH (Monk) on Mar 03, 2003 at 10:17 UTC

      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
    Re: Re: Re: Reversing Hash
    by Hofmator (Curate) on Mar 03, 2003 at 10:44 UTC
      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