195
\$\begingroup\$

In mathematics an exclamation mark ! often means factorial and it comes after the argument.

In programming an exclamation mark ! often means negation and it comes before the argument.

For this challenge we'll only apply these operations to zero and one.

Factorial
0! = 1
1! = 1

Negation
!0 = 1
!1 = 0

Take a string of zero or more !'s, followed by 0 or 1, followed by zero or more !'s (/!*[01]!*/).
For example, the input may be !!!0!!!! or !!!1 or !0!! or 0! or 1.

The !'s before the 0 or 1 are negations and the !'s after are factorials.

Factorial has higher precedence than negation so factorials are always applied first.
For example, !!!0!!!! truly means !!!(0!!!!), or better yet !(!(!((((0!)!)!)!))).

Output the resultant application of all the factorials and negations. The output will always be 0 or 1.

Test Cases

0 -> 0
1 -> 1
0! -> 1
1! -> 1
!0 -> 1
!1 -> 0
!0! -> 0
!1! -> 0
0!! -> 1
1!! -> 1
!!0 -> 0
!!1 -> 1
!0!! -> 0
!!!1 -> 0
!!!0!!!! -> 0
!!!1!!!! -> 0

The shortest code in bytes wins.

\$\endgroup\$
18
  • 27
    \$\begingroup\$ But 0!=1!, so what's the point of handling multiple factorials? \$\endgroup\$
    – boboquack
    Feb 6, 2017 at 9:22
  • 39
    \$\begingroup\$ @boboquack Because that's the challenge. \$\endgroup\$ Feb 6, 2017 at 9:24
  • 14
    \$\begingroup\$ <?='1'; ... correct 75% of the time in php. \$\endgroup\$
    – aslum
    Feb 6, 2017 at 17:17
  • 13
    \$\begingroup\$ I may be wrong here but can't any number with any factorials after it simply be removed and replaced with 1? Like 0!!!! = 1!! = 0!!!!!!!! = 1!!! = 1! = 0! = 1 etc \$\endgroup\$ Feb 6, 2017 at 22:33
  • 3
    \$\begingroup\$ @AlbertRenshaw That is correct. \$\endgroup\$ Feb 6, 2017 at 22:54

64 Answers 64

46
\$\begingroup\$

Mathematica, 25 17 bytes

Input[]/.!x_:>1-x

Takes input from a user prompt. Assumes Mathematica's notebook environment for implicit printing. To make it a command-line script, wrap it in Print[...] or to make it an argumentless function (which then takes input from the prompt), append &.

Mathematica has both of the required operators (with the required precedence), so we can just "eval" the input (which is done automatically by Input[]), but the logical negation operator doesn't work on integers (so it will remain unevaluated). If there's a !x left in the result, we replace it with 1-x.

A couple of fun facts about the evaluation:

  1. Mathematica actually also has the double factorial operator !!, which computes n*(n-2)*(n-4)*..., but applied to 0 or 1 it still gives 1, so it doesn't matter that 0!!!!! will actually be parsed as ((0!!)!!)!.
  2. Even though Mathematica leaves !0 and !1 unevaluated, it does know that ! is self-inverse, so it will automatically cancel all pairs of leading !. After the ToExpression we're always left with one of 0, 1, !0, !1.
