гольфскрипт, 46 45
На мою першу програму сценаріїв з гольфу пройшло кілька годин.
{','/{'-'/{~}%.,1-{))+{,}/\-~}{~}if}%","*}:r;
# call:
"1,3-5,9,16,18-23"r
# return:
1,3,4,5,9,16,18,19,20,21,22,23
Ви можете спробувати це на веб- сайті http://golfscript.apphb.com/
Я найкраще пояснюю це жорстокість:
{...}:r; # makes a function block ... and names it r
','/ # slices the top element of stack from each ','
# so we get ["1" "3-5" "9" "16" "18-23"]
{...}% # makes a function block ... and calls it for
# each element in the list
'-'/{~}% # slices the list by '-' and evals each element
# from string to int. ["1"] becomes [1],
# ["3-5"] becomes [3 5]
.,1- # adds the length of the list -1 on top of the stack
# so for [1] the stack becomes [1] 0, for [3 5]
# it becomes [3 5] 1
# next we add two function blocks, they, like the 0/1 just before
# are used by an if clause a tiny bit later. First block is for
# lists that have a 1 on top of them, the latter for ones with 0.
# First block, we have something like [3 5]
))+ # pops the top element of the array, increments
# it and puts back. [3 6]
## It seems {...}%~ is same as {...}/
## this is why these two are not in the code any more
{,}% # , makes a list from 0 to n-1, where n is the parameter
# so we get [[0 1 2] [0 1 2 3 4 5]]
~ # Dumps the outer array, [0 1 2] [0 1 2 3 4 5]
\ # swaps the two arrays
- # set complement [3 4 5]
~ # dumps the array, so the elements are left in the stack
# Second block, we have something like [16]
~ # just dumps the array, 16
# Blocks end
if # takes the top three elements of the stack, evaluates the
# first (0 or 1), runs second if true (anything but
# [], "", 0 or {} ), otherwise the third.
","* # joins an array with ","
редагувати 1: змінив останній {}% ~ на {} /, також мій опис, ймовірно, був неправильним.
4-9,1-2
або1-3,9-6
?