aboutsummaryrefslogtreecommitdiff
path: root/challenge-200/duncan-c-white/perl/ch-1.pl
blob: 8403d47bbb89503af9f0db0fac58743ce0f1f9ea (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
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
#!/usr/bin/perl
# 
# Task 1: Arithmetic Slices
# 
# You are given an array of integers.
# 
# Write a script to find out all Arithmetic Slices for the given array
# of integers.  An integer array is called arithmetic if it has at least
# 3 elements and the differences between any three consecutive elements
# are the same.
# 
# 
# Example 1
# 
# Input: @array = (1,2,3,4)
# Output: (1,2,3), (2,3,4), (1,2,3,4)
# 
# Example 2
# 
# Input: @array = (2)
# Output: () as no slice found.
# 
# 
# MY NOTES: pretty easy.  generate and test: generate all subarrays of len > 2
# via two nested for loops.  then test for all-elements-one-apart.  (Actually,
# that's not quite what the spec said, but I noticed that too late).
# 
# GUEST LANGUAGE: As a bonus, I also had a go at translating ch-1.pl
# into C (look in the C directory for the translation)
# 

use strict;
use warnings;
use feature 'say';
use Getopt::Long;
use Data::Dumper;

my $debug=0;
die "Usage: arithmetic-slices [--debug] intlist\n"
	unless GetOptions( "debug"=>\$debug ) && @ARGV>0;

my @list = split( /,/, join(',',@ARGV) );

die "arithmetic-slices: need at least 3 ints in list\n" unless @list>2;

my @result;

sub isarith
{
	my( @a ) = @_;
	die "need at least 3 elements in @a\n", if @a<3;
	my $v = shift @a;
	foreach my $e (@a)
	{
		$v++;
		return 0 unless $e == $v;
	}
	return 1;
}


for( my $i=0; $i<@list-2; $i++ )
{
	for( my $j=$i+2; $j<@list; $j++ )
	{
		my @sub = @list[$i..$j];
		say "debug: sub($i,$j)=". join(',',@sub) if $debug;
		push @result, \@sub if isarith(@sub);
	}
}

say "Results:";
foreach my $p (@result)
{
	say "(".join(',',@$p).")";
}