\$\endgroup\$
5
  • 3
    \$\begingroup\$ Since when was a REPL snippet allowed by default? \$\endgroup\$ Feb 7, 2017 at 12:26
  • 2
    \$\begingroup\$ @LegionMammal978 Apparently since December 2015, but I keep forgetting about it. To be fair, it's not a "snippet" in that it doesn't assume that the input is already stored somewhere in memory. And assuming the notebook environment is then not very different from having a language with implicit output. \$\endgroup\$ Feb 7, 2017 at 12:28
  • \$\begingroup\$ Just curious, could a meta link be provided? (Trying to find information there is stressful, yet another problem of the SE Q&A format...) \$\endgroup\$ Feb 8, 2017 at 2:04
  • \$\begingroup\$ @LegionMammal978 it's already in the answer. \$\endgroup\$ Feb 8, 2017 at 6:57
  • \$\begingroup\$ Pure ksh solution x=${x/[01]!*/1};echo $(($x)) - not allowed to post a proper answer :( \$\endgroup\$
    – user17752
    Feb 9, 2017 at 1:45
31
\$\begingroup\$

Bash + Unix utilities, 21 17 bytes

sed s/.!!*$/1/|bc

Verify the test cases online!

Added a TIO link to the test suite.

This must be saved in a file and run as a program. If you try to enter the command directly from the command line, it won't work because !! is expanded due to history substitution being enabled in bash's interactive mode. (Alternatively, you can turn history substitution off with set +H.)

\$\endgroup\$
9
  • \$\begingroup\$ The old version works, this one doesn't \$\endgroup\$
    – user41805
    Feb 6, 2017 at 9:37
  • \$\begingroup\$ I used the TIO link \$\endgroup\$
    – user41805
    Feb 6, 2017 at 9:40
  • \$\begingroup\$ @KritixiLithos It worked fine when I tried it on my Linux box. The problem was apparently that TIO requires a newline at the end of the simulated input line. It's a confusing situation, so I took out the TIO link. If you want to try it out there, here's the link again (but be sure to include a newline at the end of the input if you change the input to test it out): tio.run/nexus/bash#@1@cmqJQrK@nqKilom@oX5OU/P@/… \$\endgroup\$ Feb 6, 2017 at 9:53
  • 2
    \$\begingroup\$ But what if someone has run mkdir -p 's/.!!'{bunch,of,different,directories}\$/1? Then you'll get Pathname Expansion and Sed will be attempting to read directories as though they were files, instead of reading standard input, and it won't output anything! :) \$\endgroup\$
    – Wildcard
    Feb 7, 2017 at 9:13
  • 1
    \$\begingroup\$ @Wildcard I agree completely. In production scripts, I always use quotes in situations like this. (In this case, I would actually put double-quotes around the argument to sed, rather than just escaping the *. It's easier to read than using backslashes, and it avoids the possibility of missing some special character.) \$\endgroup\$ Feb 7, 2017 at 9:32
25
\$\begingroup\$

Retina, 20 15 14 bytes

Thanks to Leo for saving 1 byte.

0!
1
!!

^1|!0

Try it online!

Explanation

0!
1

Turn 0! into 1. We don't care about any other trailing !s, the resulting number is the same as if we had applied all factorials.

!!

Cancel pairs of negations. This may also cancel some factorials, but that's irrelevant.

^1|!0

Count the number of matches of this regex, which is either 1 or 0 and gives the desired result.

\$\endgroup\$
3
  • \$\begingroup\$ Alternate solution for same bytecount: \d.+... \$\endgroup\$
    – user41805
    Feb 6, 2017 at 9:15
  • \$\begingroup\$ @KritixiLithos Found a way to avoid that altogether. \$\endgroup\$ Feb 6, 2017 at 10:07
  • \$\begingroup\$ You can remove the ^ before !0 \$\endgroup\$
    – Leo
    Feb 6, 2017 at 12:53
19
\$\begingroup\$

Grime, 14 12 9 bytes

e`\0!~\!_

Try it online!

Explanation

This matches the input against a pattern, printing 1 for match and 0 for no match.

e`\0!~\!_
e`         Match entire input against this pattern:
    !      not
  \0       a sole 0
     ~     xor
      \!   exclamation mark
        _  followed by this pattern matched recursively.

The idea is this. If the input begins with a digit, then the recursive part \!_ always fails, and \0! succeeds unless we have a single 0. Their xor succeeds unless the input is a single 0. If the input begins with a !, then \0! always succeeds, and \!_ succeeds if the recursive match succeeds. Their xor succeeds exactly when the recursive match fails, thus negating it.

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

Brainfuck, 85 72 (84) bytes

,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]<+.

to return numerically, or

,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]-[-----<+>]<--.

for ASCII text. > may also be prefixed to avoid memory wrapping.

Try it online!


Loops over the input.
On 1, ends.
On "!", toggles bool a stored as 0 or 255.
On "0", toggles if there is no trailing bit, then ends.

Memory labels  | BOOL | INPUT | FLAG |

,                   first input 
[                     # loop on INPUT
  >-[-----<->]<++     subtract 49 == "1"

  [                     # case not "1"
    >++++[-<++++>]      add 16 since 49 take 16 == "!"

    +                   set FLAG
    <                   move to INPUT
    [                     # case "0"
      [+],                clear and new INPUT
      [                     # case "0!"
        [-]>-<              clear INPUT and FLAG
      ]
    ]
  ]

  >                   move to FLAG
  [                     # case "!" or "0" without tail
    <<+[-->]>[<]        not the BOOL
    ,                   take new input
    >-                  clear FLAG
  ]
  <                   move to INPUT
]

+.                    return 0 or 1

Or for text response, replace the last line with

-[-----<+>]<--.       add 49 for "0" or "1" conversion and return
\$\endgroup\$
16
\$\begingroup\$

Brainfuck - way to many bytes (232 bytes)

Clearly the wrong language for winning in code golf. Mainly I noticed a lack of anyone using this esolang. There is a good online interpreter bf interpeter or you can actually watch what the program does using this bf visualizer.

>>>>>,[>+++[<---------------->-]<<<<<<[-]+>[-]>>>>[-[<<[>+<<<<->>>[<<+>>-] ]<<[>>+<<-]<[>>+<<[-]]>>>>>[-]]<<<<<[>>>++<<<-]>+>>>>[-]]<<<<-[>>+<<[-]]>>>>,]<<->[<[-]+>[-]]<<[<[-]>>[<<+>>[-]]+<<[->>-<<]>-]>>[-]+++[<++++++++++++++++>-]<.
\$\endgroup\$
3
  • 3
    \$\begingroup\$ You crazy man!! \$\endgroup\$
    – Almo
    Feb 8, 2017 at 23:20
  • \$\begingroup\$ Love it, can you do that in malbolge? XD \$\endgroup\$ Feb 10, 2017 at 4:36
  • \$\begingroup\$ Information: There are too much shorter solutions below. \$\endgroup\$
    – DELETE_ME
    Apr 21, 2018 at 7:04
15
\$\begingroup\$

Python, -44- 42 bytes

Saved 2 bytes thanks to Zgarb!

lambda x:(x[-1]=='0')^len(x.rstrip('!'))%2

Step by step:

  1. x[-1]!='0'
    if x ends with 1 or !x doesn't end with 0, the factorial portion must have value 1, else 0
  2. ^len(x.rstrip('!'))%2
    exploit xor's property as a "conditional not". The condition in this case is if the length of initial !s is odd. However, .rstrip doesn't remove the number from the string so the length calculated is offset by 1, therefore the condition is inverted
  3. The offset by 1 in step 2 is corrected by changing != to == in step 1. Zgarb suggested using a difference comparison operator rather than applying another inversion, saving 2 bytes.

Try it online!

\$\endgroup\$
7
  • \$\begingroup\$ Fails on an input of !!0; it is currently returning 1. \$\endgroup\$
    – Value Ink
    Feb 6, 2017 at 9:45
  • \$\begingroup\$ @ValueInk should be working now \$\endgroup\$
    – busukxuan
    Feb 6, 2017 at 9:55
  • 1
    \$\begingroup\$ lambda x:(x[-1]=='0')^len(x.rstrip('!'))%2 avoids the extra inversion. \$\endgroup\$
    – Zgarb
    Feb 6, 2017 at 11:18
  • 17
    \$\begingroup\$ crossed out 44 is still regular 44 \$\endgroup\$
    – Riker
    Feb 6, 2017 at 15:23
  • 4
    \$\begingroup\$ I think he's stating that a crossed out 44 in the font used doesn't look crossed out... :) The cross out portion overlaps with the horizontal portion of the 4s. \$\endgroup\$
    – JeffC
    Feb 9, 2017 at 16:12
13
\$\begingroup\$

JavaScript (ES6), 43 41 29 bytes

s=>+eval(s.replace(/.!+$/,1))

Non-regex method (41 31 bytes)

Below is my initial approach. It's slightly more interesting, but significantly longer still a bit longer even after a significant optimization by Neil (10 bytes saved).

f=([c,...s])=>1/c?c|s>'':1-f(s)

Test cases

let f =

s=>+eval(s.replace(/.!+$/,1))

;[
  "0", "1", "0!", "1!", "!0", "!1", "!0!", "!1!", "0!!",
  "1!!", "!!0", "!!1", "!0!!", "!!!1", "!!!0!!!!", "!!!1!!!!"
].map(
  s => console.log(s, '=>', f(s))
)

\$\endgroup\$
3
  • \$\begingroup\$ I can only save 10 bytes from your non-regex method, so it's still too long: f=([c,...s])=>1/c?c|s>'':1-f(s). \$\endgroup\$
    – Neil
    Feb 6, 2017 at 13:41
  • \$\begingroup\$ @Neil Since it's much better than my 1st attempt anyway, I took the liberty to include your suggestion. \$\endgroup\$
    – Arnauld
    Feb 6, 2017 at 14:19
  • \$\begingroup\$ Ha, I had the same idea but you golfed it better. :) \$\endgroup\$
    – Devsman
    Feb 8, 2017 at 15:23
13
\$\begingroup\$

Retina, 13 bytes

A somewhat weird approach, but it's short and it works.

0$
!1
!!

^\d

With the first two lines we replace an ending 0 with !1: with this replacement we now know that the part of our string from the digit onwards is equal to 1.

Next two lines, remove pairs of !: double negation erases itself, and we already accounted for factorial with the previous step.

Last line, match a digit at the start of the string and return the number of matches: if the negations have all been eliminated we'll find a match (and as we said before we know this is equal to 1), if there's still a negation this won't match.

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Wouldn't the final digit necessarily always be a 1? In that case, you could use 1 rather than \d. \$\endgroup\$
    – user62131
    Feb 6, 2017 at 22:39
  • 1
    \$\begingroup\$ @ais523 no, because the first part will only replace an ending 0, so for example the input 0! will stay unchanged until the last line \$\endgroup\$
    – Leo
    Feb 6, 2017 at 23:07
  • 2
    \$\begingroup\$ Really lovely solution, nice work! :) \$\endgroup\$ Feb 6, 2017 at 23:32
13
\$\begingroup\$

Jelly, 5 bytes

VeMḂ$

Try it online!

Monadic function expecting a string. Inputs with leading !s cause a 1 to be printed to STDOUT along the way, so the TIO link I give is a test harness that prints the input-output pairs beneath the first line of output.

How?

VeMḂ$ - Monadic link: string
V     - eval the string
          - the implicit input of 0 causes !...! to evaluate to 1 (which gets printed),
          - the result is the evaluation of the rest: "0"=0; "0!"=1; "1"=1; "1!"=1; ...
 e    - exists in?
    $ - last two links as a monad:
  M   -     Maximal indexes - the "0" and "1" characters are greater than "!",
                            - so this results in a list of one item [i] where
                            - i is the 1-based index of the 0 or 1 character.
   Ḃ  -     %2 (vectorises) - [i%2], so a 0 if we need to logically negate and a 1 if not
                            - hence we check equality with e rather than inequality.
\$\endgroup\$
11
\$\begingroup\$

05AB1E, 9 bytes

Code:

.V¹'!ÜgG_

Uses the CP-1252 encoding. Try it online! or Verify all test cases!

Explanation:

.V         # Evaluate the input as 05AB1E code. This computes the factorial part.
   '!Ü     # Remove trailing exclamation marks..
  ¹        # ..from the first input
      g    # Get the length of the resulting string
       G   # Do the following length - 1 times:
        _  #   Negate the number
\$\endgroup\$
10
\$\begingroup\$

Ruby, 12+1 = 39 24 15 13 bytes

Uses the -n flag. Thanks to @GB for -9 bytes!

p~/!*$|0$/%2
\$\endgroup\$
7
  • \$\begingroup\$ Since you only check the length, you can delete the trailing zero, instead of checking "!0" first and a single zero after that. \$\endgroup\$
    – G B
    Feb 7, 2017 at 8:10
  • \$\begingroup\$ @GB that's a wonderful idea! However, I found a solution that's even shorter by modifying my regex to look for the position of 0 or end-of-line \$\endgroup\$
    – Value Ink
    Feb 7, 2017 at 9:25
  • \$\begingroup\$ Then you could just check for trailing '!' or zero or end of line: p~/!+$|0$|$/%2 is just 14 bytes. \$\endgroup\$
    – G B
    Feb 7, 2017 at 9:39
  • \$\begingroup\$ And then "0$|$" could become "0?$" to save another byte. \$\endgroup\$
    – G B
    Feb 7, 2017 at 14:51
  • 1
    \$\begingroup\$ Better yet !*$ is shorter by two! \$\endgroup\$
    – Value Ink
    Feb 7, 2017 at 18:03
9
\$\begingroup\$

Perl, 20 bytes

19 bytes of code + -p flag.

s/\d!+/1/;$_=0+eval

Try it online!

Perl's negation returns undef or 1, so I use 0+ to numerify the result 0+undef returns 0. Besides that, not much to say about the code.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Just wrote exactly this. Have a +1. \$\endgroup\$
    – primo
    Feb 7, 2017 at 9:26
  • \$\begingroup\$ @primo Glad to see that for once I'm not 20 bytes behind you! Thanks :) \$\endgroup\$
    – Dada
    Feb 7, 2017 at 9:59
8
\$\begingroup\$

Haskell, 27 bytes

f('!':b)=1-f b
f"0"=0
f _=1

Try it online!

Each leading ! complements the output for the rest of the expression, done as 1-. We keep flipping until we hit a digit. If the remaining is just "0", the result is 0. Otherwise, it's a 1 or is followed by one or more !, so the result is 1.

\$\endgroup\$
8
\$\begingroup\$

C, 68 62 61 53 bytes

c;e(char*a){for(c=1;*a<34;a++)c^=1;c=a[1]?c:*a&1^!c;}

Squeezed out a few more bytes with some abuse

Try it online!

\$\endgroup\$
7
  • 1
    \$\begingroup\$ I think you can remove the int from the function and you can change the *a==33 to *a<34. \$\endgroup\$
    – user41805
    Feb 6, 2017 at 18:18
  • \$\begingroup\$ Alas *a%2 is shorter than *a-48 \$\endgroup\$
    – user41805
    Feb 6, 2017 at 18:22
  • \$\begingroup\$ Thanks for the tip. I was also able to eliminate another character by removing the brackets around the return and assigning it. \$\endgroup\$
    – Ahemone
    Feb 6, 2017 at 22:30
  • \$\begingroup\$ I am pretty sure for(;*a<34;a++) can be shortened to for(;*a++<34;) saving 1 byte \$\endgroup\$ Feb 6, 2017 at 22:34
  • \$\begingroup\$ Unfortunately not, as the conditional statement it will always execute and so will push the pointer too far ahead for the return dereference. \$\endgroup\$
    – Ahemone
    Feb 6, 2017 at 22:40
7
\$\begingroup\$

Haskell, 39 bytes

f('!':b)="10"!!read[f b]
f[a]=a
f _='1'

Defines a function f, which takes a string and returns a character. Try it online!

Explanation

There are three cases: input begins with !, input has length 1, and everything else.

f('!':b)=    -- If input has head '!' and tail b,
 "10"!!      -- we index into the string "10"
  read[f b]  -- using f b converted to int. This essentially inverts f b.
f[a]=        -- If input has only one character, we know it's a digit,
 a           -- so we can just return it.
f _=         -- In all other cases, we know the input is a digit followed by !s,
 '1'         -- so we can return '1'.
\$\endgroup\$
1
  • \$\begingroup\$ Switch from String to Integer as the return type: f('!':b)=[1,0]!!f b;f"0"=0;f _=1. \$\endgroup\$
    – nimi
    Feb 6, 2017 at 20:24
6
\$\begingroup\$

Perl 6, 32 28 23 bytes

{m/(\!)*(1|0.)*/.sum%2}

How it works

{                     }  # A lambda.
{m/            /      }  # Match the lambda argument against the regex:
   (\!)*                 #   Zero or more `!`.
                         #     (First capture will be an array with one element per negation).
        (1|0.)*          #   A `1`, or a `0` and another character, zero or more times.
                         #     (Second capture will be a one-element array if the factorial
                         #     part evaluates to 1, and an empty array otherwise.)
                .sum     # Add the lengths of the two captures,
                    %2   # and return that sum modulo 2.
\$\endgroup\$
6
\$\begingroup\$

Befunge, 24 bytes

~"!"-:#v_$1+
*+2%!.@>0~`

Try it online!

This starts by counting the number of ! characters read from stdin. The first character that isn't a ! will either be a 0 or 1, but in the process of testing for ! we will have subtracted 33, making it either 15 or 16. We then read one more character, that will either be an ! or EOF, and compare if that is less than 0 (i.e. EOF).

Taking those three data points - the exclamation count (c), the digit value, (d), and the end-of-file condition (e) - we can calculate the result as follows:

!((c + d*e) % 2)

Multiplying the digit value by the end-of-file condition means it will be converted to zero if the digit was followed by a !, thus giving it the same modulo 2 value as a 1 (which remember has been converted to 16). But before applying the modulo 2, we add the initial exclamation count, which effectively toggles the modulo 2 result as many times as their were ! prefixes. And finally we not the result since our baseline values for 0 and 1 are the opposite of what we need.

Looking at the code in more detail:

~                Read a character from stdin.
 "!"-            Subtract 33 (ASCII for '!').
     :  _        Make a duplicate and check if zero (i.e. is it a '!').
         $1+     If so, drop the duplicate, increment a counter, and repeat.
       v         Otherwise move to the second line, leaving the digit value on the stack.
       >0~`      Read one more character and check if less than 0 (i.e. EOF).
*                Multiple by the digit value, making it zero if not followed by EOF.
 +               Add to the exclamation count.
  2%             Modulo 2 the result.
    !            Then not that value.
     .@          And finally write to stdout and exit.
\$\endgroup\$
6
\$\begingroup\$

Ruby, 22 21 20 bytes

->s{(s=~/!*$|0$/)%2}

Explanation:

  • First case, I got some '!' at the end, remove them, get length modulo 2.
  • Second case, no '!', if last character is zero then remove it, get length modulo 2
  • If the last character is 1, back to the first case

(-1 byte stealing @Value Ink's idea)

\$\endgroup\$
1
  • \$\begingroup\$ Awesome, I looked at this puzzle for 10 minutes but had not much time and then forgot about it. Now spotted it again in active questions and was delighted to see such a nice approach. \$\endgroup\$ Feb 13, 2017 at 7:54
5
\$\begingroup\$

Python, 38 bytes

lambda s:(s[1::2]>s[::2])^ord(s[-1])%2

TryItOnline!

An unnamed function taking an input string s and returning an integer 0 or 1.

s[1::2] is a slice of the input string that starts at index 1 and has a step size of two:
'Like this' -> 'ieti'

s[::2] is similar but starts at the default index of 0:
'Like this' -> 'Lk hs'

The test (s[1::2]>s[::2]) checks if the 0-based index of the '0' or '1' is odd, i.e. if we need to complement.
This works because the ordering of strings is checked lexicographically with any non-empty string greater than the empty string, and with ASCII ordering, so '1'>'0'>'!'. This is a byte shorter than the simpler s.index(max(s))%2.

The ord(s[-1])%2 checks to see if the last character is not a '0' (for valid input), and results in an integer (whereas the same length (s[-1]!='0') would return a boolean).
This works because the last character of the input, s[-1], will be a '0', '1', or '!' which have ASCII code points 48, 49, and 33 respectively, which are 0, 1, and 1 modulo 2.

The ^ then performs a bitwise exclusive or operation on the two above values, returning an integer since one input, the right one, is an integer. If the left is True the complement of the right is returned, if the left is False the right is returned, as required.

\$\endgroup\$
5
+100
\$\begingroup\$

APL (Dyalog Extended), 21 bytes

⍎⌽'!(\d.*)'⎕R'\1~'⍣≡⍞

Repeatedly shift any !s to the right with the fixpoint ⍣≡

!!!!0! -> !!!0!~ -> !!0!~~ -> !0!~~~ -> 0!~~~~

Then reverse with ⌽, and execute with ⍎

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Your regex can be a byte shorter. \$\endgroup\$
    – user41805
    Sep 15, 2021 at 8:17
  • \$\begingroup\$ @user41805 how? \$\endgroup\$
    – rak1507
    Sep 15, 2021 at 9:44
  • 1
    \$\begingroup\$ I think ^!(.*) works \$\endgroup\$
    – user41805
    Sep 15, 2021 at 9:53
5
\$\begingroup\$

///, 27 bytes

/0!/1//!!///!1/0//!0/1//!//

Try it online!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ I love me a /// answer. Here's some -16 bytes! \$\endgroup\$
    – AviFS
    Sep 15, 2021 at 5:13
  • \$\begingroup\$ @AviFS Thanks, I don't know why I thought that part was neccesary! \$\endgroup\$
    – nph
    Sep 16, 2021 at 20:33
  • 1
    \$\begingroup\$ You can remove the /1!/1/ and clear the !s at the end instead \$\endgroup\$
    – Jo King
    Sep 17, 2021 at 21:39
  • 1
    \$\begingroup\$ @JoKing That's a great point; totally slipped me by as well! \$\endgroup\$
    – AviFS
    Sep 17, 2021 at 22:06
4
\$\begingroup\$

Jelly, 8 bytes

œr”!LḂ=V

Try it online!

This is a function (monadic link) that takes one argument and returns via its return value. (It also often writes junk to standard output as a side effect, but we don't care about that.)

Explanation

œr”!LḂ=V
œr”!      Take {the input}, with all trailing ! deleted
    L     Take the length of this
     Ḃ    Take the parity of that length
      =   Return 0 if unequal, 1 if equal to:
       V    the value of {the input} when eval'ed as a niladic Jelly program

First, note that as the input always consists of some number of !, followed by a digit, followed by more !, that if we delete the trailing ! and take the length, we'll end up with one plus the number of leading ! in the program. Taking the parity of this will return 0 if there were an odd number of !, or 1 if there were an even number of !. Comparing to 0 is a "not" function, whereas comparing to 1 is the identity function; thus œr”!LḂ= effectively implements the "treat leading ! as NOT operators" part of the question.

As for the second half, handling factorials, ! is a factorial operation in Jelly, so if the program has no leading !, we can solve the problem directly with a simple eval (V). If the program does have leading !, those will be interpreted as taking the factorial of 0 (possibly multiple times), producing a return value of 1, which will be printed to standard output and discarded once a digit is seen; thus, they have no impact on the return value of the function that's my submission to the question.

\$\endgroup\$
1
  • \$\begingroup\$ Very nice and great explanation. \$\endgroup\$
    – ElPedro
    Feb 6, 2017 at 21:48
4
\$\begingroup\$

Java 7, 105 82 81 bytes

int a(char[]a){int b=0,c=0;for(;a[b++]<34;c^=1);return(b<a.length?1:a[b-1]&1)^c;}

Try it online!

Old regex-ish solution

int a(String a){a=a.replace("0!","1").replaceAll("1.*","1");int b=a.length()-1;return b%2^a.charAt(b)&1;}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ c^=1 is super clever. That's an unused operator if ever I've seen one. \$\endgroup\$ Feb 9, 2017 at 8:19
3
\$\begingroup\$

CJam, 12 11 bytes

r_W='0=!\~;

Try it online! Test suite (prints a 1 for each correct test case).

r      e# Read input.
_W='0= e# Duplicate and check whether the string ends in '0'. This is the
       e# only case in which the factorial part results in 0.
!      e# Negate this to get the actual result of the factorial part.
\      e# Swap with the input.
~      e# Evalute the input as CJam code. The leading `!` will apply the logical
       e# negations to the factorial result. The 0 or 1 will then push a junk value
       e# which is potentially negated a few times as well, by the factorials.
;      e# Discard the junk value.
\$\endgroup\$
3
\$\begingroup\$

Haskell, 67 65 bytes

f s|foldr(\_->not)(last s`elem`"1!")$fst.span(<'0')$s="1"|1<3="0"

Try it online! Usage: f "!!!0!!!!"

Saved two bytes thanks to @nimi.

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

Brainfuck, 115 bytes

>,[->++++[<-------->-]<[--------------->,[<[-]+>-]<<[->-[>+<+]>[-<+>]<<]>>++++++[-<++++++++>]<.>>+<]>-[<<+>,>[-]]<]

Try it online!

Ungolfed:

% 0: inverter count
% 1: result
% 2: if/else flag; tmpspace in inner loop 0

>1,[
    ->2++++[<-------->-]<1 subtract 33 (!)
    [ 
        % we've reached the number
        ---------------
        % now it's either 0 or 1

        % check next char; If it's not 0 then it's '!'
        % 0! = 1! = 1!...! so we only need to determine if at least one ! exists
        >2,
                [<[-]+>-]<1

        % apply inversions
        <0
        [->1
            % invert cell 1 once each iteration
                       % cell 1 is 0 or 1
            -          % cell 1 is 255 or 1
            [>+<+]     % cell 1 is 0; cell 2 is 1 iff cell 1 should be 1
            >2[-<+>]<1 % cell 1 is 1 or 0
        <0]

        % print result
        >1>++++++[-<++++++++>]<1.

        >>2+< % tape={0 r 0 1}
    ]
    >2-[ % we haven't seen the number yet
        <<0+>1,>2 % add to inverter count
        [-]
    ]<1
]
\$\endgroup\$
3
\$\begingroup\$

sed, 36 33 31 bytes

Pure sed, no bc / shell utils. Works on GNU sed < 4.3; 33 bytes on BSD and GNU 4.3+.

s/.!!*$/1/
:
s/!0/1/
s/!1/0/
t

Straightforward enough if you're familiar with sed; commented for those who aren't:

# Since 0! == 1! == 1 and factorial has precedence, just collapse any trailing "!" 
s/.!!*$/1/
# Define an anonymous label
:
# Invert 0 if needed
s/!0/1/
# Invert 1 if needed
s/!1/0/
# If a change was made, go back to the anonymous label.
t

Test:

% cat 109248.sed
s/.!!*$/1/
:l
s/!0/1/
s/!1/0/
tl
% wc -c 109248.sed
      33 109248.sed
% cat cases
0
1
0!
1!
!0
!1
!0!
!1!
0!!
1!!
!!0
!!1
!0!!
!!!1
!!!0!!!!
!!!1!!!!
% sed -f 109248.sed cases
0
1
1
1
1
0
0
0
1
1
0
1
0
0
0
0
% gsed -f 109248.sed cases
0
1
1
1
1
0
0
0
1
1
0
1
0
0
0
0
%
\$\endgroup\$
3
  • \$\begingroup\$ IIRC some (all?) versions of sed allow you to use the null string as a label name. If you can get that to work here, it'd save you two bytes. Actually, I'm not sure the label is even needed; unless I've missed something, the first line is idempotent, so you might be able to jump back to the start of the program rather than needing a label. \$\endgroup\$
    – user62131
    Feb 13, 2017 at 5:04
  • \$\begingroup\$ @ais523 I thought so too, but evidently it doesn't work in BSD versions. The man page says "If no label is specified, branch to the end of the script," and even that wasn't working when I tried. \$\endgroup\$
    – Kevin
    Feb 13, 2017 at 9:05
  • \$\begingroup\$ GNU sed does allow a label to be just : (more of a bug taken as feature), in which case both the t and b! commands jump to the position of the label. Plus, a sed code must work for at least one version of sed, similar to other languages, so you don't need to create code that works for BSD as well. \$\endgroup\$
    – seshoumara
    Feb 17, 2017 at 17:31
3
\$\begingroup\$

><>, 18 bytes

ib%:?\
+2%n;\i+3=l

Try it online!

Solved as part of LYAL CMC.

The basic idea is to process from left to right, doing the following:

  • If the current char is ! (boolean negation), keep it on the stack so that stack height can be used for negation count.
  • If the current char is 0 or 1, take one more char and test if there's a factorial (modifying the number to 1 if there is). Apply negation, print as number, and halt.

Optimizations:

  • To get the final number, we can simply do 2% at the end, which means we can just add the stack height + 1 (because the final stack height would be one more than the number of negations).

  • To discriminate between 48/49 and 33, we can do b% (modulo 11, idea by Jo King).

  • The (digit, factorial-or-EOF) combinations to handle are:

    (48, 33) -> 1
    (49, 33) -> 1
    (48, -1) -> 0
    (49, -1) -> 1
    

    We can use 48%11 = 4 and 49%11 = 5. Then a simple way to handle these combinations is to check if the sum of two numbers is 3 or not. We could use "is not 3" for the condition, but it turns out that we can negate it and remove the extra 1+.

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

Vyxal, 16 bytes

`\d!+`1øṙ\!\¬VṘĖ

Try it Online!

We do a little regex.

Explained

`\d!+`1øṙ\!\¬VṘĖ
`\d!+`            # The string "\\d!+" ( a regex that matches the digit followed by !)
      1øṙ         # and replace it with "1" (because 0! = 1! = 1)
         \!\¬V    # replace any remaining "!" with "¬" (not)
              ṘĖ  # then reverse and evaluate
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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