Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Anagrams & Letter Banks

by tybalt89 (Monsignor)
on Oct 27, 2017 at 20:17 UTC ( [id://1202193]=note: print w/replies, xml ) Need Help??


in reply to Anagrams & Letter Banks

"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?"

#!/usr/bin/perl # http://perlmonks.org/?node_id=1202179 use strict; use warnings; my $good = [qw( allo mallo malo)]; my $bad = [qw( tillo sillo sallo)]; grep !/(.).*\1/, @$_ and print "@$_\n" for $good, $bad;

Replies are listed 'Best First'.
Re^2: Anagrams & Letter Banks
by dominick_t (Acolyte) on Oct 27, 2017 at 20:31 UTC
    Thank you, tybalt89. It's nice to see this regex solution as well as the hash solution offered earlier. I was just reading about backreferences, and again it makes sense to me in principle, but the details remain opaque. What do the parentheses in (.) accomplish? And how does the backreference determine if something has been seen again?
      Hi dominick_t

      The parentheses capture one letter and look for a repeat, \1. He greps for a string which doesn't cause the regular expression to succed, (! /.....

      Update

      I should have been more thorough in my reply. When there is a parentheses around an expression, in this case '.', \1 refers to that captured value. If an 'a' was captured, then \1 would be a. If a 'd' was captured, then for \1 to match, it would need to find a 'd' somewhere further in the string.

      Perl will try to make the match succeed, so it will progress matching each letter until it finds a match. If it does, then the the regexp will succeed. Else, it will fail.

      If it fails then the grep succeeds!

      There would be a \2 if there were 2 sets of capturing parentheses. \1 would be what was captured in the first parens and \2 would be what was captured in the second set of parens. In this problem there is only one set of parens so only \1 would be involved.

        Thank you, Cristoforo. Would \2 look for two repeats? Does "grep" generally return "true" if it succeeds but here the "!" returns "false" if it succeeds?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1202193]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-26 02:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found