Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Hi dominik_t

> Given a list whose elements are strings (containing only letters, as they are actually English-language words), how would one print that list only on the condition that at least one of the strings in the list contains no repeated letters?

Counting repetitions or not repetitions is a call for a hash. The following iterates over lists and, using the $has_unique switch, search if one word of the list is built with just different characters.

This is done with the %chars hash: $chars{$_}++ for ($word =~ /./g) where the regex in list context returns all chars and the respective value in the hash is augmented by one.

Then if the length of the $word is equal to the number of keys of the hash the word must be built with different characters, so the switch $has_unique is turned on and after all word in the list were processed the list is printed only if the switch is on.

use strict; use warnings; my $good = [qw( allo mallo malo)]; my $bad = [qw( tillo sillo sallo)]; foreach my $list ($good,$bad){ my $has_unique; foreach my $word(@$list){ my %chars; $chars{$_}++ for ($word =~ /./g); if (scalar keys %chars == length $word){ # print "$word has no repeated letters"; $has_unique++; } } print +(join ' ', @$list),"\n" if $has_unique; } # output allo mallo malo

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

In reply to Re: Anagrams & Letter Banks by Discipulus
in thread Anagrams & Letter Banks by dominick_t

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-25 22:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found