By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,835 Members | 2,305 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,835 IT Pros & Developers. It's quick & easy.

perl recursive iteration

P: 89
Hi,

I have the data as below:

1,1000,2000,3000 999,1999,2999,3999 [m1,m2,m3,m4 n1,n2,n3,n4]
And the number of 1st and 2nd set will vary in the every line but there will be equal number of numbers in both the set.

I am successful in collecting them in the following simple manner as below:

999-1000, 1999-2000, 2999-3000 [n1-m2, n2-m3, n3-m4]

Basically, I collect all the start nos as 1,1000,2000 and 3000 and end nos in 999,1999,2999,3999 two arrays.
Expand|Select|Wrap|Line Numbers
  1. $starts = "1,1000,2000,3000";
  2. $ends = "999,1999,2999,3999";
  3.  my @test_starts = split (/,/, $starts);
  4.     my @test_ends    = split (/,/, $ends);
  5.  
  6.  $size= @starts - 1;
  7. for (my $i = 0; $i < $size; $i++)
  8.     {
  9.        print "$test_end[i] - $test_start[i+1]\n";
  10.  
  11.     }
  12.  
  13.  
The above mentioned script is just showing the method I have used to show my results and might contain some typos as these are not my actual code. And it works till this.

Now I want to add all the possible ways as below:

999-1000, 1999-2000, 2999-3000 [n1-m2, n2-m3, n3-m4]
as well as
999-2000, 999-3000 [n1-m3, n1-m4]

I am bit confused as this might require any recursive. Please let me know any method to solve the issue. Thanks.
Sep 23 '09 #1
Share this Question
Share on Google+
2 Replies


Expert
P: 70
I think you just need an inner loop, instead of recursion.
Does this give you the output you expect?
Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. use warnings;
  3.  
  4. my @starts = qw(1   1000 2000 3000);
  5. my @ends   = qw(999 1999 2999 3999);
  6. for my $i (0 .. (@starts-2)) {
  7.     for my $j (0 .. (@starts-2)) {
  8.         print "$ends[$i] - $starts[$j+1]\n" if $starts[$j+1] > $ends[$i];
  9.     }
  10. }
  11.  
  12. __END__
  13.  
  14. 999 - 1000
  15. 999 - 2000
  16. 999 - 3000
  17. 1999 - 2000
  18. 1999 - 3000
  19. 2999 - 3000
  20.  
Sep 23 '09 #2

P: 89
Thanks Toolic and that did help me.
Sep 29 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.