-
Notifications
You must be signed in to change notification settings - Fork 320
/
ch-1.pl
executable file
·80 lines (74 loc) · 1.61 KB
/
ch-1.pl
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
#!/usr/bin/perl
#
# Task 1: "Longest Consecutive Sequence
#
# You are given an unsorted array of integers @N.
#
# Write a script to find the longest consecutive sequence. Print 0 if no sequence found.
#
# Example 1:
#
# Input: @N = (100, 4, 50, 3, 2)
# Output: (2, 3, 4)
#
# Example 2:
#
# Input: @N = (20, 30, 10, 40, 50)
# Output: 0
#
# Example 3:
#
# Input: @N = (20, 19, 9, 11, 10)
# Output: (9, 10, 11)
# "
#
# My notes: clearly defined, sort it first, then walk list looking for sequences
#
use strict;
use warnings;
use feature 'say';
#use Data::Dumper;
use Getopt::Long;
my $debug = 0;
die "Usage: longest-sequence [--debug] array\n" unless
GetOptions( "debug" => \$debug ) &&
@ARGV>1;
my @x = sort { $a <=> $b } @ARGV;
# one-pass, extend sequence or start a new one each go
my @seq; # members of current sequence (empty if not in sequence)
my $next = undef; # if we're in a sequence, what's the next value expected
my @longestseq; # members of longest current sequence (empty if no sequence found yet)
foreach my $val (@x)
{
#say "debug: val=$val, seq=", join(',',@seq);
unless( @seq ) # not in a sequence? start a new one
{
@seq = ($val);
$next = $val+1;
} else
{
if( $val == $next ) # extend sequence
{
push @seq, $val;
$next++;
} else
{
say "found sequence ", join(',',@seq), ", length ", scalar(@seq) if $debug;
if( @seq > @longestseq )
{
@longestseq = @seq;
}
@seq = ( $val );
$next = $val+1;
}
}
}
say "found sequence, ", join(',',@seq), ", length ", scalar(@seq) if $debug;
my $len = @longestseq;
if( $len > 1 )
{
say join(',',@longestseq);
} else
{
say 0;
}