Thread QOTW 23 'perl' quiz (13 answers)
Opened by Crian at 2004-09-02 11:38

Crian
 2004-09-04 16:12
#49831 #49831
User since
2003-08-04
5873 Artikel
ModeratorIn
[Homepage]
user image
Hier ist meine Lösung:

Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/perl
use strict;
use warnings;

use File::Basename;

=head1 QUEST

Write a program, 'parens', which gets a command line argument, 'n',
which is an integer. The program should print all the
properly-balanced strings of parentheses of length 2n. For example,
given the argument '3', the program should print these five lines:

((()))
(()())
(())()
()(())
()()()

in some order. (The order is not important.)

For the argument '1'; the output should be:

()

and for argument '4', the output should be:

(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()

in some order.

=cut


main();
exit;


sub next_parenthesis ($$) {
my ($is, $n) = @_;
my @np;

my $open = () = $is =~ m/\(/g;
my $close = () = $is =~ m/\)/g;

push @np, '(' if $open < $n;
push @np, ')' if $close < $open;

return @np;
}


sub main {
my $n = $ARGV[0];

die "syntax: ", basename($0),
" N\n\twhere N is a natural number (number of pairs of parenthesis)\n"
unless defined $n and $n > 0;

my @output = ('');

for my $position (1 .. 2*$n) {
my @output2;

for my $is (@output) {
push @output2, "$is$_" for next_parenthesis($is, $n);
}
@output = @output2;
}

printf "%3d: %s\n", $_+1, $output[$_] for 0.. $#output;
}


und hier die Golf-Lösung:

Code: (dl )
1
2
#!/usr/bin/perl
$n=$ARGV[0];@o=('');for(1..2*$n){my@q;for(@o){$o=()=m/\(/g;$c=()=m/\)/g;push@q,"$_("if $o<$n;push@q,"$_)"if$c<$o;}@o=@q;}print"$_\n"for@o;


(umgebrochen fuer bessere Lesbarkeit, an der Stelle wird der Zeilenumbruch nicht benötigt...)\n\n

<!--EDIT|Crian|1094300060-->
s--Pevna-;s.([a-z]).chr((ord($1)-84)%26+97).gee; s^([A-Z])^chr((ord($1)-52)%26+65)^gee;print;

use strict; use warnings; Link zu meiner Perlseite

View full thread QOTW 23 'perl' quiz