挑战
程序必须返回包含在一组数字中的所有数字(逗号和连字符分隔的序列)。
s
是序列字符串;s
中的所有数字均为正;s="1,3-5,9,16,18-23"
的输出input(s) outputs
-----------------
1 1
1,2 1,2
1-4 1,2,3,4
1-4,6 1,2,3,4,6
1-4,8-11 1,2,3,4,8,9,10,11
祝好运。=)
发布于 2012-10-03 22:46:13
','/{~.,!{~)),>~}*}%','*
例如。
$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23
我实际上有四个24字符的解决方案,但我选择了这个,因为它没有任何字母数字字符。
# On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
# This is executed for each of those strings in a map
# So stack holds e.g. "1" or "3-5"
# Evaluate the string.
# If it's a single number, this puts the number on the stack.
# Otherwise it's parsed as a positive number followed by a negative number.
~
# Stack holds e.g. 1 or 3 -5
# Duplicate the last element on the stack and make a list of that length.
# If it's negative or zero, the list will be empty
.,
# Negate. An empty list => 1; a non-empty list => 0
!
# If the string was a single number "n", the stack now holds n 0
# If the string was a range "m-n", the stack now holds m -n 1
# The following block will be executed 0 times for "n" and once for "m-n"
{
# Here we rely on twos-complement numbers satisfying ~n = -n -1
# Stack: m -n
~))
# Stack: m -(-n)-1+2 = m n+1
,
# Stack: m [0 1 2 ... n]
>
# Stack: [m m+1 ... n]
~
# Stack: m m+1 ... n
}*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output
发布于 2019-06-24 21:14:17
https://codegolf.stackexchange.com/questions/8588
复制相似问题