aboutsummaryrefslogtreecommitdiff
path: root/challenge-115/arne-sommer/perl/string-chain-perl
blob: 22a6b0ba97f703613b377c417ffedaacbe344e2a (plain)
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
#! /usr/bin/env perl

use strict;
use warnings;
use feature 'say';
use Getopt::Long;
use Algorithm::Combinatorics 'permutations';
use feature 'signatures';

no warnings qw(experimental::signatures);

my $verbose = 0;

GetOptions("verbose" => \$verbose);

die "At least two strings" unless @ARGV > 1;

for my $list (permutations(\@ARGV))
{
  my @perm = @$list;

  say ": perm: " . join(", ", @perm) if $verbose;
  
  if (is_circle(@perm))
  {
    say 1;
    exit;
  }
}

say 0;

sub is_circle (@list)
{
  my $first       = shift(@list);
  my $first_start = substr($first, 0,1);
  my $second;

  while (@list)
  {
    $second = shift(@list);
    return 0 if substr($first,-1,1) ne substr($second,0,1);
    $first  = $second;
  }
    
  return 1 if $first_start eq substr($second,-1,1);
  return 0;
}