Prodotto su gamme esclusive e inclusive


18

Ispirato da questa domanda di @ CᴏɴᴏʀO'Bʀɪᴇɴ .

Tratto dalla domanda:

Il tuo compito è semplice: dati due numeri interi aeb, output ∏ [a, b]; vale a dire, il prodotto dell'intervallo tra a e b. Puoi prendere aeb in qualsiasi formato ragionevole, che si tratti di argomenti per una funzione, un input di elenco, STDIN, eccetera. È possibile produrre in qualsiasi formato ragionevole, ad esempio un valore di ritorno (per funzioni) o STDOUT. a sarà sempre inferiore a b.

Si noti che la fine può essere esclusiva o inclusiva di b. Non sono schizzinoso. ^ _ ^

La differenza per questa sfida è che saremo esigenti riguardo al tipo di intervallo. Ingresso è una stringa della forma [a,b], (a,b], [a,b), o (a,b)dove []è un confine inclusivo e ()è un confine esclusiva. Dati i confini espliciti, fornire il prodotto della gamma. Inoltre, l'intervallo di input includerà sempre almeno 1 numero, il che significa che intervalli come (3,4)non sono validi e non devono essere testati.

Casi test

[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

Questo è un , quindi vince il programma più breve in byte.


Classifica

Lo snippet di stack nella parte inferiore di questo post genera il catalogo dalle risposte a) come elenco della soluzione più breve per lingua eb) come classifica generale.

Per assicurarti che la tua risposta venga visualizzata, ti preghiamo di iniziare la risposta con un titolo, utilizzando il seguente modello Markdown:

## Language Name, N bytes

dov'è Nla dimensione del tuo invio. Se si migliora il punteggio, è possibile mantenere i vecchi punteggi nel titolo, colpendoli. Per esempio:

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

Se si desidera includere più numeri nell'intestazione (ad es. Perché il punteggio è la somma di due file o si desidera elencare separatamente le penalità del flag dell'interprete), assicurarsi che il punteggio effettivo sia l' ultimo numero nell'intestazione:

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

Puoi anche rendere il nome della lingua un collegamento che verrà quindi visualizzato nello snippet:

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

Risposte:


7

LabVIEW, 38 LabVIEW Primitives

"leggermente" modificato, ora imposta gli intervalli scansionando per () e [] e aggiungendo l'indice ai numeri.

primo


5
Avendo una lingua che richiede una gif di fantasia, hai immediatamente guadagnato ∞ rep. GG. +1
Addison Crump,

3

Python 2, 72 byte

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

Per estrarre i numeri che valutiamo s[1:-1], la stringa di input con le estremità rimosse, che fornisce una tupla. L'idea è quella di ottenere rangequesta tupla e prendere il prodotto.

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

Il fondente sembra regolare gli endpoint. L'endpoint superiore è semplice, basta tagliare il primo elemento se l'input inizia con (, fatto come [s<'[':].

L'altro endpoint è più complicato. Python non ha un modo pulito per rimuovere in modo condizionale l'ultimo elemento di un elenco perché l[:0]rimuove tutto. Quindi facciamo qualcosa di strano. Modifichiamo la stringa di tupla prima che venga valutata per virare sulla stringa "+True"o a "+False"seconda che s termini in ]o ). Il risultato è che qualcosa del genere 3,7diventa o 3,7+Falseche è 3,7o 3,7+Trueche è 3,8.

Alternativo, più carino 72:

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

3

Minecraft 15w35a +, dimensione del programma 638 totale (vedi sotto)

Come la mia risposta qui , ma modificata. Poiché Minecraft non ha input di stringa, mi sono preso la libertà di mantenere l'input del tabellone. Se questo è un problema, considera questa risposta non competitiva.

inserisci qui la descrizione dell'immagine

Questo calcola PI a,bcon inclusivo / esclusivo specificato dalle due leve. inserisci qui la descrizione dell'immagineL'input viene dato usando questi due comandi: /scoreboard players set A A {num}e /scoreboard players set B A {num}. Ricorda di usare /scoreboard objectives add A dummyprima dell'input.

Valutato con: {program size} + ( 2 * {input command} ) + {scoreboard command} = 538 + ( 2 * 33 ) + 34 = 638.

Questo codice corrisponde al seguente psuedocode:

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

Scarica il mondo qui .


2

Pyth, 20 byte

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

Provalo online: Dimostrazione o Test Suite

Spiegazione:

*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

Rubino, 79 77 byte

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

79 byte

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

Ungolfed:

-> 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,:*
}

Uso:

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

2

Scherzi a parte, 31 byte

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

Accetta input come stringa (racchiuso tra virgolette doppie)

Provalo online (l'input deve essere inserito manualmente)

Spiegazione:

,#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)

Riceve input dallo stdin.


abbiamo effettivamente pubblicato le nostre risposte nello stesso secondo Oo
Eumel

@Eumel Dovrebbe essere un badge.
Morgan Thrapp,

in realtà lo pubblicherò su Meta proprio ora ^^
Eumel

@Eumel: In realtà hai pubblicato il tuo 1 secondo prima di Morgan Thrapp
ev3commander l'

Oh veramente? ha mostrato la risposta n secondi fa su entrambe le risposte
Eumel,

1

MATLAB, 86 70 byte

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

Questo funziona anche con Octave . Puoi provare online qui . Ho aggiunto il codice come script a quell'area di lavoro, quindi puoi semplicemente inserire productRangeal prompt, quindi inserire il tuo input, ad es '(2,5]'.


Quindi il codice analizza prima l'input per estrarre le parentesi e i numeri:

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

Ciò restituisce un array di cui è composto [bracket, number, number, bracket].

L'array viene confrontato 42, in realtà qualsiasi numero compreso tra 42 e 90 inclusi lo farà. Questo determina quale tipo di parentesi era, dando un 1 se si tratta di una parentesi esclusiva e uno 0 se una parentesi inclusiva.

a=s<42;

Infine, visualizziamo il prodotto della gamma richiesta:

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

Il prodotto è composto da numeri che iniziano con il primo numero s(2)più il primo tipo di parentesi a(1)(che è un 1 se è una parentesi esclusiva), che vanno fino al secondo numero incluso e s(3)meno il secondo tipo di parentesi a(4). Questo fornisce la gamma inclusiva / esclusiva corretta.


1

Julia, 75 byte

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

Questa è una funzione anonima che accetta una stringa e restituisce un numero intero. Per chiamarlo, dagli un nome, ad es f=s->....

Ungolfed:

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 byte

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

È troppo lungo ... Attualmente sto pensando a una soluzione StringReplace+ RegularExpression.


0

PowerShell, 146 104 byte

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

Rimosso da 42 byte modificando il modo in cui i numeri vengono estratti dall'input. Corteggiare!

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 byte

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

C'è un po 'di errata corrispondenza perché il modo in cui scriveresti l' (2,5]esempio in Perl 6 sarebbe 2^..5( [2^..5]funziona anche).
Quindi devo scambiare (2con [2^e ,con .., quindi devo EVALfarlo in un intervallo.


utilizzo:

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

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

Provalo online

Spiegazione:

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 byte

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

Spiegazione

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

Test


0

R, 102 104 byte

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

Ungolfed

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])
}

modifica per consentire numeri negativi [a scapito di altri 2 caratteri



@ThisSuitIsBlackNot - R(e risolto in risposta)
mnel

0

JavaScript (ES6), 79

Come metodo anonimo

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

Snippet di prova

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>

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.