-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree_from_nesting_levels
executable file
·58 lines (52 loc) · 1.32 KB
/
Tree_from_nesting_levels
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
#!/usr/local/bin/perl
#u# http://rosettacode.org/wiki/Tree_from_nesting_levels
#c# 2021-02-03 <RC
#p# OK
use strict;
use warnings;
use Data::Dump qw(dd pp);
my @tests =
(
[]
,[1, 2, 4]
,[3, 1, 3, 1]
,[1, 2, 3, 1]
,[3, 2, 1, 3]
,[3, 3, 3, 1, 1, 3, 3, 3]
);
#for my $before ( @tests ) {
# dd { before => $before };
# local $_ = (pp $before) =~ s/\d+/ '['x($&-1) . $& . ']'x($&-1) /ger;
# 1 while s/\](,\s*)\[/$1/;
# my $after = eval;
# dd { after => $after };
#}
sub nest {
my $before = shift;
local $_ = (pp $before) =~ s/\d+/ '['x($&-1) . $& . ']'x($&-1) /ger;
1 while s/\](,\s*)\[/$1/;
my $after = eval;
$after;
}
my $ref = <<'EOD';
{ before => [] }
{ after => [] }
{ before => [1, 2, 4] }
{ after => [1, [2, [[4]]]] }
{ before => [3, 1, 3, 1] }
{ after => [[[3]], 1, [[3]], 1] }
{ before => [1, 2, 3, 1] }
{ after => [1, [2, [3]], 1] }
{ before => [3, 2, 1, 3] }
{ after => [[[3], 2], 1, [[3]]] }
{ before => [3, 3, 3, 1, 1, 3, 3, 3] }
{ after => [[[3, 3, 3]], 1, 1, [[3, 3, 3]]] }
EOD
use Test::More;
is_deeply nest([]), [];
is_deeply nest([1, 2, 4]), [1, [2, [[4]]]];
is_deeply nest([3, 1, 3, 1]), [[[3]], 1, [[3]], 1];
is_deeply nest([1, 2, 3, 1]), [1, [2, [3]], 1];
is_deeply nest([3, 2, 1, 3]), [[[3], 2], 1, [[3]]];
is_deeply nest([3, 3, 3, 1, 1, 3, 3, 3]), [[[3, 3, 3]], 1, 1, [[3, 3, 3]]];
done_testing;