排他的および包括的範囲にわたる製品


18

触発され、この問題により、@CᴏɴᴏʀO'Bʀɪᴇɴ

質問から取られた:

タスクは簡単です。2つの整数aとbが与えられた場合、output [a、b]を出力します。つまり、aとbの間の範囲の積です。a、bは、関数、リスト入力、STDINなどの引数であるかどうかにかかわらず、任意の妥当な形式で使用できます。戻り値(関数の場合)やSTDOUTなど、妥当な形式で出力できます。aは常にbよりも小さくなります。

末尾は、bを排他的または包括的に指定できることに注意してください。私は好き嫌いはありません。^ _ ^

この課題の違いは、範囲の種類について慎重になることです。入力は次の形式の文字列です[a,b](a,b][a,b)、または(a,b)どこ[]包括的境界であると()排他的な境界です。明示的な境界が与えられた場合、範囲の積を提供します。また、入力範囲には常に少なくとも1つの数字が含ま(3,4)れます。つまり、無効な範囲はテストする必要がないことを意味します。

テストケース

[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24

(a,b] => result
(2,5] => 60
(5,10] => 30240
(-4,3] => 0
(0,3] => 6
(-4,-1] => -6

(a,b) => result
(2,5) => 12
(5,10) => 3024
(-4,3) => 0
(0,3) => 2
(-4,0) => -6

これはであるため、バイト単位の最短プログラムが優先されます。


リーダーボード

この投稿の下部にあるスタックスニペットは、a)言語ごとの最短ソリューションのリストとして、b)全体的なリーダーボードとして、回答からカタログを生成します。

回答が表示されるようにするには、次のマークダウンテンプレートを使用して、見出しから回答を開始してください。

## Language Name, N bytes

N提出物のサイズはどこですか。スコアを改善する場合、古いスコアを打つことで見出しに残すことができます。例えば:

## Ruby, <s>104</s> <s>101</s> 96 bytes

ヘッダーに複数の数字を含める場合(たとえば、スコアが2つのファイルの合計であるか、インタープリターフラグペナルティーを個別にリストする場合)、実際のスコアがヘッダーの最後の数字であることを確認します。

## Perl, 43 + 2 (-p flag) = 45 bytes

言語名をリンクにして、スニペットに表示することもできます。

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

回答:



3

Python 2、72バイト

lambda s:reduce(int.__mul__,range(*eval(s[1:-1]+'+'+`']'in s`))[s<'[':])

数値を抽出するために、評価s[1:-1]文字列を削除した入力文字列、つまりタプルが得られます。アイデアはrange、このタプルを取得して製品を取得することです。

lambda s:reduce(int.__mul__,range(*eval(s[1:-1]))

ファジングは、エンドポイントを調整するために起こります。入力が始まる場合、上部エンドポイントは、簡単に最初の要素オフだけ切断される(ように行われ、[s<'[':]

もう一方のエンドポイントは扱いにくいです。Pythonには、リストl[:0]全体を削除するため、リストの最後の要素を条件付きで削除する明確な方法がありません。だから、私たちは奇妙なことをします。それは、文字列の上にタックに評価される前に私たちは、タプルの文字列を変更する"+True""+False"にかかわらの両端に応じて、]または)。結果は以下のようなものなものである3,7のいずれかになり3,7+Falseある3,7、または3,7+Trueです3,8

別のきれいな72:

lambda s:eval("reduce(int.__mul__,range((s<'[')+%s+(']'in s)))"%s[1:-1])

3

Minecraft 15w35a +、プログラムサイズ638合計(以下を参照)

ここでの私の答えと同じですが、修正されました。Minecraftには文字列の入力がないため、スコアボードの入力を維持する自由を取りました。それが問題である場合、この答えは非競争的であると考えてください。

ここに画像の説明を入力してください

これPI a,bは、2つのレバーで指定された包括的/排他的に計算します。ここに画像の説明を入力してください入力は、次の2つのコマンドを使用することによって与えられる:/scoreboard players set A A {num}/scoreboard players set B A {num}/scoreboard objectives add A dummy入力する前に使用することを忘れないでください。

使用して得点:{program size} + ( 2 * {input command} ) + {scoreboard command} = 538 + ( 2 * 33 ) + 34 = 638

このコードは、次の擬似コードに対応しています。

R = 1
T = A
loop:
  R *= A
  A += 1
  if A == B:
    if A.exclusive:
      R /= T
    if B.exclusive:
      R /= B
    print R
    end program

ここから世界をダウンロードしてください


2

Pyth、20バイト

*FPW}\)ztW}\(z}FvtPz

オンラインで試す:デモンストレーションまたはテストスイート

説明:

*FPW}\)ztW}\(z}FvtPz   implicit: z = input string
                 tPz   remove the first and last character of z
                v      evaluate, returns a tuple of numbers
              }F       inclusive range
        tW             remove the first number, if
          }\(z            "(" in z
  PW                   remove the last number, if
    }\)z                  ")" in z
