数字のグループから各数字を返します


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
我々はこれまで常に、たとえば、増加されていない入力シーケンスを持っています:4-9,1-21-3,9-6
マット

1
または重なっていますか?出力を並べ替える必要があり、重複が含まれていませんか?
ピーターテイラー

@Garethはい、これはコードゴルフです。最短の回答に投票してください。マットとピーター、質問を編集しました。確認してください。ありがとう!
ベルナマリアーノ

完全なプログラムである必要があり、出力の形式に制限はありますか?
ブラッドギルバートb2gills

回答:


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

実際には、24文字のソリューションが4つありますが、英数字が含まれていないため、これを選択しました。

使い方

# 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

単一の文字を使用せずに3-5を3,4,5に拡張するにはどうすればよいです-か?
ベルナマリアーノ

@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

オプションの文字数に1文字を追加しました(Gareth、.. kindaに感謝)。-n-p


おそらく、コマンドラインオプションを使用して、文字カウントを間違って行った可能性があります。私のカウントを修正してください
-ardnew

metaこの質問の答えを見ると、nオプションに1文字だけ追加する必要があります。
ガレス

取り外し-M5.010や交換の-eために-E
ブラッド・ギルバートがb2gills

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

あなたは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:最後の{}%〜を{} /に変更し、説明が間違っている可能性もありました。


2
+1。GolfScriptでプログラムを実行している人は誰でも獲得しているからです。
ガレス

@Garethありがとう。私は最初にperlの方法でそれをやると思った:change-to ..そしてそれを評価する。その後、配列を構築するための適切な方法を見つけることができなかったので、これを行いました。だれかがgolfscriptを使用して20文字以下のソリューションを提供することになるでしょう。
潮ona

現時点では24を持っているので、チャレンジとして20を使います;)でも、かなり簡単に節約できます。あなたが最初の失うことができるので問題は、プログラムではなく、機能を要求{し、最終的に}:r;、あなたはまた、置換することによって、1を保存することができ1-(。(ちなみに、IIRCは、最初のGolfScriptプログラムで見逃したトリックの1つです)
ピーターテイラー

PSとは微妙な違いが{...}%~あり{...}/ます。スタックのさらに下にあるものにアクセスする場合integer $、最初のスタックを使用する方が簡単です。スタックに残しているものを補うために毎回整数を調整する必要がないからです。
ピーターテイラー


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


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

パイソン2.7、147の 138バイト

z、f = input()。split( '、')、[]
zのiの場合:
 x = i.split( '-')
 len(x)> 1:f + = range(int(x [0])、int(x [1])+ 1)
 else:f + = [int(x [0])]
印刷str(f)[1:-1]

使用法:

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

最高のプログラムではありません...


1
PPCGへようこそ。インデントに1つのスペースを使用すると、回答を短くすることができると思います。
-intrepidcoder

@intrepidcoderに感謝します。単一スペースのインデントを使用できることを知りませんでした。
アレックス

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

チャレンジでは、グループ内のすべての数字を表示する必要があるというだけなので、この出力は許可されると思います。


カンマで区切られた出力はよりよい、私はSEできるもののだろう5-スペースで区切られたパターン、thatsのが私のためにクール:)
BernaMariano


1

PowerShell、79 71バイト

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

オンラインでお試しください!

内側の部分は、「1,5-9,12」を「(1)、(5..9)、(12)」形式に変更し、PowerShellが理解し、iexでそれを実行して、配列の配列を作成します。次に、各内部配列を反復処理し、最後にすべての外部配列要素を結合します

「Help Me Manage My Time」回答からコードを借りる

使用法

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

Veskahのおかげで-8バイト



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
       1+                       / add 1
      !                         / range 0..n
    x+                          / add x
,/                              / 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

Japt、12バイト

q, c@OvXr-'ò

それを試してみてください


あなたは置き換えることができc@£
オリバー

@Oliverは、I / O形式を指定しない古いチャレンジであるため、入力をコンマ区切りの文字列として受け取り、平坦化された配列として出力することに注意しました。ただし、通常は、文字列の配列として入力を指定し、多次元配列として出力を指定し£、最初の5バイトの代わりに使用します。
シャギー

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.