Variable number of elements is not a problem; it's just a circumstance that demands a little more code....
So, let's see... . o O
We know how to count the elements, $#arr... so that means we'll need to repeat the next-to-last line $#arr/2 times.
Oops. Not an integer. Well, we knew that already too, but after we've printed the first pair, we should need to repeat either of the next two lines ( ($#arr/2) -1 ) times. Or we could start with ( ($#arr +1)/2 ). Either way, Shazam! The problem of an unknown number of pairs in the array is (almost) solved, except for the trivial act of actually writing the code.
Do you smell a loop coming? I do.
Again, this is a case of TIMTOWTDI that's NOT worth pursuing, except for the mental exercise (or maybe, an obfuscation contest). The solutions with a module that's designed to do just what you want are clearly the way to go in the real world.
It does, however, have a smidgen of value for readers here in the Monastery: it emphasizes the need for precision and completeness in problem statements. |