0: Here's a function I wrote to group consecutive sets of integers in to a tabular form.
1:
2: ####
3: ##
4: ## my $table_hrf = consecutive( \@integers )
5: ##
6: ## Description: function to find consecutive integers
7: ##
8: ## Parameters: a reference to an array of integers
9: ##
10: ## Returns: table of sorted, grouped integers in the form of
11: ##
12: ## base_integer => sequence_length
13: ##
14: ## For instance, the list
15: ##
16: ## qw( 20 2 3 4 5 6 7 23 19 17 25 30 11 12 22 21 68 103829 24 18 );
17: ##
18: ## will sort to
19: ##
20: ## 2 => 5,
21: ## 11 => 1,
22: ## 17 => 8,
23: ## 30 => 0,
24: ## 68 => 0,
25: ## 103829 => 0
26: ##
27: ## which means
28: ##
29: ## sequence(5): 2 to 7
30: ## sequence(1): 11 to 12
31: ## sequence(8): 17 to 25
32: ## single: 30
33: ## single: 68
34: ## single: 103829
35: ##
36: ####
37: sub consecutive
38: {
39: my $integer_arf = shift;
40:
41: my %table = ( );
42:
43: my $base = 0;
44: my $previous = 0;
45:
46: foreach my $number ( sort numerically @{ $integer_arf } )
47: {
48: if( ( $number - 1 ) == $previous ) # if the current number is one greater
49: { # than the previous, increment our base
50: $table{ $base }++;
51: }
52: else # we've found a new sequence
53: {
54: $table{ $number } = 0; # we're the base number, so set our adder to 0
55: $base = $number;
56: }
57:
58: $previous = $number; # end of loop -- our $number is now old
59: }
60:
61: return \%table;
62: }
63:
64: sub numerically { $a <=> $b }
In reply to grouping consecutive integers by oboyle
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |