| Bytes | Lang | Time | Link |
|---|---|---|---|
| 020 | Pip | 211208T235559Z | DLosc |
| 018 | Vyxal | 211208T043034Z | lyxal |
| 057 | Wolfram Language Mathematica | 211208T064937Z | att |
| 069 | TIBasic | 211208T003147Z | Youserna |
| 064 | Julia 0.4 | 211207T135025Z | MarcMush |
| 075 | Julia 0.4 | 151210T194035Z | Alex A. |
| 068 | JavaScript ES6 | 211207T060429Z | user1824 |
| 094 | Haskell | 211205T184141Z | Benji |
| 025 | Japt | 201028T145953Z | Shaggy |
| 079 | JavaScript ES6 | 151211T155919Z | edc65 |
| 031 | Seriously | 151211T143443Z | user4594 |
| 638 | Minecraft 15w35a+ | 151211T140747Z | GamrCorp |
| 077 | Ruby | 151211T121437Z | Vasu Ada |
| 104 | R | 151211T031822Z | mnel |
| 020 | Pyth | 151211T084139Z | Jakube |
| 090 | JavaScript ES6 | 151211T084945Z | user8165 |
| 072 | Python 2 | 151211T080322Z | xnor |
| 034 | CJam | 151211T060423Z | Reto Kor |
| 128 | Mathematica | 151211T020936Z | LegionMa |
| 060 | Perl 6 | 151210T174310Z | Brad Gil |
| 041 | Japt | 151210T172203Z | ETHprodu |
| 104 | PowerShell | 151210T164143Z | AdmBorkB |
| 070 | MATLAB | 151210T154240Z | Tom Carp |
| 104 | Python 3 | 151210T153921Z | Morgan T |
| 038 | LabVIEW | 151210T153920Z | Eumel |
Pip, 20 bytes
$*VaR^"(][)"['U"+1"]
Attempt This Online! Or, verify all test cases.
Explanation
Conveniently, , is Pip's range operator; it is inclusive on the lower end and exclusive on the upper end. So if we turn the brackets into appropriate tweaks to the numbers, we can use eval to generate the range.
$*VaR^"(][)"['U"+1"]
aR In the input, replace each string in
"(][)" This string
^ Split into a list of characters
with the corresponding string in
[ ] this list:
'U ( becomes U (increment the following number)
"+1" ] becomes +1 (add 1 to the preceding number)
[ and ) don't have a corresponding replacement, so they are
simply deleted (leaving the numbers unchanged)
V Evaluate the result as a Pip expression
$* Fold on multiplication
Vyxal, 24, 18 bytes
₌≬k+iE₍ht‛(]f=+÷rΠ
I'm actually really proud of this answer, because it uses the new modifier parsing of 2.6.
With syntax highlighting:
Explained
₌≬k+iE₍ht‛(]f=+÷rΠ
₌ # Apply the following to the same stack:
≬ # The next 3 elements as a single lambda, taking argument n:
k+iE # eval(n[1:-1]) - the two numbers separated by a comma
₌ # and
₍ht # [n[0], n[-1]] - the range brackets
‛(]f= # Does the first bracket equal "(" and does the last bracket equal "]" - this determines how much to offset the range; because the two numbers in the original input will be passed to Vyxal's range function which acts like python's range() function
+ # add those offsets: an exclusive range start means the first number needs to be incremented because range() includes the first argument. an inclusive range start means the last number needs to be incremented because range() stops before the last argument.
÷r # push the range between the two numbers + their offsets
Π # and take the product
Wolfram Language (Mathematica), 57 bytes
1##&@@ToExpression["Range"<>(#/."("->"[1+"/.")"->"-1]")]&
Input a list of characters.
Fairly straightforward. Mathematica uses [ ] to introduce arguments, and Range is inclusive on both ends.
Wolfram Language (Mathematica), 69 bytes
1##&@@ToExpression["Range"<>#~StringReplace~{"("->"[1+",")"->"-1]"}]&
Input a string.
TI-Basic, 69 bytes
Input Str1
expr("{"+sub(Str1,2,length(Str1)-2
prod(randIntNoRep(min(Ans)+(sub(Str1,1,1)="("),max(Ans)-(sub(Str1,length(Str1),1)=")
Output is stored in Ans and displayed. Replace randIntNoRep( with seq(I,I, (+3 bytes) if the calculator does not support it.
Julia 0.4, 64 bytes
s->prod((x=parse(s[2:end-1]).args)[]+(s[1]<41):x[2]-(s[end]<42))
Based on Alex A's answer
Julia 1.0, 69 bytes
s->prod((:)(Meta.parse(s[2:end-1]).args+[s[1]<'*',-(s[end]<'*')]...))
Julia 0.4, 75 bytes
s->prod((x=map(parse,split(s[2:end-1],",")))[1]+(s[1]<41):x[2]-(s[end]<42))
This is an anonymous function that accepts a string and returns an integer. To call it, give it a name, e.g. 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
JavaScript (ES6), 68 bytes
s=>(f=_=>a>b||a++*f())([a,b,c]=s.match(/-?\d+|]/g),a-=-(s<'['),b-=!c)
Haskell, 94 bytes
f=(\(h:a,_:b)->product[a!h..init b!last b]).span(','/=);c!')'=c!' '-1;c!'('=c!' '+1;c!_=read c
JavaScript (ES6), 79
As an anonymous method
r=>eval("[a,b,e]=r.match(/-?\\d+|.$/g);c=a-=-(r<'@');for(b-=e<'@';a++<b;)c*=a")
Test snippet
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>
Seriously, 31 bytes
,#d@p@',@s`εj≈`Mi(@)']=+)'(=+xπ
Takes input as a string (wrapped in double quotes)
Try it online (input must be manually entered)
Explanation:
,#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
Minecraft 15w35a+, program size 638 total (see below)
Same as my answer here, but modified. Since Minecraft has no string input, I took the liberty of keeping scoreboard input. If that is a problem, consider this answer non-competitive.
This calculates PI a,b with inclusive / exclusive specified by the two levers.
Input is given by using these two commands: /scoreboard players set A A {num} and /scoreboard players set B A {num}. Remember to use /scoreboard objectives add A dummy before input.
Scored using: {program size} + ( 2 * {input command} ) + {scoreboard command} = 538 + ( 2 * 33 ) + 34 = 638.
This code corresponds to the following 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
Download the world here.
Ruby, 79 77 bytes
->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*}
79 bytes
->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,:*
}
Usage:
->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*}["(2,5]"]
=> 60
R, 102 104 bytes
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])
}
edit to allow negative numbers [at the expense of 2 more characters
Pyth, 20 bytes
*FPW}\)ztW}\(z}FvtPz
Try it online: Demonstration or Test Suite
Explanation:
*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
JavaScript (ES6), 90 bytes
s=>eval(`for(n=s.match(/-*\\d+/g),i=n[0],c=s[0]<"["||i;++i<+n[1]+(s.slice(-1)>")");)c*=i`)
Explanation
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
var solution = s=>eval(`for(n=s.match(/-*\\d+/g),i=n[0],c=s[0]<"["||i;++i<+n[1]+(s.slice(-1)>")");)c*=i`)
<input type="text" id="input" value="(5,10]" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
Python 2, 72 bytes
lambda s:reduce(int.__mul__,range(*eval(s[1:-1]+'+'+`']'in s`))[s<'[':])
To extract the numbers we evaluate s[1:-1], the input string with ends removed, which gives a tuple. The idea is to get the range of this tuple and take the product.
lambda s:reduce(int.__mul__,range(*eval(s[1:-1]))
The fudging happens to adjust the endpoints. The upper endpoint is easy, just cut off the first element if the input starts with (, done as [s<'[':].
The other endpoint is trickier. Python doesn't have a clean way to conditionally remove the last element of a list because l[:0] removes the whole thing. So, we do something weird. We modify the tuple string before it is evaluated to tack on the string "+True" or "+False" depending on whether s ends in ] or ). The result is that something like 3,7 becomes either 3,7+False which is 3,7, or 3,7+True which is 3,8.
Alternate, prettier 72:
lambda s:eval("reduce(int.__mul__,range((s<'[')+%s+(']'in s)))"%s[1:-1])
CJam, 34 bytes
r)\(@+"[()]"2/\.#\',/:i.+~1$-,f+:*
Explanation:
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.
Mathematica, 128 bytes
1##&@@Range[(t=ToExpression)[""<>Rest@#]+Boole[#[[1]]=="("],t[""<>Most@#2]-Boole[Last@#2==")"]]&@@Characters/@#~StringSplit~","&
This is too long... Currently thinking about a StringReplace + RegularExpression solution.
Perl 6, 60 bytes
{s/\((\-?\d+)/[$0^/;s/(\-?\d+)\)/^$0]/;s/\,/../;[*] EVAL $_}
There is a bit of mis-match because the way you would write the (2,5] example in Perl 6 would be 2^..5 ([2^..5] also works).
So I have to swap (2 with [2^, and , with .., then I have to EVAL it into a Range.
usage:
# 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
PowerShell, 146 104 Bytes
param($i)$a,$b=$i.trim("[]()")-split',';($a,(1+$a))[$i[0]-eq'(']..($b,(+$b-1))[$i[-1]-eq')']-join'*'|iex
Golfed off 42 bytes by changing how the numbers are extracted from the input. Woo!
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)
MATLAB, 86 70 bytes
s=sscanf(input(''),'%c%d,%d%c');a=s<42;disp(prod(a(1)+s(2):s(3)-a(4)))
This also works with Octave. You can try online here. I have added the code as a script to that workspace, so you can just enter productRange at the prompt, then enter your input, e.g. '(2,5]'.
So the code first scans the input to extract the brackets and the numbers together:
s=sscanf(input(''),'%c%d,%d%c');
This returns an array which is made of [bracket, number, number, bracket].
The array is compared with 42, actually any number between 42 and 90 inclusive will do. This determines which sort of bracket it was, giving a 1 if it is an exclusive bracket, and a 0 if an inclusive bracket.
a=s<42;
Finally, we display the product of the required range:
disp(prod(a(1)+s(2):s(3)-a(4)))
The product is of numbers staring with the first number s(2) plus the first bracket type a(1) (which is a 1 if an exclusive bracket), ranging up to and including the second number s(3) minus the second bracket type a(4). This gives the correct inclusive/exclusive range.
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)
Takes input from stdin.
LabVIEW, 38 LabVIEW Primitives
"slightly" modified, now sets the ranges by scanning for () and [] and adding the index to the numbers.


