首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从一组数字中返回每个数字

从一组数字中返回每个数字
EN

Code Golf用户
提问于 2012-10-03 16:25:30
回答 13查看 992关注 0票数 11

挑战

程序必须返回包含在一组数字中的所有数字(逗号和连字符分隔的序列)。

规则

  • s是序列字符串;
  • 包括在s中的所有数字均为正;
  • 人数将不断增加;
  • 数字永远不会重复
  • 回答时,显示s="1,3-5,9,16,18-23"的输出

示例

代码语言:javascript
运行
复制
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

祝好运。=)

EN

回答 13

Code Golf用户

回答已采纳

发布于 2012-10-03 22:46:13

GolfScript (24个字符)

代码语言:javascript
运行
复制
','/{~.,!{~)),>~}*}%','*

例如。

代码语言:javascript
运行
复制
$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

我实际上有四个24字符的解决方案,但我选择了这个,因为它没有任何字母数字字符。

是如何工作的

代码语言:javascript
运行
复制
# 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
票数 6
EN

Code Golf用户

发布于 2019-06-24 21:14:17

R,44字节

代码语言:javascript
运行
复制
`-`=seq;eval(parse(t=c("c(",scan(,""),")")))

在网上试试!

-重新定义为seq (即:),用c()包围输入并计算相应的表达式。

票数 4
EN

Code Golf用户

发布于 2019-06-24 19:01:03

果冻,9字节

代码语言:javascript
运行
复制
⁾-ryṣ”,VF

在网上试试!

代码语言:javascript
运行
复制
   y         Replace
⁾-r          hyphens with the letter r,
    ṣ”,      split on commas,
       V     evaluate every element,
        F    and flatten.

range dyad r在其两侧接受两个参数,并在它们之间生成一个包含范围。

票数 3
EN
页面原文内容由Code Golf提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codegolf.stackexchange.com/questions/8588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档