*F                     compute the product of the remaining numbers

2

ルビー、79 77バイト

->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*}

79バイト

->s{a,b=s.scan(/\-?\d+/).map &:to_i;((s[?[]?a:a+1)..(s[?]]?b:b-1)).reduce 1,:*}

ゴルフをしていない:

-> s {
  a,b=s.scan /\-?\d+/    # Extracts integers from the input string, s
  (
    a.to_i+(s[?[]?0:1).. # Increase start of the range by 1 if s contains `(`
    b.to_i-(s[?]]?0:1)   # Decrease end of the range by 1 if s contains `)`
  ).reduce 1,:*
}

使用法:

->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*}["(2,5]"]
=> 60

2

真剣に、31バイト

,#d@p@',@s`εj≈`Mi(@)']=+)'(=+xπ

入力を文字列として受け取ります(二重引用符で囲みます)

オンラインで試す(入力は手動で入力する必要があります)

説明:

,#d@p@                             get input, take first and last character off and push them individually
      ',@s`εj≈`Mi                  split on commas, map: join on empty, cast to int; explode list
                 (@)']=+)'(=+      increment start and end if braces are ( and ] respectively (since range does [a,b))
                             xπ    make range, push product

1

Python 3、104

y,r=input().split(',')
t=int(y[1:])+(y[0]<')')
for x in range(t+1,int(r[:-1])+(r[-1]>'[')):t*=x
print(t)

stdinから入力を受け取ります。


実際に同じ2番目のOo
Eumel

@Eumelそれはバッジであるべきです。
モーガンスラップ

病気は今すぐメタに投稿しています^^
ユーメル

@Eumel:実際、あなたはモーガン・スラップの1秒前にあなたのものを投稿しました
ev3commander

まあ、本当に?両方の回答でn秒前に回答が表示されました
Eumel

1

MATLAB、86 70バイト

s=sscanf(input(''),'%c%d,%d%c');a=s<42;disp(prod(a(1)+s(2):s(3)-a(4)))

これはOctaveでも機能します。こちらからオンラインで試すことができます。そのワークスペースにコードをスクリプトとして追加したのでproductRange、プロンプトで入力するだけで、入力などを入力できます'(2,5]'


そのため、コードは最初に入力をスキャンして、括弧と数字を一緒に抽出します。

s=sscanf(input(''),'%c%d,%d%c');

これはで構成される配列を返します[bracket, number, number, bracket]

配列はと比較され42、実際には42から90までの任意の数が含まれます。これは、それがどの種類のブラケットであったかを決定し、排他的ブラケットの場合は1を、包括的ブラケットの場合は0を与えます。

a=s<42;

最後に、必要な範囲の製品を表示します。

disp(prod(a(1)+s(2):s(3)-a(4)))

製品は、最初の数字s(2)と最初のブラケットタイプa(1)(排他ブラケットの場合は1)で始まる番号で、2番目の番号s(3)から2番目のブラケットタイプを引いたものまでa(4)です。これにより、正しい包括的/排他的範囲が得られます。


1

ジュリア、75バイト

s->prod((x=map(parse,split(s[2:end-1],",")))[1]+(s[1]<41):x[2]-(s[end]<42))

これは、文字列を受け入れて整数を返す匿名関数です。呼び出すには、名前を付けf=s->...ます。

ゴルフをしていない:

function f(s::AbstractString)
    # Extract the numbers in the input
    x = map(parse, split(s[2:end-1], ","))

    # Construct a range, incrementing or decrementing the endpoints
    # based on the ASCII value of the surrounding bracket
    r = x[1]+(s[1] == 40):x[2]-(s[end] == 41)

    # Return the product over the range
    return prod(r)
end

1

Mathematica、128バイト

1##&@@Range[(t=ToExpression)[""<>Rest@#]+Boole[#[[1]]=="("],t[""<>Most@#2]-Boole[Last@#2==")"]]&@@Characters/@#~StringSplit~","&

これは長すぎる...現在を考えるStringReplace+のRegularExpressionソリューション。


0

PowerShell、146 104バイト

param($i)$a,$b=$i.trim("[]()")-split',';($a,(1+$a))[$i[0]-eq'(']..($b,(+$b-1))[$i[-1]-eq')']-join'*'|iex

入力から数値を抽出する方法を変更することにより、42バイトを使い果たしました。わー!

param($i)                          # Takes input string as $i
$a,$b=$i.trim("[]()")-split','     # Trims the []() off $i, splits on comma,
                                   # stores the left in $a and the right in $b

($a,(1+$a))[$i[0]-eq'(']..($b,(+$b-1))[$i[-1]-eq')']-join'*'|iex
# Index into a dynamic array of either $a or $a+1 depending upon if the first
# character of our input string is a ( or not
# .. ranges that together with
# The same thing applied to $b, depending if the last character is ) or not
# Then that's joined with asterisks before
# Being executed (i.e., eval'd)


0

Perl 6、60バイト

{s/\((\-?\d+)/[$0^/;s/(\-?\d+)\)/^$0]/;s/\,/../;[*] EVAL $_}

(2,5]Perl 6で例を書く方法は2^..5[2^..5]また機能する)ため、少し不一致があります。
スワップに持っている私はそう(2[2^、と,して..、その後、私が持っているEVAL範囲にそれ。


使用法:

# give it a name
my &code = {...}

# the `$ =` is so that it gets a scalar instead of a constant

say code $ = '(2,5)'; # 12
say code $ = '[2,5)'; # 24
say code $ = '(2,5]'; # 60
say code $ = '[2,5]'; # 120

say code $ = '(-4,0)' # -6
say code $ = '[-4,0)' # 24
say code $ = '(-4,0]' # 0
say code $ = '[-4,0]' # 0

say code $ = '(-4,-1)' # 6
say code $ = '[-4,-1)' # -24
say code $ = '(-4,-1]' # -6
say code $ = '[-4,-1]' # 24

# this is perfectly cromulent,
# as it returns the identity of `*`
say code $ = '(3,4)'; # 1

0

CJam、34バイト

r)\(@+"[()]"2/\.#\',/:i.+~1$-,f+:*

オンラインで試す

説明:

r       Read input.
)       Split off last character.
\       Swap rest of input to top.
(       Split off first character.
@       Rotate last character to top.
+       Concatenate first and last character, which are the two braces.
"[()]"  Push string with all possible braces.
2/      Split it into start and end braces.
\       Swap braces from input to top.
.#      Apply find operator to vector elements, getting the position of each brace
        from input in corresponding list of possible braces. The lists of braces
        are ordered so that the position of each can be used as an offset for the
        start/end value of the interval.
\       Swap remaining input, which is a string with two numbers separated by
        a comma, to top.
',/     Split it at comma.
:i      Convert the two values from string to integer.
.+      Element-wise addition to add the offsets based on the brace types.
~       Unwrap the final start/end values for the interval.
1$      Copy start value to top.
-       Subtract it from end value.
,       Build 0-based list of values with correct length.
f+      Add the start value to all values.
:*      Reduce with multiplication.

0

JavaScript(ES6)、90バイト

s=>eval(`for(n=s.match(/-*\\d+/g),i=n[0],c=s[0]<"["||i;++i<+n[1]+(s.slice(-1)>")");)c*=i`)

説明

s=>
  eval(`                    // use eval to allow for loop without return or {}
    for(
      n=s.match(/-*\\d+/g), // n = array of input numbers [ a, b ]
      i=n[0],               // i = current number to multiply the result by
      c=s[0]<"["||i;        // c = result, initialise to a if inclusive else 1
      ++i<+n[1]             // iterate from a to b
        +(s.slice(-1)>")"); // if the end is inclusive, increment 1 more time
    )
      c*=i                  // multiply result
  `)                        // implicit: return c

テスト


0

R、102の 104バイト

f=function(s){x=scan(t=gsub('\\(|\\[|,|\\)|\\]',' ',s))+c(grepl('^\\(',s),-(grepl('\\)$',s)));prod(x[1]:x[2])}

非ゴルフ

f=function(s){
    # remove delimiting punctuation from input string, parse and return an atomic vector
    x=scan(t=gsub('\\(|\\[|,|\\)|\\]',' ',s)) +
    # add /subtract from the range dependent on the `[)` pre/suf-fixes
    c(grepl('^\\(',s),-(grepl('\\)$',s)))
    # get the product of the appropriate range of numbers
    prod(x[1]:x[2])
}

負の数を許可するように編集する[さらに2文字を犠牲にして


言語?
ThisSuitIsBlackNot

@ThisSuitIsBlackNot - R(および回答に固定)
mnel

0

JavaScript(ES6)、79

匿名メソッドとして

r=>eval("[a,b,e]=r.match(/-?\\d+|.$/g);c=a-=-(r<'@');for(b-=e<'@';a++<b;)c*=a")

テストスニペット

F=r=>eval("[a,b,e]=r.match(/-?\\d+|.$/g);c=a-=-(r<'@');for(b-=e<'@';a++<b;)c*=a")

// TEST
console.log=x=>O.innerHTML+=x+'\n'

;[
 ['[2,5)',24],['[5,10)',15120],['[-4,3)',0],['[0,3)',0],['[-4,0)',24],
 ['[2,5]',120],['[5,10]',151200],['[-4,3]',0],['[0,3]',0],['[-4,-1]',24],
 ['(2,5]',60],['(5,10]',30240],['(-4,3]',0],['(0,3]',6],['(-4,-1]',-6],
 ['(2,5)',12],['(5,10)',3024],['(-4,3)',0],['(0,3)',2],['(-4,0)',-6]
].forEach(t=>{
  r=F(t[0]),k=t[1],console.log(t[0]+' -> '+r+' (check '+k+ (k==r?' ok)':' fail)'))
})
<pre id=O></pre>

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