Range expansion: Difference between revisions
Content added Content deleted
m (→[[Range expansion#ALGOL 68]]: define/use generalised SIZEOF operator) |
(Link to separate format page) |
||
Line 1: | Line 1: | ||
{{task}} |
{{task}} |
||
Expand the range of integers ''-6,-3-1,3-5,7-11,14,15,17-20'' which is in the format described in [[Range extraction]] to a list of integers. |
Expand the range of integers ''-6,-3-1,3-5,7-11,14,15,17-20'' which is in the format described in [[Range extraction/Format]] to a list of integers. |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68|Revision 1 - no extensions to language used}} |
{{works with|ALGOL 68|Revision 1 - no extensions to language used}} |
Revision as of 12:45, 16 July 2010
Range expansion
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Expand the range of integers -6,-3-1,3-5,7-11,14,15,17-20 which is in the format described in Range extraction/Format to a list of integers.
ALGOL 68
<lang algol68>MODE YIELDINT = PROC(INT)VOID;
MODE RANGE = STRUCT(INT lwb, upb); MODE RANGEINT = UNION(RANGE, INT);
OP SIZEOF = ([]RANGEINT list)INT: (
- determine the length of the output array #
INT upb := LWB list - 1; FOR key FROM LWB list TO UPB list DO CASE list[key] IN (RANGE value): upb +:= upb OF value - lwb OF value + 1, (INT): upb +:= 1 ESAC OD; upb
);
PROC gen range expand = ([]RANGEINT list, YIELDINT yield)VOID:
FOR key FROM LWB list TO UPB list DO CASE list[key] IN (RANGE range): FOR value FROM lwb OF range TO upb OF range DO yield(value) OD, (INT int): yield(int) ESAC OD;
PROC range expand = ([]RANGEINT list)[]INT: (
- Finally full the output array with a generator #
[LWB list: LWB list + SIZEOF list - 1]INT out; INT upb := LWB out - 1;
- FOR INT value IN # gen range expand(list, # ) DO #
- (INT value)VOID:
out[upb +:= 1] := value
- OD #);
out
);
test:(
[]RANGEINT list = (-6, RANGE(-3, 1), RANGE(3, 5), RANGE(7, 11), 14, 15, RANGE(17, 20)); print((range expand(list), new line))
)</lang> Output:
-6 -3 -2 -1 +0 +1 +3 +4 +5 +7 +8 +9 +10 +11 +14 +15 +17 +18 +19 +20
Python
<lang python>def rangeexpand(txt):
lst = [] for r in txt.split(','): if '-' in r[1:]: r0, r1 = r[1:].split('-', 1) lst += range(int(r[0] + r0), int(r1) + 1) else: lst.append(int(r)) return lst
print(rangeexpand('-6,-3-1,3-5,7-11,14,15,17-20'))</lang>
Sample output
[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]