The weekly challenge 247 - Task 1: Secret Santa
1 #!/usr/bin/perl
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 use strict;
64 use warnings;
65 use Data::Dumper;
66 use Algorithm::Permute;
67
68 secret_santa('Mr. Wall', 'Mrs. Wall', 'Mr. Anwar', 'Mrs. Anwar', 'Mr. Conway', 'Mr. Cross');
69 secret_santa('Mr. Wall', 'Mrs. Wall', 'Mr. Anwar');
70
71 sub secret_santa {
72 my @names = @_;
73 my @permutations = ();
74 my $p_iterator = Algorithm::Permute->new ( \@names );
75 my @current_permutation;
76 while (my @perm = $p_iterator->next) {
77 @current_permutation = @perm;
78 if(valid(@perm)) {
79 push @permutations, [@perm];
80 }
81 }
82 print Dumper \@permutations;
83 unless(@permutations) {
84 push @permutations, [ @current_permutation ];
85 }
86 my $which = int(rand(scalar(@permutations)));
87 my $permutation = $permutations[$which];
88 my $last = shift @$permutation;
89 push @$permutation, $last;
90 foreach my $who (@$permutation) {
91 print "$last -> $who\n";
92 $last = $who;
93 }
94 }
95
96 sub valid {
97 my @perm = @_;
98 my $last = shift @perm;
99 push @perm, $last;
100 foreach my $name (@perm) {
101 my $family_last = $last;
102 $family_last =~ s/.* //;
103 my $family_this = $name;
104 $family_this =~ s/.* //;
105 return 0 if $family_last eq $family_this;
106 $last = $name;
107 }
108 return 1;
109 }