Min And Max Of Tokens In A String
Автор: Martin Packer
Дата: 14.07.2013
Источник: IBM developerWorks
A couple of days ago I had a need to take a REXX string comprising space-separated numbers and find their minimum and maximum values. Here's the technique I used.
(When I say "space-separated" there can be one or more spaces between the numbers, but there has to be at least one.)
The solution has three components:
The REXX SPACE function - to turn the list into a comma-separated string of numbers. (The second parameter is the number of so-called spaces to separate tokens with. The third is the actual character to use - in my case a comma.)
The REXX MIN (or MAX) function to compute the minimum (or maximum) value from this comma-separated string. These functions take a set of parameters of arbitrary length and do the maths on them. Parameters are separated by commas, hence the need to use SPACE to make it so.
INTERPRET to glue 1 and 2 together.
My need is relatively low volume, so the "health warning" about INTERPRET's performance is hardly relevant for my use case.
Here's the code:
/* Return min and max value of string of space-separated numbers */
minAndMax: procedure
parse arg list
comma_list=space(list,,",")
interpret "minimum=min("comma_list")"
interpret "maximum=max("comma_list")"
return minimum maximum
It's relatively straightforward, taking a list of numbers and returning the minimum and maximum. You'll notice it doesn't check that the tokens really are numbers. If I were to extend it I'd probably check for two SLR conditions: Overflow ("*" or similar) and Missing Value ("---" or similar). I'd probably take some of the "List Comprehension" stuff I talked about in Dragging REXX Into The 21st Century? and apply it to the list.
And my code uses this to decide if I have a range of values or just a single one. In the former case it turns the pair of numbers into e.g. "1-5" and the latter just e.g. "4".
Of course there are other ways to do minimum and maximum for a list of numbers but this one seems the simplest and most elegant to me. "6 months later me" might take a different view. :-)