18
\$\begingroup\$

Inspired by this

In the linked challenge, we are asked to apply addition to the elements of the original and the reverse of the input array. In this challenge, we are going to make it slightly more difficult, by introducing the other basic math operations.

Given an array of integers, cycle through +, *, -, //, %, ^, where // is integer division and ^ is exponent, while applying it to the reverse of the array. Or, in other words, apply one of the above functions to each element of an array, with the second argument being the reverse of the array, with the function applied cycling through the above list. This may still be confusing, so lets work through an example.

Input:   [1, 2, 3, 4, 5, 6, 7, 8, 9]
Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1]

         [ 1,  2,  3,  4,  5,    6,  7,  8,  9]
Operand:   +   *   -   /   %     ^   +   *   -
         [ 9,  8,  7,  6,  5,    4,  3,  2,  1]

Result:  [10, 16, -4,  0,  0, 1296, 10, 16,  8]

so the output for [1, 2, 3, 4, 5, 6, 7, 8, 9] would be [10, 16, -4, 0, 0, 1296, 10, 16, 8]

To cover the corner cases, the input will never contain a 0, but may contain any other integer in the range from negative infinity to positive infinity. You may take input as a list of strings representing digits if you want.

Test cases

input => output

[1, 2, 3, 4, 5, 6, 7, 8, 9]     => [10, 16, -4, 0, 0, 1296, 10, 16, 8]
[5, 3, 6, 1, 1]                 => [6, 3, 0, 0, 1]
[2, 1, 8]                       => [10, 1, 6]
[11, 4, -17, 15, 2, 361, 5, 28] => [39, 20, -378, 7, 2, 3.32948887119979e-44, 9, 308]

This is a so shortest code (in bytes) wins!

\$\endgroup\$
  • \$\begingroup\$ Sandbox (2k+ only) \$\endgroup\$ – caird coinheringaahing Sep 11 '17 at 19:29
  • \$\begingroup\$ @AdmBorkBork He is addressing it, I pointed that out in chat. \$\endgroup\$ – Mr. Xcoder Sep 11 '17 at 19:34
  • \$\begingroup\$ @AdmBorkBork corrected. I missed that in my test case generator \$\endgroup\$ – caird coinheringaahing Sep 11 '17 at 19:37
  • \$\begingroup\$ Your third test case still contains 0 >.> \$\endgroup\$ – Mr. Xcoder Sep 11 '17 at 19:43
  • 1
    \$\begingroup\$ @DigitalTrauma for languages which default to integers, I think outputting 0 is acceptable for tiny numbers like that. \$\endgroup\$ – caird coinheringaahing Sep 11 '17 at 22:59

18 Answers 18

6
\$\begingroup\$

Jelly, 10 bytes (fork)

+×_:%*6ƭ"Ṛ

I was just working on implementing a quick for this the other day, so it's quite surprising to see a use for it so soon. It still only exists as a fork, so you cannot try it online.

Sample output

$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[1,2,3,4,5,6,7,8,9]'
[10, 16, -4, 0, 0, 1296, 10, 16, 8]
$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[5,3,6,1,1]'
[6, 3, 0, 0, 1]
$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[2,1,8]'
[10, 1, 6]
$ ./jelly eun '+×_:%*6ƭ"Ṛ' '[11,4,-17,15,2,361,5,28]'
[39, 20, -378, 7, 2, 3.32948887119979e-44, 9, 308]

Explanation

+×_:%*6ƭ"Ṛ  Input: array
      6ƭ    Tie 6 dyads
+             Addition
 ×            Multiplication
  _           Subtraction
   :          Integer division
    %         Modulo
     *        Power
        "   Vectorize with
         Ṛ  Reverse
