forked from trizen/perl-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunique_permutations.pl
More file actions
47 lines (36 loc) · 969 Bytes
/
unique_permutations.pl
File metadata and controls
47 lines (36 loc) · 969 Bytes
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
#!/usr/bin/perl
# Generate only the unique permutations of a given array.
# Optimized Unique Permutation DFS without explicit key tracking
# Recursively branches unique factors only at each depth.
use 5.036;
sub unique_permutations($array, $callback) {
sub ($items, $current_perm) {
if (!@$items) {
$callback->($current_perm);
return;
}
my %level_seen;
for my $i (0 .. $#$items) {
my $item = $items->[$i];
# Skip iterations for duplicate elements in the same level
next if $level_seen{$item}++;
my @new_items = @$items;
splice(@new_items, $i, 1);
my @new_perm = (@$current_perm, $item);
__SUB__->(\@new_items, \@new_perm);
}
}->($array, []);
}
unique_permutations(
[3, 2, 2, 3],
sub ($perm) {
say "(@$perm)";
}
);
__END__
(3 2 2 3)
(3 2 3 2)
(3 3 2 2)
(2 3 2 3)
(2 3 3 2)
(2 2 3 3)