Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

confused with summing certain elements from an array

by Anonymous Monk
on Nov 20, 2007 at 12:39 UTC ( #651911=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, I have a school assignment but I seem to be unable to begin... What I was given is something like the following
my @out= (b,a,c,d,a,b,f,g,a,c,g); my @out1=(1,2,3,1,2,3,4,5,2,3,2);#the numbers declares how many times +the letters from the @out are found
I want to make a hash contains as keys the unique elements from the @out and as values the sums of the letters from the @out1. Also I want the hash to be sorted
This is the preview of the hash %hash=(a=>6,b=>4,c=>6,d=>1,f=>4,g=>7)
any ideas please?

Replies are listed 'Best First'.
Re: confused with summing certain elements from an array
by erroneousBollock (Curate) on Nov 20, 2007 at 12:45 UTC
    I want to make a hash contains as keys the unique elements from the @out and as values the sums of the letters from the @out1. Also I want the hash to be sorted
    You can do this:

    my %counts; while (my $key = shift @out) { $counts{$key} += shift @out1; }
    That looks silly to me though... why would the data be in parallel arrays to begin with?

    Also I want the hash to be sorted
    Hashes aren't sorted.

    You can iterate the keys of the hash in order as follows:

    print "$_: \t$counts{$_}\n" for sort keys %counts;

    -David

      The data are in parallel arrays because that is how the designer of the homework specified the problem. ;)

      Perl offers several ways of managing data in that fashion and I expect there may be discussion of the pros and cons of each following the submission of answers. I'd hope too that your point is made - that is not a Perlish way to manage data in most cases.


      Perl is environmentally friendly - it saves trees
Re: confused with summing certain elements from an array
by sundialsvc4 (Abbot) on Nov 20, 2007 at 16:37 UTC

    Since this is a school assignment, the person you should be talking to, first and foremost, is your instructor. But in addition, give yourself time to reason the problem out.

    One thing that I suggest to my students is:   your best friend just might be a diary or a loose-leaf notebook, and a number-two pencil. Write down, in your own words:

    • What does it do?
    • Got a question? Write it down, in your own words, in longhand. With a pencil. Slowly.
    • A computer program moves step-by-step through a definite sequence. Can you write down, in your own words, a set of step-by-step instructions for “a stupid but obedient robot?”
    • Never mind Perl! Yes, I told you to forget those stupid punctuation-rules and what compiles and what doesn't. At least for now. All that stuff is merely the “how,” and until you first determine “what” you want the computer to do, well... you don't yet... know “what” to do with all those stupid punctuation-rules anyway, so don't worry about them yet.

    Some parts of the project may suggest-themselves, starting to appear dimly in the gloom of your as-yet disorganized thoughts. For instance, you know that this program is going to involve “a loop,” and it's going to involve “counting,” and perhaps although you don't yet see how the whole thing will fit together, you can consider how you might approach one part. So, force your mind to push-away the fact that you don't yet have the entire picture, and focus instead on whatever smaller-piece now appears to be coming out of the fog. That's what the pencil-and-paper is for. I assure you that your subconscious mind is working on this problem now. Vigorous exercise -- swimming, tennis -- also helps.

    Don't just run to the Internet for someone to tell you the answer. You're here, not just to “get” the answer, but to “learn how to get” the answer. Don't cheat yourself. And, be patient. The first program I ever wrote was eight lines long, took me three months to write, and had a bug in it.

      Where were you years ago when I started taking CS classes? The first two years was all trees and no forest, so I ditched the major and jumped onto the Physics bandwagon. I would have been happier in the department if more professors had integrated your "stop and think about what the heck you are doing" philosophy.

      To the original poster: sundial is right. It isn't bad or even uncommon that you are having a "Where do I even start" problem, but you won't fix it by taking the answer straight from here. Go find help, from your instructor, from teaching assistants, from classmates, or whoever is around. You'd be doing yourself a favor to tackle this problem right away, rather than letting it compound during the semester/school year.

Re: confused with summing certain elements from an array
by moritz (Cardinal) on Nov 20, 2007 at 12:46 UTC
    A hash is not sorted, by definition. You can sort the keys when you print it, though.
    my %counts; for (0 ... $#out){ $counts{$out[$_]} += $out1[$_]; }
    should build the hash.

    Update: the Perl 6 solution is much prettier, btw:

    for @out Z @out1 -> $char, $count { %hash{$char} += $count; }
      Looks ambiguous to me. "For array iterator array1 points to scalar var and count var, increment hash at var by count" if I had never seen perl 6 code before.
Re: confused with summing certain elements from an array
by andreas1234567 (Vicar) on Nov 20, 2007 at 12:51 UTC
    Remember to use warnings and strict (put it on the first lines of your code):
    use warnings; use strict;
    In this case you will be warned that you did not properly quote your input. See Quote and Quote-like Operators in perlop for more. Good luck with your homework (and thank you for admitting that it is actually homework).
    --
    Andreas
Re: confused with summing certain elements from an array
by GrandFather (Saint) on Nov 20, 2007 at 20:08 UTC
Re: confused with summing certain elements from an array
by Rudif (Hermit) on Nov 20, 2007 at 22:11 UTC
    ... but I seem to be unable to begin...

    G. Polya would perhaps suggest "Solve a simpler problem first".

    Rudif

Re: confused with summing certain elements from an array
by sundialsvc4 (Abbot) on Nov 20, 2007 at 23:30 UTC

    “You don't know where|how to begin?” Of course you don't! How many years so-far have you been doing this? Precisely my point. It's just like how you get to Carnegie Hall: practice.

    So, your brain is trying to grapple with this new task, this new way of thinking, and it's faced with a high-pressure situation that demands you to solve a problem when no immediate solution-path presents itself. Do not let yourself panic.

    When those snatches of ideas start to come out of that gloom, invite them over. Don't grab 'em and try to jerk them into the light. Woo them a little. Give 'em time. That's how your brain learns new skills.

Re: confused with summing certain elements from an array
by jarich (Curate) on Nov 21, 2007 at 02:35 UTC

    Your data description appears to be wrong. I count 2 'b's, not 1 or 3. I count 3 'a's, not 2. I count 2 'c's, not 3. I certainly don't count 4 'f's.

    As for solving the problem, to work with parallel arrays, you'll need to use a loop to walk over all of them. For example:

    my %hash; for(my $i; $i < @out; $i++) { # do something with $out[$i]; # do something with $out1[$i]; }

    In the body of the loop you'll need to populate that hash. Think about what should be your key and what should be your value.

    Good luck!

    jarich

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://651911]
Approved by Corion
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2022-12-01 04:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?