| Bytes | Lang | Time | Link |
|---|---|---|---|
| 020 | Uiua | 250811T131238Z | nyxbird |
| 099 | APLNARS | 250811T095249Z | Rosario |
| 065 | x8616 + 8087 FPU | 190107T235839Z | 640KB |
| 042 | K ngn/k | 211216T214458Z | coltim |
| 135 | C gcc | 211215T202322Z | Benji |
| 088 | TSQL | 160613T080759Z | t-clause |
| 016 | Japt | 190110T173812Z | Kamil Dr |
| nan | PHP | 190107T190643Z | 640KB |
| nan | 160625T091607Z | Titus | |
| 027 | APL Dyalog Unicode | 160614T075610Z | Adá |
| 090 | x8664 machine code Linux | 190110T051859Z | davey |
| 064 | Runic Enchantments | 190108T211153Z | Draco18s |
| 130 | C# .NET Core | 190107T220825Z | Destroig |
| 015 | 05AB1E | 190107T192413Z | Emigna |
| 027 | 05AB1E | 181023T140852Z | Kevin Cr |
| 070 | R | 180719T154628Z | JayCe |
| 081 | shell script | 180719T185413Z | Bastian |
| 057 | Ruby | 180407T090641Z | Kirill L |
| 113 | Java 8 | 160613T080806Z | Kevin Cr |
| 127 | Emacs Lisp | 160619T215327Z | Lord Yuu |
| 197 | PHP | 160617T044912Z | Develope |
| 202 | c# | 160616T073248Z | Develope |
| 081 | Matlab 85 bytes / Octave | 160614T091517Z | LimaKilo |
| 254 | Oracle PL/SQL | 160613T095447Z | Giacomo |
| 062 | Haskell | 160613T092212Z | flawr |
| 018 | CJam | 160614T010217Z | Dennis |
| 093 | Python 3 | 160613T170327Z | MSeifert |
| 062 | Perl 6 | 160613T202513Z | Brad Gil |
| 117 | Rust | 160613T165742Z | raggy |
| 061 | Haskell | 160613T181849Z | Lazersmo |
| 064 | Python 2 | 160613T164347Z | Dennis |
| 050 | Julia | 160613T160514Z | Dennis |
| 013 | Jelly | 160613T153519Z | Dennis |
| 065 | Mathematica | 160613T104915Z | LegionMa |
| 124 | PowerShell v2+ | 160613T134625Z | AdmBorkB |
| 023 | Actually | 160613T090851Z | user4594 |
| 040 | J | 160613T085040Z | miles |
| 074 | Haskell | 160613T091253Z | C. Quill |
| 021 | Pyke | 160613T080524Z | Blue |
| 025 | Pyth | 160613T070905Z | Leaky Nu |
| 049 | Javascript ES7 | 160613T071124Z | Bál |
| 068 | Brachylog | 160613T080539Z | Fatalize |
Uiua, 20 bytes
∧⨬(+|-|×|÷|ⁿ)◿5°⊏°˜⊂
°˜⊂ # seperate head
◿5°⊏ # get indices modulo 5
∧ # fold over tail with head using:
⨬(+|-|×|÷|ⁿ) # the indices' corresponding functions
APL(NARS), 99 chars
r←f w;l;i
r←⍬⋄i←1⋄b←(+,-,×,÷,*)⋄→0×⍳∼0<l←≢w⋄→0×⍳(,1)≢⍴⍴w⋄r←w[i]
→0×⍳l<i+←1⋄r←r((1+5∣i-2)⊃b)w[i]⋄→2
//10+54+35
It appear that →0×⍳∼0<l←≢w can not handle the case w is not a list,
that would be handle from →0×⍳(,1)≢⍴⍴w or →0×⍳(,1)≠⍴⍴w.
The traditional way of write functions in APL offer many workaroud in problems of array language.
f 1 2 3 4 5
0
f 5 12 23 2 4 4 2 6 7
539
f ¯8 50 3 3 ¯123 4 17 99 13
¯1055.356944
f 16⍴2
256
f 1 0 1 0 1 0
1
f ¯9 ¯8 ¯1
¯16
f 0 ¯3
¯3
f ¯99
f ,¯99
¯99
x86-16 + 8087 FPU, 65 bytes
00000000: 9bdf 04ad 499b de04 ad49 e334 9bde 24ad ....I....I.4..$.
00000010: 49e3 2d9b de0c ad49 e326 9bde 34ad 49e3 I.-....I.&..4.I.
00000020: 1fad 919b d9e8 85c9 7413 9c7f 02f7 d99b ........t.......
00000030: d8c9 e2fb 9d7d 069b d9e8 9bd8 f191 e2c5 .....}..........
00000040: c3 .
Callable function: input array at DS:SI, length in CX. Output to ST top 8087 register stack.
Listing:
9B DF 04 FILD WORD PTR [SI] ; load first item to 8087 stack
AD LODSW
49 DEC CX
CALC:
; Add
9B DE 04 FIADD WORD PTR [SI] ; add
AD LODSW ; SI = next input
49 DEC CX ; decrement counter
E3 34 JCXZ WOMI_DONE ; exit if end of input array
; Subtract
9B DE 24 FISUB WORD PTR [SI] ; subtract
AD LODSW ; SI = next input
49 DEC CX
E3 2D JCXZ WOMI_DONE
; Multiply
9B DE 0C FIMUL WORD PTR [SI] ; multiply
AD LODSW ; SI = next input
49 DEC CX
E3 26 JCXZ WOMI_DONE
; Divide
9B DE 34 FIDIV WORD PTR [SI] ; divide
AD LODSW ; SI = next input
49 DEC CX
E3 1F JCXZ WOMI_DONE
; Exponent
AD LODSW ; AX = exponent, SI = next input
91 XCHG AX, CX ; CX = counter for loop (exponent), save CX
9B D9 E8 FLD1 ; load 1 into ST
85 C9 TEST CX, CX ; is exponent pos, neg or 0?
74 13 JZ EXP_DONE ; exit (with value 1) if exponent is 0
9C PUSHF ; save result flags for later
7F 02 JG EXP_REP ; if exp > 1 start calculation
F7 D9 NEG CX ; make exponent positive for loop
EXP_REP:
9B D8 C9 FMUL ST(0), ST(1) ; multiply ST0 = ST0 * ST1
E2 FB LOOP EXP_REP
9D POPF ; restore sign flag from earlier
7D 06 JGE EXP_DONE ; if exponent was neg, divide 1 by result
9B D9 E8 FLD1 ; push 1 into numerator
9B D8 F1 FDIV ST(0), ST(1) ; ST0 = 1 / ST1
EXP_DONE:
91 XCHG AX, CX ; restore CX
E2 C5 LOOP CALC ; if more input, start again
WOMI_DONE:
C3 RET
Sample Output:
K (ngn/k), 42 bytes
{*x{?[x;0 2;y/]}/(#1_x)#(+;-;*;%;{*/y#x})}
Sets up a reduce with the original input as x, and a corresponding list of operations to apply.
(+;-;*;%;{*/y#x})initialize a list of the desired operations to apply, using{*/y#x}for pow (only works for raising values to integer powers)(#1_x)#..."overtake" this list, expanding it to match the length of the inputxminus one (as the operations are applied between elements ofx)x{...}/...set up the reduce, seeded with the original input and run over the list of operations to apply?[x;0 2;y/]use?[x;i;f] spliceto apply the operation between the first two elements of the input, replacing those values with the result of applying the operation (y) between them
C (gcc), 135 bytes
#include<math.h>
float r(float*a,int l){float z,v=*a;for(int p=1;p<l;v=(float[]){z?pow(v,z):1,v+z,v-z,v*z,v/z}[p++%5])z=a[p];return v;}
TSQL 116 115 88 bytes
Thanks to Ross Presser suggestion I was able to golf this down to 88 characters
-- In Try-it code, this must be DECLARE @y TABLE
CREATE TABLE T(a real, i int identity)
INSERT T values(5),(12),(23),(2),(4),(4),(2),(6),(7)
DECLARE @ REAL SELECT @=CHOOSE(i%5+1,@/a,ISNULL(POWER(@,a),a),@+a,@-a,@*a)FROM T
PRINT @
Japt, 16 bytes
r@[XY]r"p+-*/"gZ
Explanation:
r@ #Reduce the input list:
"p+-*/" # The list of functions to apply (offset by one due to the behavior of Z)
gZ # Choose the one at the current index, wrapping
[ ]r # Apply that function to:
X # The result of the previous step
Y # and the current number
#Implicitly return the result of the final step
PHP, 135 130 bytes
Thanks @titus, -5 bytes, plus 0 case fix!
function f($z){return array_reduce($z,function($c,$x)use(&$i){eval('$c'.['/','**','+','-','*'][$i++?$i%5:5].'=$x;');return$c;});};
Less golfy:
function f( $t ) {
return array_reduce( $t,
function( $c, $x ) use( &$i ) {
eval('$c'.['/','**','+','-','*'][$i++?$i%5:5].'=$x;');
return $c;
}
);
};
Was really rooting for array_reduce() to work for this, but requires too many chars to beat the current lowest PHP score.
Posting it anyway in case anyone has any suggestions!
A few tricks can reduce @Willmore´s approach by 23 to 174 bytes (requires php 5.6 or later). The most saving part is removing unneccessary parentheses (-10 bytes).
function f($a){while(count($a)>1){$l=array_shift($a);$r=array_shift($a);array_unshift($a,($j=$i++%5)?($j==1?$l-$r:($j==2?$l*$r:($j==3?$l/$r:$l**$r))):$l+$r);}return end($a);}
But using the ** operator instead of pow() also allows to use eval with an array for the operations; and with a few more tricks ...
PHP >= 5.6, 82 bytes
while(--$argc)eval('$x'.['/','**','+','-','*'][$i++?$i%5:2]."=$argv[$i];");echo$x;
takes list from command line parameters. Run with php -nr '<code>' or try it online.
old version, 161 157 151 145 144 140 137 117 bytes
function f($a){while(count($a)>1)eval('$a[0]=array_shift($a)'.['+','-','*','/','**'][$i++%5].'$a[0];');return$a[0];}
The most effective golfing came from writing the intermediate result directly to the first element - after shifting the previous result from the array.
breakdown
function f($a)
{
while(count($a)>1) // while array has more than one element ...
eval('$a[0]=' // future first element :=
. 'array_shift($a)' // = old first element (removed)
. ['+','-','*','/','**'][$i++%5] // (operation)
.'$a[0];' // new first element (after shift)
);
return$a[0]; // return last remaining element
}
test suite
$cases = array (
0=>[1,2,3,4,5],
539=>[5,12,23,2,4,4,2,6,7],
'-1055.356...' => [-8,50,3,3,-123,4,17,99,13],
256 => [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
1 => [1,0,1,0,1,0],
-16 => [-9,-8,-1],
-3 => [0, -3],
-99 => [-99]
);
echo '<table border=1><tr><th>values</th><th>expected</th><th>actual result</th></tr>';
foreach ($cases as $expect=>$a)
{
$result=f($a);
echo "<tr><td>[", implode(',',$a),"]</td><td>$expect</td><td>$result</td></tr>";
}
echo '</table>';
APL (Dyalog Unicode), 29 27 bytesSBCS
Anomymous tacit prefix function. Note that * is exponentiation in APL.
≢{⍎3↓⍕⌽⍵,¨⍨⍺⍴'+-×÷*',¨'⍨'}⊢
Because APL executes right to left, we can just reverse the order of arguments of the inserted operations and reverse the entire expression. Postfix ⍨ reverses arguments. After doing a perfect shuffle of numbers and operations, we only just need to reverse, flatten, and evaluate:
≢{…}⊢ call the following function with count of and actual numbers as ⍺ and ⍵:
'⍨' this character
'+-×÷*',¨ prepend each of these characters to that; ["+⍨","-⍨","×⍨","÷⍨","*⍨"]
⍺⍴ use the left argument (count of numbers) to cyclically reshape that
⌽ reverse
⍕ format as flat string
3↓ drop leading 3 characters (a space and a symbol and ⍨)
⍎ execute as APL code
x86-64 machine code (Linux), 90 bytes
0000000000000000 <weapons_asm>:
0: 48 89 f1 mov %rsi,%rcx
3: db 07 fildl (%rdi)
0000000000000005 <math_loop>:
5: 48 83 c7 04 add $0x4,%rdi
9: 48 ff c9 dec %rcx
c: e3 49 jrcxz 57 <done>
e: da 07 fiaddl (%rdi)
10: 48 83 c7 04 add $0x4,%rdi
14: 48 ff c9 dec %rcx
17: e3 3e jrcxz 57 <done>
19: da 27 fisubl (%rdi)
1b: 48 83 c7 04 add $0x4,%rdi
1f: 48 ff c9 dec %rcx
22: e3 33 jrcxz 57 <done>
24: da 0f fimull (%rdi)
26: 48 83 c7 04 add $0x4,%rdi
2a: 48 ff c9 dec %rcx
2d: e3 28 jrcxz 57 <done>
2f: da 37 fidivl (%rdi)
31: 48 83 c7 04 add $0x4,%rdi
35: 48 ff c9 dec %rcx
38: e3 1d jrcxz 57 <done>
000000000000003a <exp_rept>:
3a: 51 push %rcx
3b: 8b 0f mov (%rdi),%ecx
3d: d9 e8 fld1
3f: 83 f9 00 cmp $0x0,%ecx
42: 74 10 je 54 <exp_rept.done>
44: 9c pushfq
45: 7f 02 jg 49 <exp_rept.l>
47: f7 d9 neg %ecx
0000000000000049 <exp_rept.l>:
49: d8 c9 fmul %st(1),%st
4b: e2 fc loop 49 <exp_rept.l>
4d: 9d popfq
4e: 7d 04 jge 54 <exp_rept.done>
50: d9 e8 fld1
52: de f9 fdivrp %st,%st(1)
0000000000000054 <exp_rept.done>:
54: 59 pop %rcx
55: eb ae jmp 5 <math_loop>
0000000000000057 <done>:
57: dd 1a fstpl (%rdx)
59: c3
Firstly, credit to gwaugh's answer which is also submitted for this post. I started working on this solution before gwaugh posted, which can be seen in my git repo's log, but ultimately his approach to this problem was the most efficient (especially the exponentiation). If you feel inclined to upvote my submission, please check out his as well.
Like my other x86 solutions, this code is simply a function that's meant to be called from a C/C++ program, which can be seen at my git repo. This means that the input array, length, and return pointer are passed through rdi, rsi, and rdx. For x86-64, getting the output location as an argument saves bytes, because normally when a C/C++ function returns a double on this processor, it's passed back through xmm0. This means the result double has to be moved from the FPU stack to a place in memory, then moved into xmm0. If we specify a place in memory we want the result, then we can just move the result double directly from the FPU stack to the memory location.
Exponentiation is done through repeated multiplication, with the assumption that we'll only get integer exponents (though the exponent can be negative). If the problem requires handling floating point exponentiation, the solution becomes extremely complicated. The standard way to compute x^y on x86 is to compute 2^(y * log2(x)). However, if x is negative (which happens in test case 2), log2(x) is a complex number, which can't be directly handled by the FPU. If you're curious how pow(double x, double y) is solved in C, check out the glibc code here (hint: it's complicated).
Runic Enchantments, 64 bytes
R31B~~?@+31B~~?@S-31B~~?@*31B~~?@S,31B~~?@Sp
\i<{1[lil1-{S{)]{{B
First line is the main program loop, which reads a number from input and performs the next math instruction. If no input, the attack is dumped to the output and the program terminates. Entry point is the < on the second line, which reads the first number from input prior to entering the main loop. Invalid input blindly accepted with unpredictable results (only + and * are defined for strings, other operations would result in an empty stack).
Woo, finally found a use for Branch command! The second line starting at index 3 acts like a function. In this case it takes in input, checks that it got input, and arranges the stack for return. Then 31B~~ invokes and cleans up after the invokation (as the Branch instruction leaves 2 values on top of the stack, add a return pointer). All told the overhead (8+5n) was less than in-line (9n). I think I'll be adding a modifier that cause B to not push those 2 values (overhead of 2 bytes to save 2n bytes). Happily, no directional commands are needed to insure consistent execution.
Also featured is the [ and ] stack-of-stacks commands, which lets the program temporarily remove the return location from the stack as it handles reading input. It saves several bytes worth of stack manipulation having to otherwise work around those 2 values. These do enforce a maximum input list of 9 values. Changing the entry to y<< increases that to 19 items (and as < acts like a NOP, the branch pointer doesn't need to update). A third line with \y<< (changing the existing \ to U) would double that again to 39 items.
Stack at the end of the Branch "function" would look like [v,i,1,x,y] where x,y are at the top and the 0-indexed location on the first line (y will always be 0) where the next instruction with execute. v is the value that started on the stack prior to entry into the Branch "function". And i is the value read from input. If no input was available, [i,1] would instead be [0] resulting in v being printed when ?@ is reached.
C# (.NET Core), 130 bytes
Without LINQ.
s=>{var x=s[0];for(var j=1;j<s.Length;j++){int t=j%5;var z=s[j];x=t<1?x=Math.Pow(x,z):t<2?x+=z:t<3?x-=z:t<4?x*=z:x/=z;}return x;};
05AB1E, 15 bytes
ćsvy"+-*/m"Nè.V
Try it online! or as a Test Suite
Explanation
ć # extract the head of the input list
sv # for each (value y, index N) in the rest of the list
y # push the element
"+-*/m"Nè # push a string representation of the Nth operator (wraps around)
.V # execute it as code
05AB1E, 29 28 27 bytes
Using 'Python eval' builtin (29 28 27 bytes):
g'(×svy')"+-*/"S„**ªNè}\J.E
Try it online or verify all test cases. (NOTE: ª is ¸« and we use the legacy version in the TIO, because .E is disabled in the new version of 05AB1E on TIO.)
Using 'Execute as 05AB1E' builtin (29 28 bytes):
vyD0‹i¦'(}N_iðë"m+-*/"Nè]J.V
Try it online or verify all test cases.
Explanation:
In Python ** is used for exponentiation. In addition, *,/,** have operator precedence over +,-. So the code transforms [-1,2,-3,4,-5] to (((((-1)+2)--3)*4)**-5), and then uses .E to execute the string as Python eval.
g # Take the length of the (implicit) input
'(× '# Create a string of "(" characters of that size
s # Swap so the (implicit) input is at the top of the stack again
v } # Loop `y` of each of its items:
y # Push `y`
') '# Push ")"
"+-*/"S # Push ["+","-","*","/"]
„**ª # Append a trailing "**": ["+","-","*","/","**"]
Nè # Get a string from this list based on the index of the loop
# (with automatic wraparound)
\ # Discard the trailing operand from the stack
J # Join all strings on the stack together
.E # Execute as Python eval (and output implicitly)
In 05AB1E negative values are with a trailing ( instead of leading -, and m is used for exponentiation. In addition, a Polish notation is used. So the program transforms [-1,2,-3,4,-5] to 1( 2+3-4*5(m, and then uses .V to execute the string as 05AB1E code.
v # Loop `y` of each of its items:
y # Push `y`
D0‹i } # If `y` is negative:
¦ # Remove the first character (the minus sign)
'( '# And push a "("
N_i # If the index of the loop is 0:
ð # Push a space character
ë # Else:
"m+-*/"Nè # Push a character from "m+-*/" based on the index of the loop
# (with automatic wraparound)
] # Close both the if-else and loop
J # Join all strings on the stack together
.V # Execute as 05AB1E code (and output implicitly)
R, 87 78 70 bytes
i=0
Reduce(function(a,j)get(substr("+-*/^",i<<-i%%5+1,i))(a,j),scan())
shell script, 157 135 133 130 124 99 95 88 85 81 bytes
golfed (bash/non-posix) - 81 bytes
f()(A=$1;S=+-*/^;shift;for B;{ C=${S:((I++%5)):1};A=`bc -l<<<$A$C$B`;};echo $A)
golfed (portable/posix, using 'cut'-operator) - 118 bytes
f()(S=+-x/^;A=$1;shift;for B;do C=`echo $S|cut -b1`;S=`echo $S|cut -b2-5`;S="$S$C";A=`echo $A$C$B|bc -l`;done;echo $A)
golfed (portable/posix, with builtins) - 124 bytes
f()(A=$1;shift;for B;do case $I in 1)C=-;;2)C=*;;3)C=/;;4)C=^;;*)C=+;I=;;esac;I=$((I+1));A=`echo $A$C$B|bc -l`;done;echo $A)
ungolfed (posix - with builtins):
A=$1
shift
for B;do
case $I in
1)C=-;;
2)C=*;;
3)C=/;;
4)C=^;;
*)C=+;I=
esac
I=$((I+1))
A=`echo $A$C$B|bc -l`
done
echo $A
ungolfed (posix - with 'cut'):
S=+-x/^
A=$1
shift
for B;do
C=`echo $S|cut -b1`
S=`echo $S|cut -b2-5`
S="$S$C"
A=`echo $A$C$B|bc -l`
done
echo $A
This is unfair!
We don't have real division in language 'sh',
so we must use 'bc' which is...lame 8-)
hint: your directory must have no files, otherwise the asterisk expands to filenames (◔_◔)
Tests:
# f 1 2 3 4 5
0
# f 5 12 23 2 4 4 2 6 7
539
# f -8 50 3 3 -123 4 17 99 13
-1055.35
# f 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
256.00
# f 1 0 1 0 1 0
1
# f -9 -8 -1
-16
# f 0 -3
-3
# f -99
-99
Ruby, 57 bytes
->a{i=0;a.reduce{|x,y|x.send %w[** + - * /][(i+=1)%5],y}}
Takes an array of floats, but also works with integers, as long as all division results are integer.
At first, I tried fiddling with eval which looks like the obvious approach, but it gets rather verbose. Instead, I opted for send, which is basically Ruby's way to call methods by names, so that x.send("+",y) is equivalent to x+y.
Java 8, 173 172 167 138 137 118 113 bytes
a->{double r=a[0],t;for(int i=1;i<a.length;r=new double[]{Math.pow(r,t),r+t,r-t,r*t,r/t}[i++%5])t=a[i];return r;}
Explanation:
a->{ // Method with double-array parameter and double return-type
double r=a[0], // Result-double, starting at the first item of the input
t; // Temp double
for(int i=1; // Index-integer, starting at the second item
i<a.length; // Loop over the input-array
r=new double[]{ // After every iteration, change `r` to:
Math.pow(r,t), // If `i%5` is 0: `r^t`
r+t, // Else-if `i%5` is 1: `r+t`
r-t, // Else-if `i%5` is 2: `r-t`
r*t, // Else-if `i%5` is 3: `r*t`
r/t}[i++%5]) // Else-if `i%5` is 4: `r/t`
// And increase `i` by 1 afterwards with `i++`
t=a[i]; // Change `t` to the next item in the array
return r;} // Return result-double
Emacs Lisp, 127 bytes
(lambda(x)(let((f'(+ - * / expt))(a(float(car x)))(x(cdr x)))(dotimes(i(length x)a)(set'a(funcall(nth(mod i 5)f)a(nth i x))))))
Ungolfed:
(lambda(x)
(let ((f'(+ - * / expt)) ; list of functions in order they are called
(a (float (car x))) ; initial value
(x (cdr x))) ;
(dotimes (i (length x) a)
(set 'a (funcall (nth (mod i 5) f) ; call the i % 5th function
a ; with accumulator
(nth i x)))))) ; and the ith value
Testcases:
(-map
(lambda(x)(let((f'(+ - * / expt))(a(float(car x)))(x(cdr x)))(dotimes(i(length x)a)(set'a(funcall(nth(mod i 5)f)a(nth i x))))))
'((1 2 3 4 5)
(5 12 23 2 4 4 2 6 7)
(-8 50 3 3 -123 4 17 99 13)
(2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2)
(1 0 1 0 1 0)
(-9 -8 -1)
(0 -3)
(-99)))
Output:
(0.0 539.0 -1055.356943846277 256.0 1.0 -16.0 -3.0 -99.0)
PHP, 206,198,197 bytes
function f($a){while(count($a)>1){$l=array_shift($a);$r=array_shift($a);array_unshift($a,($j=$i++%5)==0?($l+$r):($j==1?($l-$r):($j==2?($l*$r):($j==3?($l/$r):(pow($l,$r))))));}return array_pop($a);}
Ungolfed
<?php
function f($a)
{
while(count($a)>1)
{
$l = array_shift($a); $r = array_shift($a);
array_unshift($a,($j=$i++%5)==0?($l+$r):($j==1?($l-$r):($j==2?($l*$r):($j==3?($l/$r):(pow($l,$r))))));
}
return array_pop($a);
}
echo f([1,2,3,4,5])."\n";
echo f([5,12,23,2,4,4,2,6,7])."\n";
echo f([-8,50,3,3,-123,4,17,99,13])."\n";
echo f([2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2])."\n";
echo f([1,0,1,0,1,0])."\n";
echo f([-9,-8,-1])."\n";
echo f([0,-3])."\n";
echo f([-99])."\n";
In PHP, logic similar to my c# answer (202 bytes) :) .
c#, 238, 202 bytes
double d(double[]a){Array.Reverse(a);var s=new Stack<double>(a);int i=0,j;while(s.Count>1){double l=s.Pop(),r=s.Pop();j=i++%5;s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l,r));}return s.Peek();}
I didn't see any c# solution so I will give one. This is my first codegolf. I started writing in c# "two months ago" (though I know Java to some extent).
It uses Stack
Ungolfed and test cases
using System;
using System.Collections.Generic;
class M
{
double d(double[]a) {
Array.Reverse(a);
var s = new Stack<double>(a);
int i=0,j;
while (s.Count>1)
{
double l=s.Pop(),r=s.Pop();
j=i++%5;
s.Push(j==0?l+r:j==1?l-r:j==2?l*r:j==3?l/r:Math.Pow(l, r));
}
return s.Peek();
}
public static void Main()
{
int[][] a = new int[][]{
new int[]{1,2,3,4,5},
new int[]{5,12,23,2,4,4,2,6,7},
new int[]{-8,50,3,3,-123,4,17,99,13},
new int[]{2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2},
new int[]{1,0,1,0,1,0},
new int[]{-9,-8,-1},
new int[]{0,-3},
new int[]{-99}
};
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(new M().d(Array.ConvertAll(a[i], e => Convert.ToDouble(e))));
}
Console.ReadKey();
}
}
Output:
0
539
-1055,35694384628
256
1
-16
-3
-99
Matlab - 95 91 85 bytes / Octave - 81 bytes
Input is in such form: a = ['1' '2' '3' '4' '5'];, I hope this is covered by "string representing an array with integers/decimals", else there are 2 num2str needed additionally.
Every intermediate result gets printed to console because that saves me some semicolons. a(1) is executed so its value is then saved to ans. Also of course using ans in code is bad practice.
b='+-*/^'
a(1)
for i=2:length(a)
['(',ans,')',b(mod(i-2,5)+1),a(i)]
end
eval(ans)
In Octave, '+-*/^'(mod(i+2,5)+1) also works, which saves another 4 bytes, thanks Adám and Luis Mendo:
a(1)
for i=2:length(a)
strcat('(',ans,')','+-*/^'(mod(i-2,5)+1),a(i))
end
eval(ans)
Changelog:
- Removed spaces where possible
- added Octave solution
- replaced strcat() with []
Oracle PL/SQL, 275 254 Bytes
declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;
The data must be inserted in a table called T with a column N of type NUMBER
Usage:
drop table t;
create table t (n number);
insert into t values (-8);
insert into t values (50);
insert into t values (3);
insert into t values (3);
insert into t values (-123);
insert into t values (4);
insert into t values (17);
insert into t values (99);
insert into t values (13);
declare r number;begin for x in (select n,mod(rownum,5)r from t) loop if r is null then r:=x.n;elsif x.r=2then r:=r+x.n;elsif x.r=3then r:=r-x.n;elsif x.r=4then r:=r*x.n;elsif x.r=0then r:=r/x.n;else r:=r**x.n;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;
Output:
-1055,356943846277162152071601242992595623
275 Bytes version:
declare r number;cursor c is select n,mod(rownum,5) r from t;begin for x in c loop if r is null then r:=x.n;else case x.r when 2 then r:=r+x.n;when 3 then r:=r-x.n;when 4 then r:=r*x.n;when 0 then r:=r/x.n;else r:=r**x.n; end case;end if;end loop;DBMS_OUTPUT.PUT_LINE(r);end;
Haskell, 76 65 64 62 bytes
Thanks to @Damien for removing another two bytes=)
f(u:v)=foldl(\x(f,y)->f x y)u(zip(v>>[(+),(-),(*),(/),(**)])v)
This uses the >> which here just appends the list [(+),...] to itself length v times. The rest still works still the same as the old versions.
Old versions:
These solutions make use of the infinite lists, as cycle[...] just repeats the given list infinitely. Then it basically gets ziped with the list of numbers, and we just fold (reduce in other languages) the zipped list via a lambda, that applies the operators to the accumulator/current list element.
f(u:v)=foldl(\x(f,y)->f x y)u(zip(cycle[(+),(-),(*),(/),(**)])v)
f(u:v)=foldl(\x(y,f)->f x y)u(zip v(cycle[(+),(-),(*),(/),(**)]))
f l=foldl(\x(y,f)->f x y)(head l)(zip(drop 1l)(cycle[(+),(-),(*),(/),(**)]))
CJam, 18 bytes
q~{"+-*/#"W):W=~}*
Input is an array of floats. Try it online!
How it works
q~ Read and evaluate all input.
{ }* Reduce:
"+-*/#" Push the string of operators.
W Push W (initially -1).
):W Increment and save in W.
= Retrieve the character at that index.
~ Evaluate.
Python 3, 88 93 bytes
f=lambda x:eval('('*(len(x)-1)+'){}'.join(map(str,x)).format(*['+','-','*','/','**']*len(x)))
It started off being much shorter but then operator precedence defeated me and I had to include lots of parenthesis...
Perl 6, 70 68 65 62 bytes
{$/=[(|(&[+],&[-],&[*],&[/],&[**])xx*)];.reduce: {$/.shift.($^a,$^b)}}
{(@_ Z |(&[+],&[-],&[*],&[/],&[**])xx*).flat.reduce: {&^b($^a,$^c)}}
{(@_ Z |(*+*,*-*,&[*],*/*,&[**])xx*).flat.reduce: {&^b($^a,$^c)}}
{reduce {&^b($^a,$^c)},flat @_ Z |(*+*,*-*,&[*],*/*,&[**])xx*}
Explanation:
-> *@_ {
reduce
-> $a, &b, $c { b($a,$c) },
flat # flatten list produced from zip
zip
@_, # input
slip( # causes the list of operators to flatten into the xx list
# list of 5 infix operators
&infix:<+>, &infix:<->, &infix:<*>, &infix:</>, &infix:<**>
) xx * # repeat the list of operators infinitely
}
Technically * + * is a Whatever lambda, but is effectively the same as &[+] which is short for &infix:<+> the set of subroutines that handle infix numeric addition.
I didn't use that for multiplication or exponentiation as the ways to write them like that is at least as long as what I have (*×* or * * * and * ** *)
Test:
Test it on ideone.com
(after they upgrade to a Rakudo version that isn't from a year and a half before the official release of the Perl 6 spectests)
#! /usr/bin/env perl6
use v6.c;
use Test;
my @tests = (
[1,2,3,4,5] => 0,
[5,12,23,2,4,4,2,6,7] => 539,
[-8,50,3,3,-123,4,17,99,13] => -1055.35694385, # -2982186493/2825761
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] => 256,
[1,0,1,0,1,0] => 1,
[-9,-8,-1] => -16,
[0,-3] => -3,
[-99] => -99,
);
plan +@tests;
my &code = {reduce {&^b($^a,$^c)},flat @_ Z |(*+*,*-*,&[*],&[/],&[**])xx*}
for @tests -> $_ ( :key(@input), :value($expected) ) {
is code(@input), $expected, .gist
}
1..8
ok 1 - [1 2 3 4 5] => 0
ok 2 - [5 12 23 2 4 4 2 6 7] => 539
ok 3 - [-8 50 3 3 -123 4 17 99 13] => -1055.35694385
ok 4 - [2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2] => 256
ok 5 - [1 0 1 0 1 0] => 1
ok 6 - [-9 -8 -1] => -16
ok 7 - [0 -3] => -3
ok 8 - [-99] => -99
Rust, 123, 117 bytes
Original answer:
fn a(v:&[f32])->f32{v.iter().skip(1).enumerate().fold(v[0],|s,(i,&x)|match i%5{0=>s+x,1=>s-x,2=>s*x,3=>s/x,_=>s.powf(x)})}
stupid long method names ^^ ahh much better
fn f(v:&[f32])->f32{v[1..].iter().zip(0..).fold(v[0],|s,(&x,i)|match i%5{0=>s+x,1=>s-x,2=>s*x,3=>s/x,_=>s.powf(x)})}
ungolfed
fn f(values : &[f32]) -> f32 {
values[1..].iter().zip(0..)
.fold(values[0], |state,(&x,i)|
match i%5 {
0=>state+x,
1=>state-x,
2=>state*x,
3=>state/x,
_=>state.powf(x)
}
)
}
Haskell, 61 Bytes
foldl(flip id)0.zipWith flip((+):cycle[(+),(-),(*),(/),(**)])
Creates a series of transformations in a list, as in [add 1, add 2, subtract 3, ...], starting with 2 additions because we start with 0 in the fold. Next, we do what I call the List Application Fold, or foldl (flip id), which applies a list of homomorphisms in series. This starts with zero, adds the initial value, then does all of the above computed transformations to get a final result.
Note that (flip id) is the same as (\x y->y x), just shorter.
Sample usage:
f = foldl(flip id)0.zipWith flip((+):cycle[(+),(-),(*),(/),(**)])
f [1,2,3,4,5] -- Is 0.0
Python 2, 81 67 64 bytes
i=10
for n in input():exec'r%s=n'%'*+-*/*'[i::5];i=-~i%5
print r
Input is an array of floats. Test it on Ideone.
How it works
'*+-*/*'[i::5] selects every fifth character of the string, starting with the one at index i, so this yields ** if i = 0, + if i = 1, - if i = 2, * if i = 3 and / if i = 4. Since the string has length 6, the expression will yield an empty string if i > 5.
We initialize the variable i to 10. For each number n in the input array, we construct the string r<op>=n, which exec executes.
Initially, i = 10, so <op> is the empty string, and it initializes r with r+=n. After each step, we increment i modulo 5 with i=-~i%5, so the next step will retrieve the proper operator.
When all input numbers has been processed, and we print r, which holds the desired output.
Jelly, 13 bytes
“+_×÷*”ṁṖ⁸żFV
Try it online! or verify all test cases.
How it works
“+_×÷*”ṁṖ⁸żFV Main link. Argument: A (list of integers)
“+_×÷*” Yield the list of operations as a string.
Ṗ Yield A popped, i.e., with its last element removed.
ṁ Mold; reshape the string as popped A.
This repeats the characters of the string until it contains
length(A)-1 characters.
⁸ż Zipwith; pairs the integers of A with the corresponding characters.
F Flatten the result.
V Eval the resulting Jelly code.
Jelly always evaluates left-to-right (with blatant disregard towards
the order of operations), so this returns the desired result.
Mathematica, 67 66 65 bytes
Fold[{+##,#-#2,#2#,#/#2,If[#2==0,1,#^#2]}[[i++~Mod~5+1]]&,i=0;#]&
Simple Fold with a variable i holding the index.
PowerShell v2+, 124 bytes
param($n)$o=$n[0];if($y=$n.count-1){1..$y|%{$o=if(($x=$i++%5)-4){"$o"+'+-*/'[$x]+$n[$_]|iex}else{[math]::pow($o,$n[$_])}}}$o
Long because PowerShell doesn't have a ^ or ** operator, so we have to account for a separate case and use a .NET call.
Takes input $n as an array, sets our output $o to be the first digit. We then check the .count of the array, and so long as it's greater than one we enter the if. Otherwise, we skip the if.
Inside the if we loop through the array 1..$y|%{...} and each iteration we re-set $o to a new value, the result of another if/else statement. So long as our counter $i++ isn't modulo-5 equal to 4 (i.e., we're not at the ^ operator), we simply take $o and concatenate it with the appropriate symbol '+-*/'[$x] and the next number in the input array $n[$_]. We pipe that to iex (alias for Invoke-Expression and similar to eval), and that gets re-saved to $o. If we're on the ^ operator, we're in the else, so we execute a [math]::Pow() call, and that result gets re-saved back into $o.
In either case, we simply output $o to the pipeline and exit, with output implicit.
Actually, 23 bytes
;l"+-*/ⁿ"*@R':j':+'?o+ƒ
Actually uses postfix notation for mathematics, and operators that only ever take two arguments (such as the operators for addition, subtraction, multiplication, division, and exponentiation) do nothing when there is only one element on the stack. Thus, turning the input into Actually code is as simple as reversing the input, formatting it as numerics, and appending the operations. Then, the resultant code can be executed, giving the desired output.
Explanation:
;l"+-*/ⁿ"*@R':j':+'?o+ƒ
;l"+-*/ⁿ"* repeat the operations a number of times equal to the length of the input
(since extraneous operations will be NOPs, there's no harm in overshooting)
@R reverse the input
':j join on ":" (make a string, inserting ":" between every pair of elements in the list)
':+ prepend a ":" (for the first numeric literal)
'?o append a "?"
(this keeps the poor numeric parsing from trying to gobble up the first + as part of the numeric literal, since ? isn't interpreted as part of the literal, and is a NOP)
+ append the operations string
ƒ cast as a function and call it
Example of translated code for input 1,2,3,4,5:
:5:4:3:2:1?+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ+-*/ⁿ
J, 40 bytes
^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#)
Finds the number of values needed to use a multiple of 5 operators, than pads with the identity values of those operators. In order, + is 0, - is 0, * is 1, % is 1, and ^ is 1, which can be a bit value 00111, or 7 in base 10. Then operates on that list while cycling through operators.
Usage
f =: ^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#)
f 1 2 3 4 5
0
f 5 12 23 2 4 4 2 6 7
539
f _8 50 3 3 _123 4 17 99 13
_1055.36
f 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
256
f 1 0 1 0 1 0
1
f _9 _8 _1
_16
f 0 _3
_3
f _99
_99
Explanation
^~`(%~)`*`(-~)`+/@(|.@,7#:~#&2)(5-5|4+#) Input: A
# Get length of A
4+ Add four to it
5| Take it mod 5
5- Find 5 minus its value, call it x
#&2 Create x copies of 2
7#:~ Convert 7 to base 2 and take the last x digits
, Append those x digits to the end of A
|.@ Reverse it, call it A'
^~ Power, reversed operators
%~ Division, reversed operators
* Multiplication
-~ Subtraction, reversed operators
+ Addition
/@ Insert the previous operations, separated by `,
into A' in order and cycle until the end
Then evaluate the equation from right-to-left
and return
Haskell - 74
f(x:xs)=foldl(\x(o,y)->o x y)x(zip(cycle[(+),(-),(*),(/),flip(^).floor])xs)
Test cases:
λ> f[1,2,3,4,5] -> 0.0
λ> f[5,12,23,2,4,4,2,6,7] -> 539.0
λ> f[-8,50,3,3,-123,4,17,99,13] -> -1055.356943846277
λ> f [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256.0
It could probably be shorter; Haskell's support for infinite lists and higher order functions make the direct solution quite pleasant, though. A version of ^ :: Double -> Double -> Double would be nicer for golfing, but I couldn't find one. Thankfully, I didn't need a full lambda, so pointless style shaved off a few bytes.
Pyke, 22 21 bytes
lt5L%"+-*/^"L@\RJQ_XE
lt5L% - map(len(input)-1, %5)
"+-*/^"L@ - map(^, "+-*/^"[<])
\RJ - "R".join(^)
E - pyke_eval(^, V)
Q_X - splat(reversed(input))
Pyth, 27 26 25 bytes
.v+>tlQ*lQ"^c*-+":jdQ\-\_
Pyth uses prefix notation: 1+2 is written as +1 2 (space needed to separate numbers).
Therefore, for the first testcase, the expression would be (((1+2)-3)*4)/5, which in prefix notation, would be written as /*-+ 1 2 3 4 5.
In Pyth, float division is c instead of /, so it becomes c*-+ 1 2 3 4 5.
Also, in Pyth, -100 is written as _100 instead.
Therefore, for the third test case, which is ((((((((-8+50)-3)*3)/-123)^4)+17)-99)*13), it becomes: *-+^c*-+ _8 50 3 3 _123 4 17 99 13.
.v+>tlQ*lQ"^c*-+":jdQ\-\_
jdQ Join input by space.
: \-\_ Replace "-" with "_".
>tlQ*lQ"^c*-+" Generate the string "...^c*-+" of suitable length.
+ Join the two strings above.
.v Evaluate as a Pyth expression.
History
- 33 bytes:
v:P+*lQ\(ssV+R\)Q*"+-*/p"lQ\p"**" - 27 bytes:
.vs+_XUtQUQ"+-*c^"m:+;d\-\_ - 26 bytes:
.vs+_XUtQUQ"+-*c^":jdQ\-\_
Javascript ES7 49 bytes
a=>a.reduce((c,d,e)=>[c**d,c+d,c-d,c*d,c/d][e%5])
Saved 9 bytes thanks to Dom Hastings, saved another 6 thanks to Leaky Nun
Uses the new exponentiation operator.
Brachylog, 68 bytes
hI,?bL,1:+:-:*:/:^b:L:I{bhv?t.|[O:L:I]h$(P,LbM,OhA,Lh:Ir:A&:M:Pr&.}.
That's long… but it uses no evaluation predicate.
Explanation
Main predicate
hI, Unify I with the first element of the input ?bL, L is the input minus the first element 1:+:-:*:/:^b Construct the list of predicates [+:-:*:/:^] :L:I{...}. Call predicate 1 with [[+:-:*:/:^]:L:I] as inputPredicate 1
bhv?t. If the second element of Input is empty (i.e. L), unify Output with the last element of Input | Or [O:L:I] Input = [O:L:I] h$(P, P is O circularly permutated to the left LbM, M is L minus the first element OhA, A is the first element of O Lh:Ir:A& Call predicate A on [I:First element of L] :M:Pr&. Call predicate 1 recursively with P:M:

