17
\$\begingroup\$

In mathematics, the factorial, shortened "fact" of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! is 1 * 2 * 3 * 4 * 5 = 120

The factorial of 0 is 1, according to the convention for an empty product.


These are the regular facts we are used to. Let's add some alternatives:

  1. The factorial (defined above)
  2. The double factorial: n!! = 1 + 2 + ... + n
  3. The triple factorial: n!!! = 1 - (2 - (3 - ( ... - n)))...)
  4. The quadruple factorial: n!!!! = 1 / (2 / (3 ... / n)))...). Note: This is floating point division, not integer division.

Challenge

Take a non-negative integer input n, directly followed by between 1 and 4 exclamation marks. The input will look (exactly) like this: 0!, 5!!, 132!!! or 4!!!!. In this challenge, you may not assume a flexible input format, sorry.

Output

The output should be the result, on any convenient format. The result of the quadruple factorial must have at least 2 digits after the decimal point, except for 0!!!! = 0.

Test cases:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
---
0!! = 0
1!! = 1
2!! = 3
3!! = 6
4!! = 10
5!! = 15
6!! = 21
7!! = 28
8!! = 36
9!! = 45
10!! = 55
---
0!!! = 0
1!!! = 1
2!!! = -1
3!!! = 2
4!!! = -2
5!!! = 3
6!!! = -3
7!!! = 4
8!!! = -4
9!!! = 5
10!!! = -5
---
0!!!! = 0
1!!!! = 1
2!!!! = 0.5
3!!!! = 1.5
4!!!! = 0.375
5!!!! = 1.875
6!!!! = 0.3125
7!!!! = 2.1875
8!!!! = 0.27344
9!!!! = 2.4609
10!!!! = 0.24609

The shortest solution in each language wins.

\$\endgroup\$
  • 2
    \$\begingroup\$ Can the quadruple factorial also be rational division? \$\endgroup\$ – Martin Ender Aug 3 '17 at 7:12
  • 6
    \$\begingroup\$ "The double factorial" definition's a fit off... \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 9:11
  • 4
    \$\begingroup\$ @Erik, it's an alternative double fact ;-) \$\endgroup\$ – Stewie Griffin Aug 3 '17 at 9:39
  • 1
    \$\begingroup\$ @StewieGriffin BTW it's a little bit sneaky that 0! -> 1. \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 9:48
  • 5
    \$\begingroup\$ Title should be Alternative Facts \$\endgroup\$ – Digital Trauma Aug 3 '17 at 16:49

21 Answers 21

7
\$\begingroup\$

JavaScript (ES6), 88 bytes

s=>eval(([a,b]=s.split(/\b/),g=k=>+a?k-a?k+'_*+-/'[b.length]+`(${g(k+1)})`:k:+!b[1])(1))

Test cases

let f =

s=>eval(([a,b]=s.split(/\b/),g=k=>+a?k-a?k+'_*+-/'[b.length]+`(${g(k+1)})`:k:+!b[1])(1))

for(o = '!'; o <= '!!!!'; o += '!') {
  for(n = 0; n <= 10; n++) {
    console.log(n + o + ' = ' + f(n + o));
  }
}

Formatted and commented

s =>                                // given the input string s,
  eval(                             // evaluate as JS code:
    ( [a, b] = s.split(/\b/),       //   a = integer (as string) / b = '!' string
      g = k =>                      //   g = recursive function taking k as input
        +a ?                        //     if a is not zero:
          k - a ?                   //       if k is not equal to a:
            k + '_*+-/'[b.length] + //         append k and the operation symbol
            `(${g(k + 1)})`         //         append the result of a recursive call
          :                         //       else:
            k                       //         just append k and stop recursion
        :                           //     else:
          +!b[1]                    //       return 1 for multiplication / 0 otherwise
    )(1)                            //   initial call to g() with k = 1
  )                                 // end of eval()
\$\endgroup\$
7
\$\begingroup\$

Husk, 15 bytes

§!ëΠΣF-F/#'!oṫi

Try it online!

Explanation

Indexing into a list of functions: the joys of using a functional language.

§!ëΠΣF-F/#'!oṫi  Implicit input, say x = "6!!!"
              i  Convert to integer (parses the leading sequence of digits): 6
            oṫ   Descending range to 1: y = [6,5,4,3,2,1]
  ë              Four-element list containing the functions
   Π             product,
    Σ            sum,
     F-          left fold with subtraction (gives 0 for empty list), and
       F/        left fold with division (gives 0 for empty list).
 !               1-based index into this list with
         #'!     count of !-characters in input: gives F-
§                Apply to y and print implicitly: -3

I use a descending range and left folds, since - and / take their arguments in reverse order in Husk.

\$\endgroup\$
  • \$\begingroup\$ Indexing into a list of functions is woah... \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 12:08
  • \$\begingroup\$ I was thinking of Haskell, and then I see this... Truly seems to be the right tool for the job. +1 \$\endgroup\$ – alleks Aug 4 '17 at 3:40
  • \$\begingroup\$ This is what Husk was made for :D \$\endgroup\$ – Leo Aug 5 '17 at 19:48
6
\$\begingroup\$

C# (.NET Core), 134 130 128 bytes

s=>{double e=s.Split('!').Length,n=int.Parse(s.Trim('!')),i=n,r=n;for(;--i>0;)r=e>4?i/r:e>3?i-r:e>2?i+r:i*r;return n<1&e<3?1:r;}

Try it online!

The best part of code golfing are the things you learn while trying to solve the challenges. In this one I have learnt that in C# you can trim other characters besides whitespaces from strings.

  • 4 bytes saved thanks to LiefdeWen!
  • 2 bytes saved because I do not need to substract 1 to s.Split('!').Length, just fix the limits in e>4?i/r:e>3?i-r:e>2?i+r:i*r and n<1&e<3?1:r.
\$\endgroup\$
  • 1
    \$\begingroup\$ You can make e n and i also double to avoid declaring it for r to save 4 bytes. \$\endgroup\$ – LiefdeWen Aug 3 '17 at 10:09
  • 1
    \$\begingroup\$ @LiefdeWen Or float to save another byte. \$\endgroup\$ – Kevin Cruijssen Aug 3 '17 at 13:09
4
\$\begingroup\$

Perl 5, 62 bytes

61 bytes code + 1 for -p.

$_=/^0!$/+eval join(qw{| *( +( -( /(}[s/!//g],1..$_).")"x--$_

Thanks to @G B for pointing out a miss on my part!

Try it online! (this uses -l for readability)

\$\endgroup\$
  • 4
    \$\begingroup\$ 0! should be 1 not 0 \$\endgroup\$ – G B Aug 3 '17 at 9:39
  • \$\begingroup\$ @GB Well that doesn't make any sense... Fixed for +5! \$\endgroup\$ – Dom Hastings Aug 3 '17 at 12:07
4
\$\begingroup\$

R, 113 111 bytes

function(s){z=strtoi((n=strsplit(s,'!')[[1]])[1])
n=length(n)
`if`(z,Reduce(c('*','+','-','/')[n],1:z,,T),n<2)}

Try some test cases!

ungolfed:

function(s){
  n <- strsplit(s,"!")[[1]]          # split on "!"
  z <- strtoi(n[1])                  # turn to integer
  n <- length(n)                     # count number of "!"
  FUN <- c(`*`,`+`,`-`,`/`)[[n]]     # select a function
  right <- TRUE                      # Reduce (fold) from the right
  if( z > 0)                         # if z > 0
    Reduce(FUN, 1:z,,right)          # return the value
  else    
    (n < 2)                          # 1 if n = 1, 0 if n > 1
}
\$\endgroup\$
  • \$\begingroup\$ el(strsplit(s,"!")) saves 1 byte \$\endgroup\$ – bouncyball Aug 3 '17 at 16:18
4
\$\begingroup\$

Python3, 124 130 121 119 bytes

At this point, I believe that recursion is the key to further byte saving.

s=input()
l=s.count('!')
v=int(s[:-l])+1
print(eval((" *+-/"[l]+"(").join(map(str,range(1,v)))+")"*(v-2)or"0")+(l<2>v))

Try the testcases on Try it online!

-9 bytes thanks to @Mr.Xcoder!

-2 bytes thanks to @Felipe Nardi Batista!

\$\endgroup\$
  • \$\begingroup\$ Fails for 6!. It should be 720. \$\endgroup\$ – Mr. Xcoder Aug 3 '17 at 8:08
  • \$\begingroup\$ I updated the Tio test suite. \$\endgroup\$ – Mr. Xcoder Aug 3 '17 at 8:23
  • \$\begingroup\$ -3 bytes. \$\endgroup\$ – Mr. Xcoder Aug 3 '17 at 8:25
  • \$\begingroup\$ Oh yeah, sure, didn't spot that \$\endgroup\$ – Mr. Xcoder Aug 3 '17 at 8:26
  • 2
    \$\begingroup\$ Behold ES6 \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 9:23
3
\$\begingroup\$

Pyth, 34 30 bytes

+uv++H@"/*+-"/Q\!G_tUK.vQKq"0!

Try it online!

Explanation

+uv++H@"/*+-"/Q\!G_tUK.vQKq"0!"Q    Implicit: append "Q
                                    Implicit: read input to Q
                      .vQ           Evaluate Q as Pyth code. This evaluates the integer,
                                    any !'s are parsed as unary NOT for the next expression
                                    and discarded.
                     K              Save the result to K.
                    U               Get a list [0, 1, ..., K-1].
                   t                Drop the first item to get [1, 2, ..., K-1].
                  _                 Reverse to get [K-1, K-2, ..., 1].
 u                       K          Starting from G = K, for H in [K-1, K-2, ..., 1] do:
             /Q\!                     Count the !'s in Q.
      @"/*+-"                         Get the correct operator.
    +H                                Prepend the current H.
   +             G                    Append the previous value G.
  v                                   Evaluate as Python code.
                          q"0!"Q    See if Q == "0!".
+                                   If so, add 1.
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 27 bytes

þL"/*+-"¹'!¢©è".»"ì.VD_нi®Θ

Try it online!

\$\endgroup\$
  • \$\begingroup\$ DO you know why „.» doesn't work? \$\endgroup\$ – Riley Aug 3 '17 at 13:08
  • \$\begingroup\$ @Riley » is part of an unfinished compressed string, so it errors out and, as usually in 05AB1E, the error is ignored. \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 13:19
  • \$\begingroup\$ I was trying to do "*+-/"èU then after using L follow up with .»X but it treats X as a string, not a command and .»X.V is even wonkier. \$\endgroup\$ – Magic Octopus Urn Aug 3 '17 at 15:13
  • \$\begingroup\$ @MagicOctopusUrn X doesn't eval. X.V are two commands. \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 15:31
  • \$\begingroup\$ @EriktheOutgolfer yeah, but I was hoping it'd eval before processing the fold. Hoping, not expecting :(. Could've sworn there was a "use single character String as command in dyadic chain" or something. \$\endgroup\$ – Magic Octopus Urn Aug 3 '17 at 15:32
2
\$\begingroup\$

Ruby, 83 80 79 bytes

->s{z=s.count ?!;s<?1?1+1<=>z:eval([*1..w=s.to_i]*(".0"+"_*+-/"[z]+?()+?)*~-w)}

Try it online!

Explanation:

->s{
    # Get number of !
    z=s.count ?!

    # Special case: if the number is 0, then output 0 or 1 depending on z
    s<?1?1+1<=>z:

    # Otherwise build the full expression as a string and then evaluate it
    eval([*1..w=s.to_i]*(".0"+"_*+-/"[z]+?()+?)*~-w)
}
\$\endgroup\$
2
\$\begingroup\$

Java 8, 141 136 134 bytes

s->{float q=s.split("!",-1).length,n=new Float(s.split("!")[0]),i=n,r=n;for(;--i>0;r=q<3?i*r:q<4?i+r:q<5?i-r:i/r);return n<1&q<3?1:r;}

-5 bytes (141 → 136) thanks to @CarlosAlejo's C# answer.

Explanation:

Try it here.

s->{                                // Method with String parameter and float return-type
  float q=s.split("!",-1).length,   //  Amount of exclamation marks + 1
        n=new Float(s.split("!")[0]),
                                    //  The number before the exclamation marks
        i=n,                        //  Index (starting at `n`)
        r=n;                        //  Return sum (starting at `n`)
  for(;--i>0;                       //  Loop from `i-1` down to 1
    r=                              //   Change the result (`r`) to:
      q<3?                          //    If `q` is 2:
       i*r                          //     Multiply
      :q<4?                         //    Else if `q` is 3:
       i+r                          //     Addition
      :q<5?                         //    Else if `q` is 4:
       i-r                          //     Subtraction
      :                             //    Else (if `q` is 5):
       i/r                          //     Division
  );                                //  End of loop
  return n<1&q<3?                   //  Edge case if the input is `0!`:
          1                         //   Then return 1
         :                          //  Else:
          r;                        //   Return the result
}                                   // End of method
\$\endgroup\$
  • 1
    \$\begingroup\$ I have seen a similar answer somewhere else... :-D I keep forgetting that float is shorter than double. \$\endgroup\$ – Charlie Aug 3 '17 at 12:55
  • \$\begingroup\$ @CarlosAlejo Yeah, I noticed your answer after my initial 141 byte answer. Changing float q=s.length()-(s=s.replace("!","")).length(),n=new Float(s) to the current answer saved me 5 bytes. :) Forgot to add a "bytes saved thanks to" part I noticed now.. Sorry about that. \$\endgroup\$ – Kevin Cruijssen Aug 3 '17 at 13:07
  • \$\begingroup\$ oh, nevermind that, I'm glad you liked my answer. :-) \$\endgroup\$ – Charlie Aug 3 '17 at 13:24
2
\$\begingroup\$

Jelly,  24 23 26  25 bytes

+ 3  2 bytes patching up to fix after misinterpretation :(

×
+
_
÷
ṣ”!µḢVRṚȯL©Ị$®ŀ@/

A full program (a monadic link with helper links referenced by program location)

Try it online! or see a test suite.

How?

× - Link 1, multiply: number, number

+ - Link 2, add: number, number

_ - Link 1, subtract: number, number

÷ - Link 1, divide: number, number

ṣ”!µḢVRṚȯL©Ị$®ŀ@/ - Main link: list of characters, a
ṣ”!               - split s at '!' characters
   µ              - monadic separation, call that b
    Ḣ             - head - pop and yield the digit list from b, modifying b
     V            - evaluate as Jelly code (get the number, say N)
      R           - range = [1,2,3,...,N]
       Ṛ          - reverse = [N,...,3,2,1]
            $     - last two links as a monad:
         L        -   length of modified b (number of '!' characters)
          ©       -   (copy to register)
           Ị      -   insignificant? (1 when just one '!', 0 when two or more)
        ȯ         - logical or (1 for "0!", 0 for "0!!...", the reversed-range otherwise)
                / - cumulative reduce by:
               @  -  with swapped arguments:
              ŀ   -    dyadic call of link at index:
             ®    -      recall value from register (number of '!' characters)
\$\endgroup\$
  • \$\begingroup\$ Fails for 0!. \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 15:41
  • \$\begingroup\$ Oh, haha - I had read your comment under the OP wrong - I thought they'd made 0! defined as 0 which would be wrong. \$\endgroup\$ – Jonathan Allan Aug 3 '17 at 15:48
  • \$\begingroup\$ All fixed up now :) \$\endgroup\$ – Jonathan Allan Aug 3 '17 at 16:08
  • \$\begingroup\$ Too bad TIO is broken right now so that I can't test if it's still invalid. :( :P Also too bad that you can't use / on an empty list. D: EDIT: Apparently valid for 0!, 0!!, 0!!! and 0!!!!. +1 \$\endgroup\$ – Erik the Outgolfer Aug 3 '17 at 16:51
2
\$\begingroup\$

Self-modifying x86_64 machine code, 123 bytes

0f b6 0f 31 c0 eb 11 0f be c9 8d 04 80 8d 44 41 d0 0f b6 4f 01 48 ff c7 83 f9 21 75 ea b9 21 21 21 a1 33 0f 0f bc c9 81 c1 ff 07 00 00 c1 e9 03 0f b6 c9 89 ca 09 c2 74 35 55 48 89 e5 c7 45 fc 59 58 5c 5e 8a 4c 0d fc 88 0d 15 00 00 00 f3 0f 2a c8 83 f8 02 5d 7c 1f ff c8 0f 57 c0 f3 0f 2a c0 f3 0f 5e c1 83 f8 01 0f 28 c8 7f eb c3 f3 0f 10 05 03 01 00 00 c3 0f 28 c1 c3

Why would interpreted languages be able to dynamically run code with fancy evals, but not plain machine code?

Try it with:

#include <stdio.h>
#include <sys/mman.h>
#include <errno.h>

char ff[] = "\x0f\xb6\x0f\x31\xc0\xeb\x11\x0f\xbe\xc9\x8d\x04\x80\x8d\x44\x41\xd0\x0f\xb6\x4f\x01\x48\xff\xc7\x83\xf9\x21\x75\xea\xb9\x21\x21\x21\xa1\x33\x0f\x0f\xbc\xc9\x81\xc1\xff\x07\x00\x00\xc1\xe9\x03\x0f\xb6\xc9\x89\xca\x09\xc2\x74\x35\x55\x48\x89\xe5\xc7\x45\xfc\x59\x58\x5c\x5e\x8a\x4c\x0d\xfc\x88\x0d\x15\x00\x00\x00\xf3\x0f\x2a\xc8\x83\xf8\x02\x5d\x7c\x1f\xff\xc8\x0f\x57\xc0\xf3\x0f\x2a\xc0\xf3\x0f\x5e\xc1\x83\xf8\x01\x0f\x28\xc8\x7f\xeb\xc3\xf3\x0f\x10\x05\x03\x01\x00\x00\xc3\x0f\x28\xc1\xc3";
int main()
{
    char* page = (char*)((unsigned long)((char*)ff) & (~0xfffLL));
    if (mprotect(page, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC) < 0) {
        perror("mprotect");
        return -1;
    }
    float (*f)(char*) = (float (*)(char*))ff;
    char* testcases[] = { "0!","1!","2!","3!","4!","5!","6!","7!","8!","9!","10!",
                          "0!!","1!!","2!!","3!!","4!!","5!!","6!!","7!!","8!!","9!!","10!!",
                          "0!!!","1!!!","2!!!","3!!!","4!!!","5!!!","6!!!","7!!!","8!!!","9!!!","10!!!",
                          "0!!!!","1!!!!","2!!!!","3!!!!","4!!!!","5!!!!","6!!!!","7!!!!","8!!!!","9!!!!","10!!!!",
                        };
    for (int i = 0; i < 44; i++) {
        printf("%s -> %f\n", testcases[i], f(testcases[i]));
    }
}

Assembly:

_f:
100000d4f:  0f b6 0f    movzx   ecx, byte ptr [rdi]
100000d52:  31 c0   xor eax, eax
100000d54:  eb 11   jmp 17 <_f+18>
100000d56:  0f be c9    movsx   ecx, cl
100000d59:  8d 04 80    lea eax, [rax + 4*rax]
100000d5c:  8d 44 41 d0     lea eax, [rcx + 2*rax - 48]
100000d60:  0f b6 4f 01     movzx   ecx, byte ptr [rdi + 1]
100000d64:  48 ff c7    inc rdi
100000d67:  83 f9 21    cmp ecx, 33
100000d6a:  75 ea   jne -22 <_f+7>
100000d6c:  b9 21 21 21 a1  mov ecx, 2703302945
100000d71:  33 0f   xor ecx, dword ptr [rdi]
100000d73:  0f bc c9    bsf ecx, ecx
100000d76:  81 c1 ff 07 00 00   add ecx, 2047
100000d7c:  c1 e9 03    shr ecx, 3
100000d7f:  0f b6 c9    movzx   ecx, cl
100000d82:  89 ca   mov edx, ecx
100000d84:  09 c2   or  edx, eax
100000d86:  74 35   je  53 <_f+6E>
100000d88:  55  push    rbp
100000d89:  48 89 e5    mov rbp, rsp
100000d8c:  c7 45 fc 59 58 5c 5e    mov dword ptr [rbp - 4], 1583110233
100000d93:  8a 4c 0d fc     mov cl, byte ptr [rbp + rcx - 4]
100000d97:  88 0d 15 00 00 00   mov byte ptr [rip + 21], cl
100000d9d:  f3 0f 2a c8     cvtsi2ss    xmm1, eax
100000da1:  83 f8 02    cmp eax, 2
100000da4:  5d  pop rbp
100000da5:  7c 1f   jl  31 <_f+77>
100000da7:  ff c8   dec eax
100000da9:  0f 57 c0    xorps   xmm0, xmm0
100000dac:  f3 0f 2a c0     cvtsi2ss    xmm0, eax
100000db0:  f3 0f 5e c1     divss   xmm0, xmm1
100000db4:  83 f8 01    cmp eax, 1
100000db7:  0f 28 c8    movaps  xmm1, xmm0
100000dba:  7f eb   jg  -21 <_f+58>
100000dbc:  c3  ret
100000dbd:  f3 0f 10 05 03 01 00 00     movss   xmm0, dword ptr [rip + 259]
100000dc5:  c3  ret
100000dc6:  0f 28 c1    movaps  xmm0, xmm1
100000dc9:  c3  ret

Explanations will be added later. The basic idea is to modify the divss xmm0, xmm1 instruction at 0x100000db0 and replace it with a mulss, addss, subss or divss according to supplied operand. A small trick is also used to parse the input string.

Assembly generated with:

float f (char* s)
{
    int x;
    for (x=0; *s != '!'; s++) {
        x=10*x + (*s-'0');
    }
    unsigned char op = (__builtin_ctz(*(unsigned int *)s ^ 0xa1212121)-1) >> 3;
    if (x == 0 && op == 0) {
        return 1;
    }
    unsigned int lookup = 0x5e5c5859;
    unsigned char new_code = ((unsigned char*)&lookup)[op];
    asm("movb %0, 0x15(%%rip)" : : "r" (new_code));
    float sum;
    for (sum = x--; x>0; x--) {
        sum = x / sum;
    }
    return sum;
}
\$\endgroup\$
2
\$\begingroup\$

Haskell, 105 102 98 96 bytes

0!3=0
x!y=foldr([(*),(+),(-),(/)]!!y)([1,0,0,1]!!y)[1..x]
f s|[(n,b)]<-lex s=read n!(length b-1)

Saved 9 bytes thanks to Zgarb and nimi.

Try it online.

\$\endgroup\$
  • \$\begingroup\$ @Zgarb You are right. Fixed. \$\endgroup\$ – Cristian Lupascu Aug 3 '17 at 11:30
  • \$\begingroup\$ I think you can also drop the parens around read n, and f= is unnecessary as per our rules. \$\endgroup\$ – Zgarb Aug 3 '17 at 11:34
  • \$\begingroup\$ @Zgarb Right again :) . Thanks! \$\endgroup\$ – Cristian Lupascu Aug 3 '17 at 11:36
  • \$\begingroup\$ Switching back to a named function and using lex saves two bytes: f s|[(n,b)]<-lex s=read n!(length b-1). \$\endgroup\$ – nimi Aug 3 '17 at 16:06
  • \$\begingroup\$ @nimi Wow, thanks! I'm so new to Haskell that I didn't even know about lex. That's awesome! :) I don't see how that saves bytes though - I get 99 bytes after this. \$\endgroup\$ – Cristian Lupascu Aug 4 '17 at 6:28
1
\$\begingroup\$

Gaia, 26 25 bytes

ẋ)@d┅v;l“×+⁻÷”=“ₔ⊢”+e¤ḥ!∨

Try it online!

Explanation

ẋ                          Split the input into runs of the same character.
 )                         Get the last one (the !'s).
  @                        Push an input (since there's none left, use the last one).
   d                       Parse as number (ignores the !'s).
    ┅v                     Get the reverse range: [n .. 1]
      ;                    Copy the ! string
       l“×+⁻÷”=            Get its length and index into this string of operators.
               “ₔ⊢”+       Append 'ₔ⊢' to the operator.
                    e      Eval the resulting string, which is "reduce by <operator> with
                            swapped arguments." Reducing an empty list gives 0.
                     ¤     Bring the !'s back to the top.
                      ḥ!   Remove the first character and check if it's empty.
                        ∨  Logical OR; turns 0 from 0! to 1, doesn't change anything else.
\$\endgroup\$
1
\$\begingroup\$

Jelly, 28 bytes

×
+
_
÷
³ċ”!
ḟ”!VRṚ¢ŀ@/¢Ị¤¹?

Try it online!

Got the idea of separating the links into lines from Jonathan Allan's answer for -2 bytes.

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

APL (Dyalog), 30 bytes

Inspired by lstefano's solution.

{0::0⋄(⍎'×+-⌹'⊃⍨≢⍵~⎕D)/⍳⍎⍵∩⎕D}

Try it online!

{} anonymous function where the argument is represented by :

0:: if any error happens:

  0 return zero

 now try:

  ⍵∩⎕D the intersection of the argument and the set of Digits (removes exclamation points)

   execute that (turns it into a number)

  ɩndices of that

  ()/ insert (APL is right associative, as needed) the following function between terms:

   ⍵~⎕D argument without Digits (leaves exclamation points)

   tally that (i.e. how many exclamation points)

  '×+-⌹'⊃⍨ use that to pick from the list of symbols*

   execute (turns the symbol into a function)


(matrix division) is used instead of ÷ (normal division) to cause an error on an empty list

\$\endgroup\$
  • \$\begingroup\$ What does :: do in a dfn? \$\endgroup\$ – Zacharý Aug 4 '17 at 22:18
  • \$\begingroup\$ It is an error guard. If at any point after the error guard is set up, an error with any of the numbers (0=1…999, 1000=1001…) to the left of the :: happens, then the value to the right of the :: is immediately returned. \$\endgroup\$ – Adám Aug 5 '17 at 22:00
  • \$\begingroup\$ Well, I never knew about that, thanks! \$\endgroup\$ – Zacharý Aug 5 '17 at 22:20
0
\$\begingroup\$

Perl 5, 96 bytes

s/(\d+)//;@a=1..$1;$"=qw|* + -( /(|[$l=-1+length];$_=$1?"@a".($l>1?')'x($1-1):''):$l?0:1;$_=eval

Try it online!

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

Dyalog APL, at least 29 chars

{(⍎i⊃'×+-÷')/⍳⍎⍵↓⍨-i←+/'!'=⍵}

The expression is ALMOST correct. It passes all the test cases EXCEPT 0!!!! for which it gives 1 instead of the required 0 and that's because in APL the reduction of an empty vector is supposed to return the neutral element for the function used to reduce. For the quotient that's 1. At the moment I don't have time to try and fix it but I'll leave it here for a rainy day.

\$\endgroup\$
  • \$\begingroup\$ It is raining: {0::0⋄(⍎'×+-⌹'⊃⍨≢⍵~⎕D)/⍳⍎⍵∩⎕D} Try it online! \$\endgroup\$ – Adám Aug 3 '17 at 17:56
  • \$\begingroup\$ Very cool! I don't mind at all if you claim it as your solution, given that the differences are more than the similarities. \$\endgroup\$ – lstefano Aug 4 '17 at 7:53
  • \$\begingroup\$ Done. \$\endgroup\$ – Adám Aug 4 '17 at 8:05
0
\$\begingroup\$

05AB1E, 25 24 bytes

þDLðýs¹'!¢<"*+-/"ès<×J.V

Try it online!

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

Mathematica, 152 bytes

(T=ToExpression;If[#=="0!!!!",0,s=T@StringCount[#,"!"];t=T@StringDrop[#,-s];{#!,i~Sum~{i,#},Sum[-i(-1)^i,{i,#}],N@Product[1/i^(-1)^i,{i,#}]}[[s]]&[t]])&
\$\endgroup\$
0
\$\begingroup\$

Javascript, 111 163 bytes

s=>([a,b]=s.split(/\b/),c=b.length,a==0&c==1||eval((p=[...Array(+a+1).keys()].slice(1).join(c-1?c-2?c-3?'/(':'-(':'+':'*'))+')'.repeat((p.match(/\(/g)||[]).length)))

Readable Version

s=>([a,b]=s.split(/\b/),c=b.length,a==0&c==1||eval((p=
[...Array(+a+1).keys()].slice(1).join(c-1?c-2?c-3?'/(':'-
(':'+':'*'))+')'.repeat((p.match(/\(/g)||[]).length)))
\$\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.