返回一组数字中的每个数字

11

规则

• `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
``````

1

1

@Gareth是的，这是一个代码高尔夫，然后请投票给我最短的答案。马特和彼得，我编辑了问题，请检查。谢谢！
BernaMariano

6

GolfScript（24个字符）

``````','/{~.,!{~)),>~}*}%','*
``````

``````\$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23
``````

这个怎么运作

``````# 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
``````

BernaMariano 2012年

@BernaMariano，对不起，我以某种方式错过了您的问题。我将详细解释扩展答案。

7

Perl 25 26 25

`\$_` 是序列字符串

``````s/-/../g;\$_=join",",eval
``````

``````[~/] \$ perl -M5.010 -pe 's/-/../g;\$_=join",",eval' <<< "1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23
``````

ardnew

Gareth 2012年

4

golfscript，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
``````

``````{...}: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 ","
``````

2
+1，因为任何在GolfScript中进行程序的人都可以得到。
Gareth 2012年

@加雷斯谢谢。我首先以为我会以perl的方式进行操作：将-更改为..并对其进行评估。然后我找不到建立任何数组的任何明智方法，所以我做到了。我确信有人会用golfscript带来大约20个字符的解决方案。
shiona 2012年

Peter Taylor

PS `{...}%~`和之间有细微的差别`{...}/`。如果您要使用堆栈访问更远的内容，`integer \$`则第一个比较简单，因为您不必每次都调整整数以补偿剩余的内容。

4

R，44个字节

```-`=seq;eval(parse(t=c("c(",scan(,""),")")))``

3

K，47

``````","/:,/\${x+!1+y-x}.'2#'a,'a:"I"\$'"-"\:'","\:0:0
``````

``````k)","/:,/\${x+!1+y-x}.'2#'a,'a:"I"\$'"-"\:'","\:0:0
1,3-5,9,16,18-23
"1,3,4,5,9,16,18,19,20,21,22,23"
``````

`","/:\$,/{{x+!1+y-x}. 2#"J"\$"-"\:x}'","\:0:0`对于43个字节
streetster '19

3

果冻，9字节

``````⁾-ryṣ”,VF
``````

``````   y         Replace
⁾-r          hyphens with the letter r,
ṣ”,      split on commas,
V     evaluate every element,
F    and flatten.
``````

2

J，53 43 41 39 38个字符

``````;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
``````

``````   ;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1-4,8-11
1 2 3 4 8 9 10 11
``````

``````   ;(}.[:i.1+])/&.>".'- ,;'charsub 1!:1[1
1,3-5,9,16,18-23
1 3 4 5 9 16 18 19 20 21 22 23
``````

2

Hassium，173字节

`````` func main(){p="1,2,3,5-8".split(",")for(c=0;c<p.length;c++){e=p[c]if(e.contains("-")){p=e.split("-")for(x=p[0].toInt();x<=p[1].toInt()print(x++ +",")){}}else print(e+",")}}
``````

1

Python 2.7版，147个 138字节

```z，f = input（）。split（'，'），[]

x = i.split（'-'）
如果len（x）> 1：f + = range（int（x [0]），int（x [1]）+ 1）
else：f + = [int（x [0]）]

```

```>>> python nums.py
“ 1,3-5,9,16,18-23”
1、3、4、5、9、16、18、19、20、21、22、23
```

1

intrepidcoder

Alex

1

MATLAB，47个字节

``````disp(eval(['[',strrep(input(''),'-',':'),']']))
``````

``````'1,3-5,9,16,18-23'
``````

``````1     3     4     5     9    16    18    19    20    21    22    23
``````

BernaMariano

1

Perl 6，36个字节

``\$_=get;say join ',',EVAL S:g/\-/../``
``1,3,4,5,9,16,18,19,20,21,22,23``

1

PowerShell，79 71字节

``('('+(\$args[0]-replace'-','..'-replace',','),(')+')'|iex|%{\$_})-join','``

用法

``````PS C:\Tools\Scripts\golfing> .\return-each-number-from-a-group-of-numbers.ps1 '1,3-5,9,16,18-23'
1,3,4,5,9,16,18,19,20,21,22,23``````

-8字节归功于Veskah

1

K（oK），40 31字节

``````,/{{x+!1+y-x}. 2#.:'"-"\x}'","\
``````

``````,/{{x+!1+y-x}. 2#.:'"-"\x}'","\ / the solution
","\ / split input on ","
{                      }'     / apply lambda to each
"-"\x       / split x on "-"
.:'            / value (.:) each (')
2#               / 2 take (dupe if only 1 element)
{        }.                  / diadic lambda, 2 args x and y
y-x                    / y subtract x
!                         / range 0..n
,/                              / flatten
``````

0

Clojure，110字节

``````#(clojure.string/join","(for[s(.split %",")[a b][(map read-string(.split s"-"))]r(if b(range a(inc b))[a])]r))
``````

0

Python 2，112字节

``````L=[]
for s in input().split(','):
if'-'in s:a,b=map(int,s.split('-'));L+=range(a,b+1)
else:L+=[int(s)]
print L``````

0

Japt，12个字节

``````q, c@OvXr-'ò
``````

@Oliver是一个古老的挑战，它没有指定其I / O格式，因此我谨慎地犯错，将输入作为逗号分隔的字符串并将输出作为展平的数组。但是，通常情况下，是的，我将输入指定为字符串数组，将输出指定为多维数组，并且仅用于`£`代替前5个字节。

0

Python 2，90个字节

``lambda s:sum((range(u[0],u[-1]+1)for u in[map(int,t.split('-'))for t in s.split(',')]),[])``