\$\endgroup\$
  • \$\begingroup\$ whaaaaaaaat come on really :( but nice, this quick seems quite useful :D \$\endgroup\$ – HyperNeutrino Sep 11 '17 at 19:53
  • \$\begingroup\$ This needs to be pulled to Jelly. +1 although you may want to extend ƭ to support nilads (replace value) and monads (apply on left argument) as well \$\endgroup\$ – Erik the Outgolfer Sep 12 '17 at 9:50
  • \$\begingroup\$ @EriktheOutgolfer It already works with monads. See the examples I posted in Jelly chat. Nilads are a different case. \$\endgroup\$ – miles Sep 12 '17 at 11:52
  • \$\begingroup\$ @miles I mean just like how nilads behave here. \$\endgroup\$ – Erik the Outgolfer Sep 12 '17 at 11:56
  • \$\begingroup\$ @EriktheOutgolfer Ok it supports nilads now, but requires you to define their length, and use a space between each. Example 2 1”q3ƭ€ on [7,4,9,0] returns [2, 1, 'q', 2] \$\endgroup\$ – miles Sep 12 '17 at 12:22
4
\$\begingroup\$

Husk, 16 bytes

This challenge favours languages that can create infinite lists of functions. Maybe not, eval FTW

zF¢+ë+*-÷e%^Ṡze↔

Try it online!

How?

  ¢+ë+*-÷e%^         The infinite list [+,*,-,÷,%,^,+,*,-,...
    ë+*-÷            The list [+,*,-,÷]
         e%^         The list [%,^]
   +                 Concatenated
  ¢                  Then repeated infinitely
               ↔     The input reversed e.g [9,8,7,6,5,4,3,2,1]
            Ṡze      Zipped with itself     [[9,1],[8,2],[7,3],[6,4],[5,5],[4,6],[3,7],[2,8],[1,9]]
zF                   Zipwith reduce, the list of functions and the list of lists.
                     [F+[9,1],F*[8,2],F-[7,3],F÷[6,4],F%[5,5],F^[4,6],F+[3,7],F*[2,8],F-[1,9]]
                     [10     ,16     ,-4     ,0      ,0      ,1296   ,10     ,16     ,8      ]

Alternative 17 byte solution:

ṠozIzI¢+ë+*-÷e%^↔
\$\endgroup\$
  • \$\begingroup\$ Out of curiosity, why can't you do ë+*-÷%^? Why do the e necessary? \$\endgroup\$ – caird coinheringaahing Nov 14 '17 at 1:15
  • \$\begingroup\$ @cairdcoinheringaahing ë takes 4 arguments, e takes 2. There isn't one for 6 \$\endgroup\$ – H.PWiz Nov 14 '17 at 1:30
3
\$\begingroup\$

05AB1E, 18 bytes

Â"+*-÷%m"Ig×)øε`.V

Try it online!

Explanation

                    # push a reversed copy of the input
 "+*-÷%m"            # push the list of operators
         Ig×         # repeat it input times
            )ø       # zip together
              ε      # apply to each triplet
               `     # push separately to stack
                .V   # evaluate
\$\endgroup\$
  • \$\begingroup\$ Ig∍ if you wanted to use the "newish" command (haven't seen much here). \$\endgroup\$ – Magic Octopus Urn Oct 12 '17 at 18:58
3
\$\begingroup\$

Bash + GNU utilities, 53

tac $1|paste -d, $1 -|tr ',
' '
;'|paste -sd+*-/%^|bc

This script takes a filename as a command-line parameter.

Try it online.

The nice thing here is that paste -d allows a list of separators to be given, which are used cyclically. The rest it just getting the input into the right format to do this.

\$\endgroup\$
3
\$\begingroup\$

Jelly, 15 bytes

żṚj"“+×_:%*”ṁ$V

Try it online! or see the test-suite.

How?

żṚj"“+×_:%*”ṁ$V - Link: list of numbers, a       e.g. [5, 3, 6, 1, 1]
 Ṛ              - reverse a                           [1, 1, 6, 3, 5]
ż               - interleave                          [[5,1],[3,1],[6,6],[1,3],[1,5]
             $  - last two links as a monad:
    “+×_:%*”    -   literal list of characters        ['+','×','_',':','%','*']
            ṁ   -   mould like a                      ['+','×','_',':','%']
   "            - zip with the dyad:
  j             -   join                              ["5+1","3×1","6_6","1:3","1%5"]
              V - evaluate as Jelly code (vectorises) [6, 3, 0, 0, 1]
\$\endgroup\$
  • \$\begingroup\$ Save a couple of bytes with ż“+×_:%*”;"ṚV \$\endgroup\$ – Erik the Outgolfer Sep 12 '17 at 12:23
  • \$\begingroup\$ @EriktheOutgolfer that only works if the length of the input is exactly 6. I think you'd need to do ż“+×_:%*”ṁ$;"ṚV which is also 15 bytes. \$\endgroup\$ – Jonathan Allan Sep 12 '17 at 15:24
  • \$\begingroup\$ ok what was I thinking of...I so miss "tie" :( \$\endgroup\$ – Erik the Outgolfer Sep 12 '17 at 15:29
3
\$\begingroup\$

Python 2, 67 bytes

-3 bytes thanks to ovs.

lambda l:[eval(j+'*+*-/%*'[-~i%6::6]+l[~i])for i,j in enumerate(l)]

Try it online!

Python 2, 95 bytes

lambda l:[[add,mul,sub,div,mod,pow][i%6](v,l[~i])for i,v in enumerate(l)]
from operator import*

Try it online!

eval is evil... but perhaps more golfy. :P

\$\endgroup\$
  • \$\begingroup\$ 67 bytes \$\endgroup\$ – ovs Sep 12 '17 at 10:37
2
\$\begingroup\$

JavaScript (ES7), 68 67 bytes

a=>[...a].map((v,i)=>(x=a.pop(),o='+*-/%'[i%6])?eval(v+o+x)|0:v**x)

let f =

a=>[...a].map((v,i)=>(x=a.pop(),o='+*-/%'[i%6])?eval(v+o+x)|0:v**x)

console.log(JSON.stringify(f([1, 2, 3, 4, 5, 6, 7, 8, 9]    ))) // [10, 16, -4, 0, 0, 1296, 10, 16, 8]
console.log(JSON.stringify(f([5, 3, 6, 1, 1]                ))) // [6, 3, 0, 0, 1]
console.log(JSON.stringify(f([2, 1, 8]                      ))) // [10, 1, 6]
console.log(JSON.stringify(f([11, 4, -17, 15, 2, 361, 5, 28]))) // [39, 20, -378, 7, 2, 3.32948887119979e-44, 9, 308]

\$\endgroup\$
  • \$\begingroup\$ Nice solution! Maybe you can move the assignment of o inside the parentheses of .pop() to save a few bytes. \$\endgroup\$ – Luke Sep 11 '17 at 21:10
  • \$\begingroup\$ @Luke The assignment to o is also used as the condition of the ternary operator. That would break that scheme. \$\endgroup\$ – Arnauld Sep 11 '17 at 21:15
  • \$\begingroup\$ @Shaggy. That was the exact same first Arnauld's answer. \$\endgroup\$ – user72349 Sep 11 '17 at 22:27
  • \$\begingroup\$ @ThePirateBay: Ah. On SE mobile so can't see edit histories. \$\endgroup\$ – Shaggy Sep 11 '17 at 22:28
2
\$\begingroup\$

Perl 6, 67 66 bytes

Saved 1 byte thanks to @nwellnhof.

{map {EVAL ".[0] {<+ * - div % **>[$++%6]} .[1]"},zip $_,.reverse}

Try it online!

Very unimaginative (and probably bad) solution. Zips the argument with itself reversed. The resulting list is then mapped with the block that EVALs the string a (operator) b. The operator is chosen from the list of strings <+ * - div % **> using the free state (think static in C — the value persists across the calls of the block) variable $. This is created for each block separately and set to 0. You can do anything you like with it, but you may reference it only once (each occurence of $ refers to another variable, actually). So $++%6 is actually 0 during the first call, 1 during the second, ... 5 during the 6th, 0 during the 7th and so on.

I at first tried to do without an EVAL. The operators are in fact just subs (= functions), but their names are so extremely ungolfy (&infix:<+> and so on) that I had to forgo that approach.

\$\endgroup\$
  • \$\begingroup\$ map {EVAL ".[0] ... .[1]"},zip $_,.reverse is 1 byte shorter. \$\endgroup\$ – nwellnhof Sep 11 '17 at 23:40
  • \$\begingroup\$ @nwellnhof, thanks! \$\endgroup\$ – Ramillies Sep 11 '17 at 23:50
2
\$\begingroup\$

Haskell, 74 117 105 bytes

x#y=fromIntegral.floor$x/y
x%y=x-x#y
f u=[o a b|(o,a,b)<-zip3(cycle[(+),(*),(-),(#),(%),(**)])u(reverse u)]

Try it online!

Saved 12 bytes thanks to @nimi

There is certainly a better way to achieve this.

EDIT 1. Fixed exponent for integers; 2. There's definitely a better way, see comment below: 95 91 bytes

x#y=fromIntegral.floor$x/y
x%y=x-x#y
f=zipWith3($)(cycle[(+),(*),(-),(#),(%),(**)])<*>reverse

Try it online!

\$\endgroup\$
  • \$\begingroup\$ zipWith3($)(cycle[(+),(*),(-),div,mod,(^)])<*>reverse Is a shorter, now deleted version of yours. \$\endgroup\$ – H.PWiz Sep 11 '17 at 20:28
  • \$\begingroup\$ @H.PWiz I was looking for something like that but didn't have the time to look further. Why did you delete it? I believe it's not forbidden to have two different solutions in the same language, especially when one is far better than the other... \$\endgroup\$ – jferard Sep 11 '17 at 20:54
  • \$\begingroup\$ @H.PWiz Fixed exponent. \$\endgroup\$ – jferard Sep 12 '17 at 8:30
  • \$\begingroup\$ No need for the h in the call of o: o a b and without that you can inline h (TIO). \$\endgroup\$ – nimi Sep 12 '17 at 15:00
1
\$\begingroup\$

Python 2, 71 bytes

lambda l:[eval(y+'+*-/%*'[x%6]*-~(x%6>4)+l[~x])for x,y in enumerate(l)]

Try it online!

Saved 2 bytes thanks to ovs!

\$\endgroup\$
1
\$\begingroup\$

J, 44 42 bytes

Crossed out 44, yada yada...

-2 bytes thanks to @ConorO'Brien

_2+/`(*/)`(-/)`(<.@%/)`(|~/)`(^/)\[:,],.|.

Try it online!

So many parens and inserts... Surely there's a better way to do this (maybe using insert rather than infix?)

Explanation

_2(+/)`(*/)`(-/)`(<.@%/)`(|~/)`(^/)\[:,],.|.  Input: a
                                       ],.|.  Join a with reverse(a)
                                      ,       Ravel (zip a with reverse(a))
_2                                 \          To non-overlapping intervals of 2
  (+/)`(*/)`(-/)`(<.@%/)`(|~/)`(^/)           Apply the cyclic gerund
   +/                                           Insert addition
        */                                      Insert subtraction
             -/                                 Insert division 
                  <.@%/                         Insert integer division
                          |~/                   Insert mod
                                ^/              Insert exponentiation

Some notes:

J doesn't have integer division, so we compose %-division with >.-floor. J's mod (|) does the reverse order of what we'd expect, so we have to invert its order using ~-reflexive.

Even though we're moving over intervals of 2, we have to use /-insert to insert the verbs to have them be used dyadically since that's how \-infix works.

\$\endgroup\$
  • \$\begingroup\$ I'd also love to know how to avoid all the () and repeated / -- I wasn't able to figure it out.... \$\endgroup\$ – Jonah Sep 11 '17 at 22:16
  • \$\begingroup\$ @Jonah, best I can think of is something like / on a reversed array (since it operates backwards...) with verbs like (,+)`(,*) but that doesn't help much... (also it doesn't work) \$\endgroup\$ – cole Sep 11 '17 at 22:27
  • 1
    \$\begingroup\$ The gerund can be +/`(*/)`... \$\endgroup\$ – Conor O'Brien Sep 11 '17 at 23:01
1
\$\begingroup\$

Ruby, 63 57 bytes

->a{t=0;a.map{|x|eval [x,a[t-=1]]*%w(** % / - * +)[t%6]}}

Nothing fancy, really. Just iterate on the array, use an index as reverse iterator, join into a string using the right operator, evaluate, rinse and repeat.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

k, 40 bytes

{_((#x)#(+;*;-;%;{y!x};{*/y#x})).'x,'|x}

Try it online!

{                                      } /function(x)
                                     |x  /reverse x
                                  x,'    /zip concat with x
        ( ; ; ; ;     ;       )          /list of operations
         + * - %                         /add, mult, sub, div
                 {y!x}                   /mod (arguments need to be reversed)
                       {*/y#x}           /pow (repeat and fold multiply)
  ((#x)#                       )         /resize operations to length of x
                                .'       /zip apply
 _                                       /floor result
\$\endgroup\$
1
\$\begingroup\$

MATL, 27 23 bytes

-4 bytes thanks to @LuisMendo

tP+1M*1M-IM&\w1M^v"@X@)

Try it online!

Explanation:

tP         % duplicate and flip elements
+          % push array of sums (element-wise)
1M*        % push array of products (element-wise)
1M-        % push array of subtractions (element-wise)
IM&\w      % push array of divisions and modulo (element-wise)
1M^        % push array of power (element-wise)
v          % vertically concatenate all arrays
"@X@)    % push to stack values with the correct index based on operator
           % (implicit) convert to string and display
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 68 + 1 (-p) = 69 bytes

print$",eval'int 'x($i%6==3).$_.qw|+ ** % / - *|[$i--%6].$F[$i]for@F

Try it online!

Takes input as space separated list of numbers.

\$\endgroup\$
  • \$\begingroup\$ Fails for the last test case :( tio.run/##K0gtyjH9/… \$\endgroup\$ – Shaggy Sep 11 '17 at 22:39
  • \$\begingroup\$ Not anymore. :) \$\endgroup\$ – Xcali Sep 11 '17 at 23:04
0
\$\begingroup\$

R, 74 bytes

function(l)Map(Map,c(`+`, `*`, `-`, `%/%`, `%%`,`^`),l,rev(l))[1:sum(l|1)]

Try it online!

This is the final answer I came up with. It returns a list of length length(l) where each element is a list containing the corresponding element. Kinda crappy but they're all there. If that's unacceptable, either of the Map can be replaced with mapply for +3 bytes.

Since R operators are all functions (the infix notation just being syntactic sugar), I tried to select one from a list; for example, the 94 byte solution below.

To try and get rid of the loop, I tried sapply, but that only works with a single function and input list. Then I remembered the multivariate form, mapply, which takes an n-ary function FUN and n succeeding arguments, applying FUN to the first, second, ..., elements of each of the arguments, recycling if necessary. There is also a wrapper function to mapply, Map that "makes no attempt to simplify the result". Since it's three bytes shorter, it's a good golfing opportunity.

So I defined a trinary function (as in the 80 byte solution below) that takes a function as its first argument, and applies it to its second and third ones. However, I realized that Map is a function that takes a function as its first argument and applies it to successive ones. Neat!

Finally, we subset at the end to ensure we only return the first length(l) values.

R, 80 bytes

function(l)Map(function(x,y,z)x(y,z),c(`+`, `*`, `-`, `%/%`, `%%`,`^`),l,rev(l))

Try it online!

This one doesn't work, as it will return 6 values for lists with less than 6 elements.

R, 94 bytes

function(l){for(i in 1:sum(l|1))T[i]=switch(i%%6+1,`^`,`+`,`*`,`-`,`%/%`,`%%`)(l,rev(l))[i]
T}

Try it online!

Explanation (mildly ungolfed):

function(l){
 for(i in 1:length(l)){
  fun <- switch(i%%6+1,`^`,`+`,`*`,`-`,`%/%`,`%%`) # select a function
  res <- fun(l,rev(l))                             # apply to l and its reverse
  T[i] <- res[i]                                   # get the i'th thing in the result
 }
 T                                                 # return the values
}

Because each of the functions is vectorized, we can index at the end (res[i]). This is better than the eval approach below.

R, 100 bytes

function(l)eval(parse(t=paste("c(",paste(l,c("+","*","-","%/%","%%","^"),rev(l),collapse=","),")")))

Try it online!

This is the shortest eval approach I could find; because we have to collect the results into one vector, we need to paste a c( ) around all the expressions, which adds a ton of unnecessary bytes

\$\endgroup\$
0
\$\begingroup\$

Casio-Basic, 108 bytes

{x+y,x*y,x-y,int(x/y),x-int(x/y)y,x^y}⇒o
dim(l)⇒e
Print seq(o[i-int(i/6)6+1]|{x=l[i+1],y=l[e-i]},i,0,e-1)

That was painful. Especially because mod(x,y) returns x when it really shouldn't, which meant I had to make my own mod function: hence the x-int(x/y)y.

Loops i from 0 to length(l)-1, taking successive elements in the o list and applying l[i] for x and l[-i] for y. (negative indices don't work though, so instead I subtract i from the length of the list and take that index.)

107 bytes for the function, +1 byte to add l in the parameters box.

\$\endgroup\$
0
\$\begingroup\$

Java 8, 336 bytes

import java.math.*;a->{int b[]=a.clone(),i=0,l=b.length,s,t;for(;i<l/2;b[i]=b[l+~i],b[l+~i++]=t)t=b[i];BigInteger r[]=new BigInteger[l],u,v;for(i=-1;++i<l;t=b[i],v=new BigInteger(t+""),r[i]=(s=i%6)<1?u.add(v):s<2?u.multiply(v):s<3?u.subtract(v):s<4?u.divide(v):s<5?u.remainder(v):t<0?u.ZERO:u.pow(t))u=new BigInteger(a[i]+"");return r;}

Try it here.

Sigh..
Input as int[], output as java.math.BigInteger[].

Without the rule "To cover the corner cases, the input will never contain a 0, but may contain any other integer in the range from negative infinity to positive infinity.", using integers in the range -2147483648 to 2147483647, it would be 186 bytes (input as int[], and no output because it modifies this input-array instead to save bytes):

a->{int b[]=a.clone(),i=0,l=b.length,t,u,v;for(;i<l/2;b[i]=b[l+~i],b[l+~i++]=t)t=b[i];for(i=-1;++i<l;v=b[i],a[i]=(t=i%6)<1?u+v:t<2?u*v:t<3?u-v:t<4?u/v:t<5?u%v:(int)Math.pow(u,v))u=a[i];}

Try it here.

Explanation:

import java.math.*;            // Required import for BigInteger

a->{                           // Method with int[] parameter and BigInteger[] return-type
  int b[]=a.clone(),           //  Make a copy of the input-array
      i=0,                     //  Index-integer
      l=b.length,              //  Length of the input
      s,t;                     //  Temp integers
  for(;i<l/2;b[i]=b[l+~i],b[l+~i++]=t)t=b[i];
                               //  Reverse the input-array and store it in `b`
  BigInteger r[]=new BigInteger[l],
                               //  Result-array
             u,v;              //  Temp BigIntegers
  for(i=-1;                    //  Reset `i` to -1
      ++i<l;                   //  Loop over the array(s):
                               //    After every iteration:
      t=b[i],                  //     Set the current item of `b` in `t`
      v=new BigInteger(t+""),  //     And also set it in `v` as BigInteger
      r[i]=(s=i%6)<1?          //   If the index `i` modulo-6 is 0:
            u.add(v)           //    Add the items with each other
           :s<2?               //   Else-if index `i` modulo-6 is 1:
            u.multiply(v)      //    Multiply the items with each other
           :s<3?               //   Else-if index `i` modulo-6 is 2:
            u.subtract(v)      //    Subtract the items with each other
           :s<4?               //   Else-if index `i` modulo-6 is 3:
            u.divide(v)        //    Divide the items with each other
           :s<5?               //   Else-if index `i` modulo-6 is 4:
            u.remainder(v)     //    Use modulo for the items
           :                   //   Else (index `i` modulo-6 is 5):
            t<0?               //    If `t` is negative:
             u.ZERO            //     Simply use 0
            :                  //    Else:
             u.pow(t))         //     Use the power of the items
    u=new BigInteger(a[i]+""); //  Set the current item of `a` to `u` as BigInteger
                               //  End of loop (implicit / single-line body)
  return r;                    //  Return the result BigInteger-array
}                              // End of method
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.