title: And and… and. And.?

text:
# Question
Title: And and… and. And.?
## Introduction:

Inspired by the Puzzling-stackexchange post with the same name, which I've answered four years ago:

> Can you create a perfectly valid English sentence, which makes perfect sense, but which contains the word "**and**" in it, five times consecutively in a row ?
>
> "*Something-or-other* **and and and and and** *something-else.*"

With my answer:

> Let's say we have a store owner and his clerk. The store owner want the clerk to make a sign for the shop, which has the name (for example): "*Toys And Puzzles*".
> So, the clerk makes the sign and presents it to the owner.
> The owner thinks the spacing isn't really good. It currently looks something like:
> `Toys And Puzzles`
> but he wanted it to look more like:
> `Toys And Puzzles`
> So he says to the clerk:
> "The spacing between Toys **and And and And and** Puzzles should be a bit larger. Could you please fix that?"

## Challenge:

Given a string input, replace all occurrences of the word 'and' with five times that word; three in lowercase, interleaved with two of the original cased word.

Some examples:

* `AND` would become `and AND and AND and`
* `and` would become `and and and and and`
* `AnD` would become `and AnD and AnD and`

There is one catch however ():

You're not allowed to use the characters `aAnNdD` in your source code. Any other character is still allowed, even if it's the unicode value of these letters, only these six characters themselves are banned.

## Challenge rules:

* Your source code cannot contain any of the characters `aAnNdD`.
* You can assume the input-string only contains spaces and letters (both lower- and uppercase)
* You can assume the input is non-empty
* It is possible that the input-string does not contain the word 'and', in which case it's returned as is
* Instead of a string you are also allowed to take the input as a list/array/stream of characters/code-point-integer (or other similar variations)
* Don't replace substrings of `and` if it isn't a standalone word (see test cases with `stand`, `band`, and `Anderson`)

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input:  "Toys And Puzzles"
Output: "Toys and And and And and Puzzles"

Input:  "and"
Output: "and and and and and"

Input:  "AND and anD"
Output: "and AND and AND and and and and and and and anD and anD and"

Input:  "Please stand over there and watch" # note that the "and" in "stand" isn't changed
Output: "Please stand over there and and and and and watch"

Input:  "The crowd loves this band" # note that the "and" in "band" isn't changed
Output: "The crowd loves this band"

Input:  "Toys and And and And and Puzzles"
Output: "Toys and and and and and and And and And and and and and and and and And and And and and and and and and Puzzles"

Input:  "Mr Anderson went for a walk and found a five dollar bill" # note that the "And" in "Anderson" isn't changed
Output: "Mr Anderson went for a walk and and and and and found a five dollar bill"

```

# Answer
> 5 votes
# 05AB1E, 18 bytes

-(3+1) from Kevin Cruijssen, -1 from ovs, -1 from Neil's Charcoal answer.

```
#εÐl'€ƒQils‚5∍]˜ðý

```

Try it online!

## Explanation

```
#                   Space split
 ε                  Map:
  Ð                     Triplicate
   l                    lowercase
    '€ƒQ                == "and"?
        i               If true:
         l                  Lowercase
          s‚                Paired with original
            5∍]             Extend to 5 items
                       (Else: return the current item)
               ˜   Flatten
                ðý Join by spaces

```

# Answer
> 10 votes
# C (gcc), ~~179~~ ~~176~~ ~~157~~ ~~152~~ 149 bytes

-3 -3 bytes thanks to ceilingcat

-19 bytes thanks to xibu

```
L,M,P=543452769;f(s,t)typeof("")s,t;{M=M>>8|*s<<24;t=(M|'    '|L<<24)-P?t:memcpy(t-3,(typeof(0)[]){P,M|=1<<29,P,M,P},20)+19;L=M;(*t=*s)&&f(s+1,t+1);}

```

Try it online!

## Assumptions

* ASCII
* Little-endian
* `sizeof(int) == 4`
* `sizeof(int *) >= sizeof(char *)` (I cannot imagine what absurd platform this would be false on, but you never know.)
* `typeof()` provided by the compiler.

## Breakdown

We step through the input string one character at a time. This character is placed at the top-most byte of `M`, shifting the previous characters to the left. This makes it so that `M` continuously holds a record of the four current characters. That's this part:

```
M=M>>8|*s<<24

```

Next up, we make `M` lower-case, and OR our fourth character with the previous character that we had before `M`. We compare the whole shebang with our magic number `P`, which represents the string "and ". Why ORing with the previous character like that? Well, it will only be true if that character was 0 (as in we are in the beginning of the string) or a space:

```
(M|'    '|L<<24)==P

```

If this is true, we know we have an "and" to deal with. We make sure the last character of `M` is a space and not NUL, and build an anonymous array of integers to copy into target string.

This array is built from noting that the word "and" (and whatever arbitrary case variant we picked out of the source string) will always be followed by a space (except for the last instance) when expanded to its final form, which means a neat four bytes, which happens to be the size of an integer. The string "and " is represented by `P` (little-endian makes the string appear reversed when viewed as a number):

```
M|=1<<29                        Make highest byte of M a space
t=memcpy(
    t-3                         Copy to sightly before target string
    ,(typeof(0)[]){P,M,P,M,P}   Integer array of "and " isotopes
    ,20)
+19                             Increment target string

```

Why to we copy to three bytes before the current target string? Because we have already copied those bytes before we knew it was an "and". And since this `memcpy()` is only ever called when we have found the keyword, we will never copy out of bounds.

The rest is straight-forward:

```
L=M;                            Last = Current
(*t=*s)&&f(s+1,t+1)             Copy byte and go to next bytes
                                in strings if not end-of-string

```

# Answer
> 6 votes
# Perl 5 \+ `-p -040 -l`, 35 bytes

This script contains unprintables so the link is to a Bash program that builds the script and runs the tests.

```
$s= ~'...';s/^$s$/$s $& $s $& $s/gi

```

Try it online!

## Explanation

Uses Perl `s///`ubstitution operator, but necessitates that `and` is built outside due to the source restriction. To create `and`, the `$s` is set to `~"\x9e\x91\x9b"` using the raw bytes (hence using `xxd`). I started with `"\x61\x6e\x64"` and tried to look for shorter approaches. I also looked at `PWQ^"195"` and variants of that, and `v97.110.100`, but `~` was shortest. Once that string is created, it's possible to `s///`ubstitute it surrounded by start and end anchors (`^` and `$`) due to the `-040` command-line switch which uses space (ASCII 32, octal 040) as the record separator (which is also stripped off by `-l`) making `$_` equal just the words themselves, with case-`/i`nsensitivity, with the string (`$s`) and the matched string `$&` as required, `/g`lobally within the input.

---

# Perl 5 \+ `-p040l`, 41 bytes

Without using RegEx. Link shows 50 bytes because I'm using the `\xXX` notation. Will fix when I'm not on mobile!

```
$s= ~"\x9e\x91\x9b";$_=lc eq$s?"$s $_ $s $_ $s":$_

```

Try it online!

# Answer
> 5 votes
# Python 3.8, 102 bytes

```
k=iⁿput().split();o=[]
while k:w,*k=k;o+=([w],[x:=w.lower(),w,x,w,x])["\x61\x6e\x64"==x]
priⁿt(*o)

```

Try it online!

---

# Python 3.8, ~~106~~ 104 bytes

-2 bytes inspired by this answer from Luis Mendo.

```
exec('priⁿt(*sum([([x:=w.lower(),w,x,w,x],[w])["\x61\x6e\x64"!=x]for w i\x6e iⁿput().split()],[]))')

```

Try it online!

Deobfuscated Code:

```
priⁿt(*sum([([x:=w.lower(),w,x,w,x],[w])["and"!=x]for w in iⁿput().split()],[]))

```

# Answer
> 4 votes
# Python 3, ~~160~~ ~~151~~ 149 bytes

```
q='\141\156\144'
l='=l\141mb\144\141 x:'
exec(f"f{l}x {q} x[0]+((q+x[:5])*2+q+f(x[4:])if' {q} '==x[:5].lower()else f(x[1:]));g{l}f(' '+x+' ')[1:-1]")

```

Try it online!

Since xnor said it would take imagination I've gone ahead and done a python answer. It is more of a proof of concept than anything else since I am quite rusty on python golf.

## Explanation

I wrote the pretty straightforward code:

```
q='and'
f=lambda x:x and x[0]+((q+x[:5])*2+q+f(x[4:])if' and '==x[:5].lower()else f(x[1:]))
g=lambda x:f(' '+x+' ')[1:-1]

```

Which would solve the problem if it were not for the character restriction. Then to get around the restriction I used `exec` with escape codes on all the problematic characters.

```
exec("q='\141\156\144';f=l\141mb\144\141 x:x \141\156\144 x[0]+((q+x[:5])*2+q+f(x[4:])if' \141\156\144 '==x[:5].lower()else f(x[1:]));g=l\141mb\144\141 x:f(' '+x+' ')[1:-1]")

```

And since `and` appeared in the original source 3 times, I moved the definition of `q` outside the exec and inserted `q` in those places to save bytes. I also wrote a substitution for `=lambda x:` since it appears twice.

```
q='\141\156\144'
l='=l\141mb\144\141 x:'
exec(f"f{l}x {q} x[0]+((q+x[:5])*2+q+f(x[4:])if' {q} '==x[:5].lower()else f(x[1:]));g{l}f(' '+x+' ')[1:-1]")

```

# Answer
> 4 votes
# Dyalog APL, ~~99~~ ~~95~~ ~~93~~ ~~92~~ 39 bytes

```
(7⍴'\b',⎕ucs 65 78 68)⎕R(15⍴'\l& & ')⍠1

```

Try it online!

Golfed ... a lot of bytes thanks to @Adám

# Answer
> 3 votes
# JavaScript (ES6),  ~~76 74~~  73 bytes

*Saved 1 byte thanks to @tsh*

```
s=>s.repl\u0061ce(/\b\x61\x6e\x64\b/gi,(x=(y='\x61\x6e\x64')+' $& ')+x+y)

```

Try it online!

Without escaped characters, this simply reads as:

```
s=>s.replace(/\band\b/gi,(x=(y='and')+' $& ')+x+y)

```

# Answer
> 3 votes
# PHP, 97 bytes

Saved 17 bytes thanks to Dom Hastings

```
<?php $b=chr(97);$c=XWT^"990";echo(preg_repl.$b.ce)("/\b$c\b/i","$c \\0 $c \\0 $c",${$b.rgv}[1]);

```

Try it online!

---

# PHP, 114 bytes

```
<?php $b=chr(97);$c=$b.chr(110).chr(100);$e=preg_repl.$b.ce;echo$e("/\b($c)\b/i","$c \\1 $c \\1 $c",${$b.rgv}[1]);

```

Try it online!

# Ungolfed

```
<?php

$b = chr(97);
$c = $b . chr(110) . chr(100);
$e = "preg_repl{$b}ce";

echo $e("/\b($c)\b/i", "$c \\1 $c \\1 $c", ${$b . "rgv"}[1]);

```

`chr(97)` resolves to 'a', `chr(110)` to 'n', and `chr(100)` to 'd'.

PHP allows you to define a variable as a string, then execute a function with the standard function syntax. e.g.:

```
$d = 'print';
$d('hello world'); // Parsed as print('hello world');

```

Using this I am able to execute the preg\_repl**a**ce function by interpolating the `chr(97)` from earlier and run a case insensitive regex to perform the necessary operation.

The final issue comes from input variables in PHP being e.g. `$argv[1]` \- and they're always **a**rgv. Fortunately PHP has a variable variable syntax, so `${'argv'}` is the same as `$argv` \- so I simply concatontate my `chr(97)` to 'rgv' and execute in variable variable syntax.

Finally, a few bytes are saved by using PHP's assumptions. An unquoted string is how to reference a constant in PHP. Undefined constants are assumed to be their own name.

# Answer
> 3 votes
## Excel, ~~437~~ 435

Closing quotes and parens already discounted. It's not pretty, but I found some surprising optimizations.

### Setup

Input: `C1`

Cells `B1` to `B9` (One cell per row).

```
 [SPACE]
=B1&LEFT(RIGHT(TEXT(,"[$-33]MMMM"),4),3)&B1
=UPPER(B2)
=LEFT(B2,2)&RIGHT(B3,3)
=LEFT(B2,3)&RIGHT(B3,2)
=LEFT(B3,3)&RIGHT(B2,2)
=LEFT(B3,2)&RIGHT(B5,3)
=PROPER(B2)
=LEFT(B2,2)&RIGHT(B6,3)

```

Cells `C2` to `C9`

```
=SUBSTITUTE(B1&C1&B1,B2,REPT(B2,5))
=SUBSTITUTE(C2,B3,B2&B3&B2&B3&B2)
=SUBSTITUTE(C3,B4,B2&B4&B2&B4&B2)
=SUBSTITUTE(C4,B5,B2&B5&B2&B5&B2)
=SUBSTITUTE(C5,B6,B2&B6&B2&B6&B2)
=SUBSTITUTE(C6,B7,B2&B7&B2&B7&B2)
=SUBSTITUTE(C7,B8,B2&B8&B2&B8&B2)
=TRIM(SUBSTITUTE(C8,B9,B2&B9&B2&B9&B2))

```

...where C9 is the final output.

### How It Works

* B2 - `TEXT()` creates the text "Phando" (EN January) in Venda, an official language of South Africa. The rest of it extracts the "and" from it and surrounds it with spaces.
* The rest of the Cells in Column B simply enumerate all possible capitalizations of "and".
* C2 - We first surround the input with spaces so edge handling is easier. Then replace "and" with 5 of itself.
* After this, the rest of the cells in column C replace occurrences of the corresponding capitalization permutation in column B with the sandwiched string.
* In the last cell, trim off the surrounding spaces.

### Note

* Nesting the C's gives us no advantage because we trade off the equals sign for the auto-closed parens.

# Answer
> 3 votes
# sed, <sup>~~70~~ \\$\cdots\\$ ~~56~~</sup> 52 bytes

Saved 4 bytes thanks to Dom Hastings!!!

```
s/\b\x61\x6e\x64\b/& \0 & \0 &/Ig;s/&/\x61\x6e\x64/g

```

Try it online!

Swaps all occurances of `and` (which is written in escaped hex as `\x61\x6e\x64`) in any case surrounded by word boundaries (`\b`) with: a ampersand (`&`), followed by that occurance, another ampersand, that occurance again, and finally a third ampersand. Since all input only contains spaces and letters, any ampersands present are there because of those swaps. So they're all replaced with `and` (`\x61\x6e\x64`) to complete the process.

# Answer
> 2 votes
# Jelly,  ~~23 22 21~~  20 bytes

Note: `ɗ` is not a `d`!

```
Ḳ,@ṁ5Kɗ€Œlẹ¥¦“2ɼ»Ṗ¤K

```

A monadic Link accepting a list of characters which yields a list of characters.

**Try it online!**

### How?

Note: `and` is not in Jelly's dictionary, and its compression is `“¡ÞṄɱ»` which we could use, but I decided to go with `“2ɼ»Ṗ¤` which is also five bytes.

```
Ḳ,@ṁ5Kɗ€Œlẹ¥¦“2ɼ»Ṗ¤K - Main Link: list of characters, S
Ḳ                    - split (S) at spaces -> list of words
                     - (implicitly set the right argument to:)
                  ¤  -   nilad followed by link(s) as a nilad:
             “2ɼ»    -     compression of "andy"
                 Ṗ   -     pop -> "and"                         -
            ¦        - sparse application...
           ¥         - ...indices: last links as a dyad - f(words, "and")
        Œl           -               lower-case (all the words)
          ẹ          -               indices of ("and" in the lower-cased words)
      ɗ€             - ...action: last three links as a dyad for each - f(word,"and"):
  @                  -               with swapped arguments:
 ,                   -                 pair -> ["and", word]
   ṁ5                -                 mould like five -> ["and", word, "and", word, "and"]
     K               -                 join with spaces
                   K - join with spaces

```

# Answer
> 2 votes
# Scala 2.12, ~~126~~ 116 bytes

```
"(?i)(\\b\u0061\u006e\u0064\\b)".r repl\u0061ce\u0041llI\u006e(_,m=>{v\u0061l x=m+""toLowerC\u0061se;s"$x $m "*2+x})

```

You do need to assign that function to a variable of type `String => String`, though, and enable postfix operators (to save 1 byte). This adds 21 more characters.

```
def f:String=>String="(?i)(\\b\u0061\u006e\u0064\\b)".r repl\u0061ce\u0041llI\u006e(_,m=>{v\u0061l x=m group 0 toLowerC\u0061se;s"$x $m $x $m $x"})

```

After Scala 2.13, you need to use backticks around variable names when using unicode escapes, hence Scala 2.12.2.

Try it online

Prettier version

```
val f: String => String = s =>
  raw"(?i)(\band\b)".r.replaceAllIn(s,
    m => {
      val x = m.group(0).toLowerCase
      s"$x $m $x $m $x"
    })

```

# Answer
> 2 votes
# Japt, ~~22~~ 21 bytes

Work in progress

```
r`%ß@%b`È3ÇXvÃqXû5}'i

```

Try it

## Original (w/ `-S` flag)

```
¸cÈv ¶`ß@`Å?5ogX¸iXv:X

```

Try it

```
¸cÈv ¶`ß@`Å?5ogX¸iXv:X     :Implicit input of string
¸                          :Split on spaces
 c                         :Map then flatten
  È                        :Passing each X through the following function
   v                       :  Lowercase
     ¶                     :  Test for equality with
      `ß@`                 :    The compressed string "band" ("and" compressed is also 2 bytes but includes the "d")
          Å                :    Slice off the first character
           ?               :  If true
            5o             :    Range [0,5)
              g            :    Index (0-based) each into
               X¸          :      Split X on spaces, converting it to a single element array
                 i         :      Prepend
                  Xv       :        Lowercase X
                    :X     :  Else return X
                           :Implicit output joined by spaces

```

# Answer
> 2 votes
# Haskell, 177 bytes

```
r x|_:z:_<-[x..]=z
(#)=elem.r
f(b:t@(c:e:g:h:s))|u<-b:c:e:g:" ",[b,h]<" !",c#"bB",e#"oO",g#"eE",i<-r<$>"`mc"=b:i++u++i++u++i++f(h:s)
f" "=""
f(b:t)=b:f t
g x|_:y<-f$' ':x++" "=y

```

Try it online!

## Explanation

`r` takes a character and returns the next character in ASCII order. That is to say its successor.

Then we use this to make `(#)` which takes a character and a list and checks if that character's successor is in the list.

Then we use that to make `f`.

Many of the functions I would really like to use from Haskell are missing.

# More boring version, 174 bytes

```
(#)=elem
f(b:t@(c:e:g:h:s))|u<-b:c:e:g:" ",[b,h]<" !",c#"\65\97",e#"\78\110",g#"\68\100",i<-"\97\110\100"=b:i++u++i++u++i++f(h:s)
f" "=""
f(b:t)=b:f t
g x|_:y<-f$' ':x++" "=y

```

Try it online!

This version forgoes using `r` to generate forbidden characters and instead escapes them. Boring but saves 3 bytes.

# Answer
> 2 votes
# GNU sed, 38 bytes

```
s/\<\c!\c.\c$\>/\L&\E & \L&\E & \L&/Ig

```

"and" is written escaped as `\c!\c.\c$`. `\cx` means take the character `x`, convert it to upper case if it is a lower case letter, and then flip bit 6. The surrounding `\<` and `\>` mean word boundaries. `&` corresponds to the matched string. `\L` switches to lowercase, and `\E` switches back. The `I` modifier means ignore case when matching. The `g` modifier means replace all matches, not just the first.

Try it online!

# Answer
> 1 votes
# Charcoal, 29 bytes

```
≔“1“$K”η⪫Ｅ⪪Ｓ ⎇⁼↧ιη⪫⟦ηιηιη⟧ ι

```

Try it online! No verbose mode because it won't "compress" the string for me. Explanation:

```
≔“1“$K”η

```

Assign the compressed string `and` to a variable. (None of the various ways of compressing the string `and` uses a banned letter; this is just the shortest option, after banning the uncompressed string.)

```
   Ｓ                    Input string
  ⪪                     Split on literal space
 Ｅ                      Map over words
        ι               Current word
       ↧                Lowercased
      ⁼                 Equals
         η              "and"
     ⎇                  If true then
           ⟦ηιηιη⟧      Alternate lowercase and original word
          ⪫             Join with literal space
                   ι    Otherwise the original word
⪫                       Join everything with literal space
                        Implicitly print

```

# Answer
> 1 votes
# Pip `-s`, 34 bytes

```
Y Jz@[i13 3]{(gPEyLC@gQy?,5o)}Mq^s

```

Try it online!

### Explanation

Non-regex solution taking advantage of the "letters and spaces only" rule. Partially inspired by Jonathan Allan's Jelly answer.

```
Y Jz@[i13 3]{(gPEyLC@gQy?,5o)}Mq^s
                                    z is lowercase alphabet; i is 0; o is 1 (implicit)
   z@[i13 3]                        Get the lowercase letters at indices 0, 13, and 3
  J                                 Join them into the string "and"
Y                                   Yank that into the variable y
                               q    Read a line of input from stdin
                                ^s  Split on spaces
            {                }M     Map this function:
              g                      The list of arguments: [word]
               PEy                    with y prepended: ["and" word]
             (              )        Index this list with the following index:
                        ?             If
                    @g                 the first argument
                  LC                   lowercased
                      Qy               equals y
                         ,5           then range(5)
                           o          else 1

```

Here's what the indexing does: If the `word` we're processing is some case-variant of `"and"`, we get the first five elements of the list `["and" word]`. With cyclic indexing, this amounts to `["and" word "and" word "and"]`. If the word is some other word, we get the element at index 1, which is just `word`.

The result is a (possibly nested) list, which the `-s` flag joins on spaces and then autoprints. An example run:

```
q       "Stand aNd  watch"
q^s     ["Stand" "aNd" "" "watch"]
{ }Mq^s ["Stand" ["and" "aNd" "and" "aNd" "and"] "" "watch"]
Output: Stand and aNd and aNd and  watch

```

---

## Pip, 34-bytes (no flags)

```
Y Jz@[i13 3]qR-:yWR`\b`yWR` & `WRy

```

Try it online!

### Explanation

My initial solution using regex:

```
Y Jz@[i13 3]qR-:yWR`\b`yWR` & `WRy
                                    z is lowercase alphabet; i is 0 (implicit)
   z@[i13 3]                        Get the lowercase letters at indices 0, 13, and 3
  J                                 Join them into the string "and"
Y                                   Yank that into the variable y
            q                       Read a line of input from stdin
             R                      In that string, replace
                y                    the string "and"
                 WR`\b`              wrapped in the regex `\b`: `\band\b`
              -:                     with the case-insensitive flag set: `(?i)\band\b`
                                    with
                       y             the string "and"
                        WR` & `      wrapped in the regex ` & `: ` & and & `
                               WRy   wrapped in the string "and": `and & and & and`
                                     (where & in replacement context stands for the
                                     full match)
                                    Autoprint (implicit)

```

# Answer
> 1 votes
# Stax, 32 26 bytes

```
å╔é╩⌐╬²ßxæ╬:Ö5ò▌@ Θ5YS₧Ñπε

```

Run and debug it

I knew packed stax mutation was good for something.

Saved 6 bytes thanks to an anonymous donor.

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~116~~ 112 bytes

<sup>*-4 bytes thanks to att!*</sup>

```
Stri\.6egRepl\.61ce[a:Regul\.61rExpressio\.6e["(?i)\\b"<>#<>"\\b"]:>Stri\.6egRiffle@{#,a,#,a,#}]&@"\.61\.6e\.64"

```

Try it online! An expression that evaluates to a function. Uses the standard regex `(?i)\band\b`. For reference, the shortest equivalent function that doesn't use a regex is 118 bytes:

```
Stri\.6egRepl\.61ce[a=WordBou\.6ed\.61ry;a~~b:#~~a:>Stri\.6egRiffle@{#,b,#,b,#},Ig\.6eoreC\.61se->1>0]&@"\.61\.6e\.64"

```

# Answer
> 1 votes
# Lua, 151 bytes

```
b="\97\110\100"_G["lo\97\100"]('pri\110t(\97rg[1]:gsub("%w+",fu\110ctio\110(s)retur\110 s:lower()==b '..b..' (b.." "..s.." "):rep(2)..b e\110\100))')()

```

Try it online!

### How It Works

`b` is a string which is equal to "and" via ASCII escape codes.

`_G` in Lua is the "global environment table", the data structure containing all global variables. We can index this with a string, which can contain ASCII codes for the forbidden letters.

`load()` returns a function from the string passed to it (which we immediately call). Again, ASCII codes are used here for forbidden characters.

`arg` is the command-line arguments table

`gsub()` is a Global SUBstitution function, it takes a pattern (in this case a sequence of 1 or more alphanumeric characters) and replaces it according to the second parameter, in this case an anonymous function which it calls for every match.

`and` is a boolean operator which return the right-hand-side of the operation or `false`.

`rep()` is a string repetition function.

### Readable Version

```
-- Match Every Word, Replacing Any "and"s
print(arg[1]:gsub("%w+",function(s)
    return s:lower() == "and" and ("and "..s.." "):rep(2).."and"
end))

```

---
Tags: code-golf, string, restricted-source
---


title: Calculate the square root only using ++

text:
# Question
Title: Calculate the square root only using ++
Your task is to calculate the square root of a positive integer without using any mathematical operators to change the number, such as:

* Setting a variable (ex. squareRoot = 5)
* Addition (A+B)
* Subtraction (A-B)
* Multiplication (A\*B)
* Division (A/B)
* Square, cube, fourth, etc. roots
* Exponents

Comparison operators (such as \<, \>, ==, etc) are not considered "mathematical operators" for the purposes of this question and are allowed as long as they do not change the value of a variable.

The only operator that you are able to use is ++. The following exceptions are in place:

* If you wish, you may initialize a variable by setting it to 0.
* If your language does not include the ++ syntax, you may use an equivalent syntax, such as foo+=1 or foo=foo+1
* The square root should be calculated to at least 6 digits beyond the decimal (the hundred-thousands place) and outputted as a whole number of the decimals (ex. if I input 2 it could come out as 14142135624 or 1414213 depending on the rounding). Rounding up or down is not important.

User-defined functions are not allowed. In addition, simulating functions with goto is not allowed as well.

I'm interested to see what everyone submits! Happy coding!

## CLARIFICATION

Clarify that number is a positive integer. You are welcome to make code that would do any number but it is not necessary.

## CLARIFICATION #2

Clarify that comparison operators are allowed.

## CLARIFICATION #3

Addition, subtraction, multiplication, division, and functions to change numbers are not allowed **at all**, regardless of whether they are saved to a variable or not. I'm sorry that this invalidates a couple existing answers, but I meant to define this group of operators with "change the number" in order to prevent troll answers (ex. I just used the sqrt() function, you only prohibited addition, multiplication, division, and subtraction). Sorry for the confusion.

## CLARIFICATION #4

Clarify that we need at least 5 digits. 10 digits caused code to run for a long time.

# Answer
> 13 votes
## Python 66

```
print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real

```

## Output

```
>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
121
110000000000
>>> print'%.0f'%reduce(lambda a,b:abs(a)+1e10j,range(-2,input())).real
1000
316227766017

```

> This solution uses Spiral of Theodorus on a complex plane to achieve the result.

# Answer
> 7 votes
# Python, 184 characters

The following Python solution uses only the increment operator and no other arithmetic operators at all. However, with the required precision (10 digits), it takes an impossibly long time to run. You can test it with lower precision (3 digits) by reducing `1e20` to `1e6`.

```
import sys;t=0
for _ in range(int(sys.argv[1])):
 for _ in range(int(1e20)):t+=1
q=0
while 1:
 z=0
 for _ in range(q):
  for _ in range(q):z+=1
 if z>=t:break
 q+=1
print(q)

```

Ungolfed:

```
import sys

# t = N * 100000000000000000000 (magnitude of twice the precision)
t = 0
for _ in range(int(sys.argv[1])):
    for _ in range(int(1e20)):
        t += 1
q = 0
while True:
    # z = q * q
    z = 0
    for _ in range(q):
        for _ in range(q):
            z += 1
    if z >= t:
        break
    q += 1
print(q)

```

# Answer
> 3 votes
## Fortran 73

```
read*,t;s=0;do while(abs(s*s/1e10-t)>1e-10);s=s+1;enddo;print*,s/1e5;end

```

Might take a loooong to actually determine an answer for certain values, but it'll work for sure. While I use `*` and `-`, *these are not changing any values*, only the `s=s+1` actually changes anything.

# Answer
> 2 votes
# CJam, 26 bytes

```
q~,1e20,m*,:N!{)_,_m*,N<}g

```

Try it online. Paste the **Code**, type the desired integer in **Input** and click **Run**. Before you do, I suggest changing `1e10` to `1e4` though.

The Java interpreter handles `1e6` with input “2” in about 15 seconds. `1e20` will require a *huge* amount of RAM.

### Examples

```
$ cjam <(echo 'q~,1e2,m*,:N!{)_,_m*,N<}g') <<< 4; echo
20
$ cjam <(echo 'q~,1e2,m*,:N!{)_,_m*,N<}g') <<< 2; echo
15
$ cjam <(echo 'q~,1e4,m*,:N!{)_,_m*,N<}g') <<< 4; echo
200
$ cjam <(echo 'q~,1e4,m*,:N!{)_,_m*,N<}g') <<< 2; echo
142
$ cjam <(echo 'q~,1e6,m*,:N!{)_,_m*,N<}g') <<< 4; echo
2000
$ cjam <(echo 'q~,1e6,m*,:N!{)_,_m*,N<}g') <<< 2; echo
1415

```

### Background

Since we're not allowed mathematical operators to change numbers, we're going to use setwise operators to change arrays.

The code starts by "multiplying" the input (“i”) by 1e20, but without any actual multiplication. Instead, we push an array containing “i” integers, an array containing 1e20 integers, take their cartesian product and compute its length.

Then, we push zero and increment until the product of the integer by itself (calculated as above) is no longer smaller than `i * 1e20`. This causes the square root to be rounded up.

### How it works

```
q~     " Read for STDIN and interpret. ";
,      " Push an array containing that many integers. ";
1e20,  " Push the array [ 0   …   1e20 - 1]. ";
m*,:N  " Get the length of the cartesian product and save it in “N”. ";
!      " Logical NOT. Since the input is a positive integer, this pushes 0. " ;
{      " ";
  )    " Increment the integer on the stack.";
  _,   " Push an array containing that many integers. ";
  _m*, " Get the length of the cartesian product of the array by itself. ";
  N<   " If the product is smaller than the target value, push 1; otherwise push 0. ";
}g     " Repeat the loop if the result was 1. ";

```

# Answer
> 1 votes
# Cobra - 62

**Posted before the third edit, no longer valid.**

Not only is it short, but it should be overflow-free if `n < Decimal.maxValue`

```
def f(n)
    r,e=0d,10000000000
    while r/e*r/e<n,r+=1
    print r

```

# Answer
> 0 votes
## Scala, 117

```
val z=BigInt(readLine+"0000000000")
print(Stream.from(1)find(x=>(BigInt(0)/:Stream.fill(x,x)(1).flatten){_+_}>=z)get)

```

Doesn't finish in a reasonable amount of time, even for 2 as input, but it does work. You may notice that I'm doing `_+_`, but that only ever adds 1, and Scala doesn't have a `++` operator anyway. I could save two characters by replacing the inner Stream with List, but then it would run out of memory. As written, I think it scales only in processing time, not memory usage.

# Answer
> 0 votes
# PHP, 124 bytes

It's an exhaustive algorithm. It just tries numbers until the square of that number is bigger than the "goal" number (which is the input times 1E`number of decimals` squared (10.000 for a 2 decimal result). Then it prints that last number.

```
for(;$a++<$z=$argv[1];)for(;$$a++<1e6;)$g++;for(;$b++<$g;$i=$x=0)for(;$i++<$b;)for($j=0;$j++<$b;)if(++$x>=$g)break 3;echo$b;

```

Run like this (`-d` added for aesthetic reasons only):

```
php -d error_reporting=32757 -r 'for(;$a++<$z=$argv[1];)for(;$$a++<1e6;)$g++;for(;$b++<$g;$i=$x=0)for(;$i++<$b;)for($j=0;$j++<$b;)if(++$x>=$g)break 3;echo"$b\n";' 2

```

Don't recommend trying this out with anything more than 3 decimals or a number above 10.

# Answer
> 0 votes
# Haskell, 70 bytes

```
s i|r<-[1..i]=foldl1(.)[(+1)|j<-r,k<-r]
f i=[j-1|j<-[0..],s j 0>=i]!!1

```

`f` gives the integer square root by finding the largest number whose square is less than or equal to the input. The squaring function `s i` increments by one for every element of an `(i,i)` matrix. (Typed on phone so might have typos).

# Answer
> 0 votes
# x86-64 Assembly Code, 22 bytes

No operators or function calls, as per the rules.

```
// Int from stack -> st0
fild 8(%rsp)
// sqrt(st0) -> st0
fsqrt
ret

```

Expects argument pushed onto the stack, then call this function, like so:

```
push $2
call a

```

The result is saved onto the register stack (`%st0`). Tested on MinGW64.

---
Tags: code-golf, restricted-source
---


title: Separating the _____ from the _____

text:
# Question
Title: Separating the _____ from the _____
There are two types of people in this world: users and admins. Let's find out who the real admins are.

The task is simple: If the script is run with elevation, print 'True' and only 'True' (only trailing newlines permitted as extra). If the script is run as an unelevated user, print 'False' and only 'False', exceptions granted for trailing new lines.

The code can be run on any operating system which is currently available free of charge, or on any CPU architecture as a code insertion OR it can run on Windows 10.

The selected operating system must have at least 3 privilege levels, and should return 'True' for any execution of code above the default user privilege level.

I couldn't find any tags for this, so please if you have suggestions, name them. Good luck!

# Answer
> 11 votes
# Python 3, 32 bytes

-13 bytes thanks to @Arnauld -1 byte thanks to @Dingus

```
import os
print(os.getuid()<1e3)

```

Try it online!

# Answer
> 9 votes
# Bash, ~~39~~ ~~31~~ 27 bytes

Saved 4 bytes thanks to Gilles 'SO- stop being evil'!!!

```
a=False
>/a&&a=True
echo $a

```

Try it online!

Works on any \*nix system.

**Explanation**

```
a=False         # set env variable a to False
>/a             # try to create (>) (or overwrite if it exists) file /a
                # but directory / has root write privileges
                # and if /a is created by root in a
                # previous run the file will have root only
                # write privileges
   &&a=True     # if this succeeds set a to True
                # if this fails a will be left as is
echo $a         # will be True for root and False otherwise

```

# Answer
> 2 votes
## Batch, 32 bytes

```
fltmc>nul&&echo True||echo False

```

Taken from this Stack Overflow answer.

---
Tags: code-golf
---


title: Prime Time Travel

text:
# Question
Title: Prime Time Travel
Don't tell anyone, but I've nicked my uncle's time travel machine! My uncle is obsessed with prime numbers, though, and that shows in the machine — he has programmed it so that it can only go to dates that sum up to a prime number.

So it can't go to `1947-08-15` because 1947+8+15 = 1970, which is not a prime number. It *can* go to `1947-07-25`, because 1947+7+25 = 1979, which is prime. So if I want to go back to watch India's independence celebrations, it looks like I'll have to go a few weeks earlier and wait out those 20 days.

I have some other dates that I want to go to, and I'll similarly have to go to a date before (or if I'm lucky, equal to) my target date, that sums up to a prime number. I'm impatient, though, and don't want to wait too much — so I want to find the date I can use that is closest to my target date.

**Can you write me a program that takes my target date and gives me the date I should input into the time machine — the closest date before or equal to the given date whose parts add up to a prime number?**

(For this challenge, we're using the *proleptic* Gregorian calendar — which simply means we use the current Gregorian calendar even for periods when people then were using the older Julian calendar.)

### Input

* A date
    + ideally, any date in the Current Era (AD); practically, whatever subset of that your language can naturally handle
    + in any single human-readable format⁺ you like

### Output

* The date closest to the input date, which is less than or equal to the input and whose date+month+year sums up to a prime number.
    + in any single human-readable format⁺ you like

⁺: "human readable" as in the day, month and year all separately spelt out, in whatever order

### Test cases

```
1947-08-15
=> 1947-07-25
1957-10-04
=> 1957-09-27
1776-07-04
=> 1776-07-04
999-12-12
=> 0999-12-10
2018-06-20
=> 2018-06-15
1999-01-02
=> 1998-12-29
1319-12-29
=> 1319-07-01

```

*(Thanks to @Shaggy, @PeterTaylor, and @Arnauld for help with the question.)*

# Answer
> 5 votes
# JavaScript (Node.js), 94 bytes

Takes input as 3 integers in currying syntax `(year)(month)(day)`. Returns a hyphen-separated string with a leading hyphen.

```
y=>m=>g=d=>(P=k=>n%++k?P(k):~k)(n=eval(s='-'+new Date(y,m-1,d).toJSON().split`T`[0]))?g(d-1):s

```

Try it online!

### How?

We first convert the date to JSON format `yyyy-mm-ddT00:00:00.000Z` (ISO 8601), split it on the `'T'`, keep only the left part and add a leading hyphen, which gives `-yyyy-mm-dd`.

```
s = '-' + new Date(y, m - 1, d).toJSON().split`T`[0]

```

This expression **s** can now be `eval()`'uated to get the opposite **n** of the sum of **year + month + day**.

```
n = eval(s)

```

We use the helper function **P()** to test whether **-n** is prime (in which case it returns **0**). If it is, we return **s**. Otherwise, we try again with the previous day.

```
(P = k => n % ++k ? P(k) : ~k)(n) ? g(d - 1) : s

```

# Answer
> 5 votes
# Red, 87 bytes

```
func[d][d: d + 1 until[d: d - 1 n: d/2 + d/3 + d/4 i: 1 until[n %(i: i + 1)= 0]i = n]d]

```

Try it online!

## More readable:

```
f: func [ d ] [
    d: d + 1
    until [
        d: d - 1
        n: d/day + d/month + d/year
        i: 1
        until [
            i: i + 1
            n % i = 0
        ]
        i = n
    ]
    d
]

```

# Answer
> 3 votes
# Python 2, ~~130~~ 127 bytes

Input is `year, month, day`.

-3 bytes thanks to Kevin Cruijssen.

```
from datetime import*
def f(a):
  while(lambda n:any(n%m<1for m in range(2,n)))(a.year+a.month+a.day):a-=timedelta(1)
  print a

```

Try it online!

# Answer
> 3 votes
# Ruby, 94 bytes

Try it online!

Takes a single Date input, and returns a string in the ISO 8601 format (`YYYY-MM-DD`).

```
require'date'
require'prime'
->d{d.downto(0){|i|break i.to_s if (i.day+i.month+i.year).prime?}}

```

It uses Ruby's prime module. If that's not allowed, or frowned upon, then for two bytes more I present this abomination:

---

# Ruby, 97 bytes

Try it online!

It uses a check for a number being prime from this stackoverflow answer. I have no idea how this works, it looks a bit like witchcraft. Same input as above, and same output.

```
require'date'
->d{d.downto(0){|i|break i.to_s if ?1*(i.day+i.month+i.year)!~ /^1?$|^(11+?)\1+$/}}

```

# Answer
> 3 votes
# , 117 bytes

```
function(d){while(!numbers::isPrime(y(d))){d=d-1};d}
`<`=format
y=function(d)sum(as.integer(c(d<"%Y",d<"%m",d<"%d")))

```

Try it online!

# Answer
> 2 votes
# Java 8, ~~144~~ 128 bytes

```
d->{for(;;d=d.minusDays(1)){int n=d.getYear()+d.getMonthValue()+d.getDayOfMonth(),i=2;for(;i<n;n=n%i++<1?0:n);if(n>1)return d;}}

```

Try it online.

`java.time.LocalDate` class has been an improvement in comparison to the old `java.util.Date`, but why did they had to make those names longer (`getMonthValue` and `getDayOfMonth` instead of `getMonth` and `getDay`).. \>.\>

**Explanation:**

```
d->{                      //  Method with LocalDate as both parameter and return-type
  for(;;                  //  Loop indefinitely
      d=d.minusDays(1)){  //    Going one day back after every iteration
    int n=d.getYear()+d.getMonthValue()+d.getDayOfMonth(),
                          //   Set `n` to the sum of year+month+day
    i=2;for(;i<n;n=n%i++<1?0:n);if(n>1)
                          //   If `n` is a prime:
      return d;}}         //    Return the now modified input-LocalDate `d`

```

# Answer
> 2 votes
# Ruby, ~~57~~ 53 bytes

```
->d{d-=9until/^(11+)\1+$/!~?1*(d.day+d.year+d.mon);d}

```

Try it online!

Not my idea - stolen from the "abomination" by IMP1

---

## Original idea:

# Ruby, 59 bytes

```
->d{d-=9until((2...w=d.day+d.year+d.mon).all?{|x|w%x>0});d}

```

Try it online!

# Answer
> 2 votes
# F#, 134 133 bytes

```
let rec s(d:System.DateTime)=
 let x=d.Year+d.Month+d.Day
 if(Seq.tryFind(fun i->x%i=0){2..x-1}).IsNone then d else d.AddDays(-1.)|>s

```

-1 byte thanks to from sundar.

Try it online!

Total the day, month and year and see if it's prime. If it is, return that date. If not, decrement the date by 1 day and try again.

# Answer
> 1 votes
# PowerShell, ~~105~~ 90 bytes

```
for($a=$args[0];'1'*((Date $a -f yyyy+MM+dd)|iex)-match'^(..+)\1+$';$a=$a.AddDays(-1)){}$a

```

Try it online!

*Thanks to sundar for -13 bytes.*

Takes input as a `DateTime` `2018-06-20` and saves it into `$a`. Then we're in a `for` loop. Each iteration, we're taking `$a` `-f`ormatted like `yyyy+MM+dd` (i.e., the current date we're on separated by `+` signs) added together with `|iex` (similar to `eval`), string-multiplying that with `1`s to form a unary number, and using a prime-checking regex to determine if the current date is prime or not. If it is not prime, we `.AddDays(-1)` to go backwards a day and continue the loop. If it is prime, we break out of the loop and place `$a` onto the pipeline with implicit output.

The resulting output is culture-dependent. On TIO, which uses `en-us`, the output is long-date format, which looks like `Saturday, July 1, 1319 12:00:00 AM`.

# Answer
> 1 votes
# Bash, ~~114~~ 108 bytes

```
a=`date +%s -d$1`
while [ "`date +%d+%m+%Y -d@$a|bc|factor|awk NF!=2`" ]
do a=$[a-86400]
done
date +%F -d@$a

```

Try it online!

My first ever bash golf. Honestly, my first real bash program ever ... primality test taken from here.

This might sometimes fail if there is a timezone change, but TIO uses UTC, so there it should work.

# Answer
> 1 votes
# C (gcc), ~~167~~ 164 bytes

-3 bytes thanks to ceilingcat.

```
r;P(n,i){for(r=0;++i<n;)r|=n%i<1;}f(y,m,d){for(;P(y+m+d,1),r;)d=--d?d:" >8><><>><><>"[!--m?y--,m=12:m]/2+(m==2&y%4<1&y%100|y%400<1);printf("%04d-%02d-%02d",y,m,d);}

```

Try it online!

## Rundown

```
r;P(n,i){for(r=0;++i<n;)r|=n%i<1;}

```

The anti-prime-checking function. Since the earliest valid year we need to deal with is 0001-01-01, the lowest number we ever need to worry about is 3, so the special-case checks for n==2 or n \< 2 are stripped out. r is set to a truthy value if n is *not* a prime. r is kept global, since not having to return it saves two bytes (`i=n;` to return vs `,r` to check the global). i is set to 1 by the function caller, to save another 2 bytes.

```
f(y,m,d){for(;P(y+m+d,1),r;)

```

We take the date as three separate integers and start the main loop, which goes on until y+m+d is prime. Then we come to the meat of the function:

```
!--d?                           Decrement day and check if zero, which means we go back to last day of previous month.
d=" >8><><>><><>"               The string contains the number of days of each month times 2, to bring them into printable ASCII range.
                                We begin the string with a space, to avoid having to substract from index later.
[!--m?y--,m=12:m]/2+            Decrement month and check if zero. If so, go back a year and set m to 12. Use m as index in string.
(m==2&!(y%4)&y%100|!(y%400))    If the new month is February, add 1 to day if it's a leap year.
:0;                             Do nothing if day did not become zero.

```

It might seem iffy to use m and y both in the leap year check and as the index of the string, when the evaluation order is unspecified. Luckily, we only check for leap year if m == 2, which can't happen at the same time as we change m and y, since that only happens going from January to December, so the leap year check is never bothered by the order of evaluation.

Finally, the result is printed to STDOUT:

```
printf("%04d-%02d-%02d",y,m,d);}

```

# Answer
> 0 votes
# C# - ~~281~~ ~~239~~ 232 Char

```
using System;class P{static void Main(){var d=DateTime.Parse(Console.ReadLine());do{int c=d.Year+d.Month+d.Day;if(c%2!=0){int i=3;for(;i<=c;i+=2)if(c%i==0)break;if(i>=c)break;}d=d.AddDays(-1);}while(d>DateTime.MinValue);Console.WriteLine(d);}}

```

ungolfed:

```
using System;
class P
{
    static void Main()
    {
        var d = DateTime.Parse(Console.ReadLine());
        do
        {
            int c = d.Year + d.Month + d.Day;
            // minimum datetime in c# is 0001-01-01
            // therefore do not need to check for the first two primes
            int i = 3;
            for (; i < c; i += 2) if (c % i == 0) break;
            // check to break the date decrement loop if counter passed the input value
            // ie, no factor could be found
            if (i >= c) break;

            d = d.AddDays(-1);
        } while (d > DateTime.MinValue);
        Console.WriteLine(d);
    }
}

```

Made the code less efficient but smaller. Prime loop will now go up to the integer rather than the square root. It will also process all even numbers.

# Answer
> 0 votes
# MATL, 14 bytes

```
`tsZp?.}YOqZOT

```

Try it online!

Alternately:

### 15 bytes

```
`tsZp~tbYOw-ZOw

```

Try it online!

# Answer
> 0 votes
# Scala, 116 bytes

```
d=>LazyList.iterate(d)(_ minusDays 1)find{d=>val s=d.getYear+d.getMonthValue+d.getDayOfMonth
2 to s/2 forall(s%_>0)}

```

Uses `java.time.LocalDate` as input and output.

Try it in Scastie

---
Tags: code-golf, primes, date
---


title: Integers, Assemble!

text:
# Question
Title: Integers, Assemble!
Your task is to assemble the integers from `1` to `N` (given as input) into a rectangle of width `W` and height `H` (also given as input). Individual numbers may be rotated by any multiple of 90 degrees, but they must appear as contiguous blocks in the rectangle. That is, you cannot break one of the numbers into multiple digits and place the digits in the rectangle individually, neither can you bend three digits of a number around a corner. You could consider each number a brick from which you're building a wall.

Here is an example. Say your input is `(N, W, H) = (12, 5, 3)`. One possible solution is:

```
18627
21901
53114

```

For clarity, here are two copies of this grid, one with the one-digit numbers hidden and one with the two-digit numbers hidden:

```
1####    #8627
2##01    #19##
##11#    53##4

```

It's fine if the rectangle cannot be disassembled again in a unique way. For instance, in the above example, the `12` could also have been placed like this:

```
#####    18627
21#01    ##9##
##11#    53##4

```

## Rules

You may assume that `N` is positive and that `W*H` matches the number of digits in the integers from `1` to `N` inclusive, and that a tiling of the rectangle into the given numbers exists. I don't currently have a proof whether this is always possible, but I'd be interested in one if you do.

Output may either be a single linefeed-separated string or a list of strings (one for each line) or a list of lists of single-digit integers (one for each cell).

The results of your submission must be determinstic and you should be able to handle all test cases in less than a minute on reasonable desktop machine.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

Except for the first one, none of these are unique. Each test case is `N W H` followed by a possible output. Make sure that your answer works when the rectangle is too narrow to write the larger numbers horizontally.

```
1 1 1
1

6 6 1
536142

6 2 3
16
25
34

10 1 11
1
0
8
9
2
6
7
3
1
5
4

11 13 1
1234567891011

27 9 5
213112117
192422581
144136119
082512671
205263272

183 21 21
183116214112099785736
182516114011998775635
181116013911897765534
180415913811796755433
179115813711695745332
178315713611594735231
177115613511493725130
176215513411392715029
175115413311291704928
174115313211190694827
173115213111089684726
172015113010988674625
171915012910887664524
170814912810786654423
169714812710685644322
168614712610584634221
167514612510483624120
166414512410382614019
165314412310281603918
164214312210180593817
163114212110079583716

200 41 12
81711132917193661114105533118936111184136
50592924448815915414562967609909953662491
89529721161671582389717813151113658811817
41418184511110119010183423720433017331118
35171183614003547461181197275184300111711
41874381132041861871718311415915921116264
11914245014112711011594492626831219331845
17125112629222085166344707736090956375181
94507611291431121128817413566319161275711
11011540021119913511011169939551729880780
92725141607727665632702567369893534277304
78118311405621148296417218591118562161856

```

# Answer
> 3 votes
# Pyth, 35 bytes

```
juum+WghHl+dQd~tQN<+.TGmkeHeH)_BvzY

```

Credits to mbomb007. I used his algorithm. Originally I only wanted to help Steven H., but then I really wanted to see a short version.

Takes `N` on the first line, and `W,H` on the second line: Try it online: Demonstration

Found a nasty bug in the Pyth implementation of `.[` (my own fault, since I implemented it). Gotta fix it tomorrow. This resulted in +3 bytes.

### Explanation:

```
juum+WghHl+dQd~tQN<+.TGmkeHeH)_BvzY
                                  Y   start with the empty list []
                                      I'll perform all operations on this list.
                                      Sometimes it is called G, sometimes N.
                                vz    read the second line and evaluate it: [W, H]
                              _B      bifurcate it with reverse: [[W, H], [H, W]]
 u                                    for each pair H in ^:
                    .TG                  transpose G
                   +   mkeH              append H[1] empty strings
                  <        eH            use only the first H[1] strings
                                         lets call this result N
  u                          )           modify N, until it doesn't change anymore:
   m                        N               map each d in N to:
     WghHl+dQ                                  if H[0] >= len(d+Q):
    +        d  Q                                 d + Q
              ~t                                  and decrement Q by 1
             d                                 else:
                                                  d
j                                     at the end print every row on a separate line

```

# Answer
> 7 votes
# Python 2, ~~210~~ 200 bytes

**Edit:** Works now!

Fills from top to bottom, left to right, starting with the largest numbers. Then, transpose and do it again. Then transpose and print. I had to pad with spaces for the transposition to work, since the lines aren't to their full length yet.

I had trouble getting a nested `exec` working (to do `exec'exec"..."*w\n;...'*2`. If someone can figure it out, let me know.

```
n,w,h=input()
s=[""]*h
for x in 1,2:
    exec"for i in range(h):l=len(s[i]+`n`)<=w;s[i]+=`n`*l;n-=l\n"*w;s=[r.replace(" ","")for r in map(lambda x:`x`[2::5],zip(*[r.ljust(w)for r in s]))];w,h=h,w
print s

```

**Try it online** \- Uses a modified function so it can run multiple test cases more easily (and it couldn't use `exec`). Uncomment the other version and modify stdin to see it run.

**Less golfed:**

```
def f(n,w,h):
    s=[""]*h
    for x in 1,2:
        for j in[0]*w:
            for i in range(h):
                l=len(s[i]+`n`)<=w
                s[i]+=`n`*l
                n-=l
        s=[r.ljust(w)for r in s]
        s=map(lambda x:`x`[2::5],zip(*s))
        s=[r.replace(' ','')for r in s]
        w,h=h,w
    print"\n".join(s)

```

# Answer
> 6 votes
## JavaScript, ~~284~~ ~~259~~ ~~245~~ ~~241~~ ~~240~~ ~~223~~ ~~209~~ 205 bytes

```
// Golfed
let f = (N,W,H)=>eval('a=Array(H).fill("");while(N)g:{s=""+N--;d=s[L="length"];for(i in a)if(a[i][L]+d<=W){a[i]+=s;break g}for(p=0;d;++p){l=a[p][L];for(k=p+d;k>p;)l=a[--k][L]-l?W:l;while(l<W&&d)a[p+--d]+=s[d]}}a');

// Ungolfed
(N,W,H) => {
    a = Array(H).fill(""); // Create `H` empty rows.

    while (N) g : {
        s = "" + N--; // Convert the number to a string.
        d = s[L="length"]; // Count the digits in the number.

        // Loop through the rows trying to fit the number in horizontally.
        for (i in a) {
            if (a[i][L] + d <= W) { // If it fits.
                a[i] += s; // Append the number to the row.
                break g; // This is what a goto statement looks like in JavaScript.
            }
        }

        // Loop through the rows trying to fit the number in vertically.
        for (p = 0; d; ++p) {
            l = a[p][L]; // Get the length of the row.

            // Find `d` adjacent rows of the same length.
            for (k = p + d; k > p; ) {
                // If `a[--k][L] == l`, continue.
                // Else set `l` to `W` so the next loop doesn't run.
                l = a[--k][L] - l ? W : l;
            }

            // Put the characters in position.
            while (l < W && d)
                a[p+--d] += s[d];
        }
    }

    return a;
}

let test_data = [[1,1,1],
                 [6,6,1],
                 [6,2,3],
                 [10,1,11],
                 [10,11,1],
                 [11,13,1],
                 [27,9,5],
                 [183,21,21],
                 [184,2,222],
                 [200,41,12],
                 [1003,83,35]];

for (let test of test_data)
    console.log(f(test[0],test[1],test[2]));
```

# Answer
> 2 votes
# Pyth, ~~79 50~~ 48 Bytes

~~Noncompeting until I work out bugs (for example, \[6,6,1\] returns the same as \[6,1,6\]). It's my first time trying to use Pyth, so I'm probably missing a lot of features.~~

*Thanks to Jakube, saved 29 bytes and made my code actually work!*

Saved another two byte by realizing that the `repr()` calls were unnecessary.

It's basically just a translation of mbomb007's Python 2 answer.

```
AEJmkHFb2VHVGIgGl+@JNQ XNJ~tQ)))=.[.TJkGA,HG)jJ

```

Takes input in the form of
`n`
`w,h`.

# Answer
> 2 votes
# Stax, 27 bytes

```
é!L↑?∞S░♠╔)¥¼/ÿµ◄÷│♦╫Δò6√√╣

```

Run and debug it

It takes input on one line in the for `{N} {H} {W}`.

This program starts with a grid of spaces of the specified size. For each number from `N` .. `1`, it attempts to do a single string replacement from a string of spaces of the appropriate size to the formatted number. If no replacement can be performed, then it tries again with a transposed grid.

```
z)A+*   create "grid" of spaces and newlines of specified size
,Rr     create range [n ... 1]
F       for each number execute the indented section; it will fit the value into the grid
  $%z(  make a string out of spaces the same length as the number; e.g. 245 => "   "
  Y     store the space string in register Y; this will be used as a search substring
  [#    count the number of occurrences of y in the grid; the grid is still on the stack
  X     store the count in register X; this will be used as a condition
  G     jump to routine at closing curly brace
  y_$|e replace the first instance of y (the spaces) with the current number
  xG    push x; then jump to routine at closing curly brace
        end program
}       called routine jump target
C       pop top of stack; if it's truthy terminate routine
|jM|J   split on newlines; transpose; join with newlines

```

Run this one

# Answer
> 0 votes
# Pip, 59 bytes

Oy, Pip can be verbose for a golfing language sometimes...

```
YsXbRLcJnWa{T` `X#a~yx:Y(t:{J*Z:a^n}Jny)Y$`.a.$'--a}x?(ty)y

```

Try it online!

### Ungolfed

Approach: store the grid as a newline-separated string, using regex to replace a run of spaces with the current number, and transposing if there isn't a run of spaces long enough.

```
; Command-line arguments are: a (the number), b (the width), c (the height)
; x is "", a falsey value

; Set up the initial string:
;  sXb  String of b spaces
;  RLc  Make a list of c of those
;  Jn   Join on newline
Y sXb RL c J n

; Define a function t that transposes a newline-separated string:
;  a^n  Split argument on newlines
;  Z    Zip (transposes, but results in a list of lists of characters)
;  J*   Join each of the sublists into a string
;  Jn   Join those strings on newline
t: {(J* Z (a^n)) J n}

; Loop while a is nonzero:
W a {

  ; Loop till a regex made of len(a) spaces matches in y:
  T y ~ ` `X#a

    ; Transpose y and set x to a truthy value to indicate that we've transposed it:
    ;  (t y)  Call the t function on y
    ;  Y      Assign the result back to y
    ;  x:     Assign it to x also
    x: Y (ty)

  ; When we break out of the loop, we have matched the first run of len(a) spaces
  ; in y; now we want to replace that with the number a:
  ;  $`   The part of the string before the match
  ;  .a   Concatenated to a
  ;  .$'  Concatenated to the part of the string after the match
  ;  Y    Assign that to y
  Y $`.a.$'

  ; Decrement a
  --a
}

; After the main loop, we need to transpose y back if we transposed it:
;  x?     Is x truthy?
;  (t y)  If so, transpose y
;  y      If not, return y as-is
x ? (ty) y

; The result is autoprinted.

```

---
Tags: code-golf, number, grid, tiling
---


# Question
Title: Fill in an increasing sequence with as many numbers as possible
A list of numbers is called monotonically increasing (or nondecreasing) is every element is greater than or equal to the element before it.

For example, `1, 1, 2, 4, 5, 5, 5, 8, 10, 11, 14, 14` is monotonically increasing.

Given a monotonically increasing list of positive integers that has an arbitrary number of empty spots denoted by `?`, fill in the empty spots with positive integers such that as many unique integers as possible are present in the list, yet it remains monotonically increasing.

There may be multiple ways to accomplish this. Any is valid.

Output the resulting list.

> **For example**, if the input is
>
> ```
> ?, 1, ?, 1, 2, ?, 4, 5, 5, 5, ?, ?, ?, ?, 8, 10, 11, ?, 14, 14, ?, ?
>
> ```
>
> it is guaranteed that without the empty spots the list will be monotonically increasing
>
> ```
> 1, 1, 2, 4, 5, 5, 5, 8, 10, 11, 14, 14
>
> ```
>
> and your task is to assign positive integers to each `?` to maximize the number of distinct integers in the list while keeping it nondecreasing.
>
> One assignment that is ***not valid*** is
>
> ```
> 1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 8, 10, 11, 14, 14, 14, 14, 14
>
> ```
>
> because, while it is nondecreasing, it only has one more unique integer than the input, namely `3`.
>
> In this example it is possible to insert six unique positive integers and keep the list nondecreasing.
> A couple possible ways are:
>
> ```
> 1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 8, 10, 11, 12, 14, 14, 15, 16
>
> 1, 1, 1, 1, 2, 3, 4, 5, 5, 5, 5, 6, 6, 7, 8, 10, 11, 13, 14, 14, 20, 200
>
> ```
>
> Either of these (and many others) would be valid output.

All empty spots must be filled in.

There is no upper limit on integers that can be inserted. It's ok if very large integers are printed in scientific notation.

Zero is not a positive integer and should never be inserted.

In place of `?` you may use any consistent value that is not a positive integer, such as `0`, `-1`, `null`, `False`, or `""`.

**The shortest code in bytes wins.**

# More Examples

```
[input]
[one possible output] (a "*" means it is the only possible output)

2, 4, 10
2, 4, 10 *

1, ?, 3
1, 2, 3 *

1, ?, 4
1, 2, 4

{empty list}
{empty list} *

8
8 *

?
42

?, ?, ?
271, 828, 1729

?, 1
1, 1 *

?, 2
1, 2 *

?, 3
1, 3

45, ?
45, 314159265359

1, ?, ?, ?, 1
1, 1, 1, 1, 1 *

3, ?, ?, ?, ?, 30
3, 7, 10, 23, 29, 30

1, ?, 2, ?, 3, ?, 4
1, 1, 2, 3, 3, 3, 4

1, ?, 3, ?, 5, ?, 7
1, 2, 3, 4, 5, 6, 7 *

1, ?, 3, ?, 5, ?, ?, 7
1, 2, 3, 4, 5, 6, 7, 7

1, ?, ?, ?, ?, 2, ?, ?, ?, ?, 4, ?, 4, ?, ?, 6
1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 6

98, ?, ?, ?, 102, ?, 104
98, 99, 100, 101, 102, 103, 104 *

```

# Answer
# Haskell, 41 bytes

`f` takes a list and returns a list, with 0 representing `?`s.

```
f=scanr1 min.tail.scanl(#)0
m#0=m+1
_#n=n

```

Basically, first scan list from left, replacing 0s by one more than the previous element (or 0 at the start); then scan from right reducing too large elements to equal the one on their right.

Try it online! (with wrapper to convert `?`s.)
> 12 votes

# Answer
# Mathematica, 84 bytes

```
Rest[{0,##}&@@#//.{a___,b_,,c___}:>{a,b,b+1,c}//.{a___,b_,c_,d___}/;b>c:>{a,c,c,d}]&

```

Pure function taking a list as argument, where the empty spots are denoted by `Null` (as in `{1, Null, Null, 2, Null}`) or deleted altogether (as in `{1, , , 2, }`), and returning a suitable list (in this case, `{1, 2, 2, 2, 3}`).

Turns out I'm using the same algorithm as in Ørjan Johansen's Haskell answer: first replace every `Null` by one more than the number on its left (`//.{a___,b_,,c___}:>{a,b,b+1,c}`), then replace any too-large number by the number on its right (`//.{a___,b_,c_,d___}/;b>c:>{a,c,c,d}`). To deal with possible `Null`s at the beginning of the list, we start by prepending a `0` (`{0,##}&@@#`), doing the algorithm, then deleting the initial `0` (`Rest`).

Yes, I chose `Null` instead of `X` or something like that to save literally one byte in the code (the one that would otherwise be between the commas of `b_,,c___`).
> 4 votes

# Answer
# C 127

**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**

```
#define p;printf("%d ",l
l,m,n;main(c,v)char**v;{for(;--c;m++)if(**++v-63){for(n=atoi(*v);m--p<n?++l:n))p=n);}for(;m--p+++1));}

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~31~~ ~~23~~ 13 bytes

Saved 10 bytes thanks to *Grimy*

```
ε®X:D>U].sR€ß

```

Try it online!

**Explanation**

```
ε      ]       # apply to each number in input
 ®X:           # replace -1 with X (initially 1)
    D>U        # store current_number+1 in X
        .s     # get a list of suffixes
          R    # reverse
           €ß  # take the minimum of each

```
> 3 votes

# Answer
# Pip, ~~25~~ ~~23~~ 21 bytes

```
Y{Y+a|y+1}MgW PMNyPOy

```

Takes input as multiple space-separated command-line arguments. Outputs the result list one number per line. Try it online! (I've fudged the multiple command-line args thing because it would be a pain to add 25 arguments on TIO, but it does work as advertised too.)

### Explanation

We proceed in two passes. First, we replace every run of `?`s in the input with a sequence starting from the previous number in the list and increasing by one each time:

```
? 1 ? 1 2 ? 4 5 5 5 ? ? ? ? 8 10 11 ?  14 14 ?  ?
1 1 2 1 2 3 4 5 5 5 6 7 8 9 8 10 11 12 14 14 15 16

```

Then we loop through again; for each number, we print the minimum of it and all numbers to its right. This brings the too-high numbers down to keep monotonicity.

```
                      y is initially "", which is 0 in numeric contexts
                      Stage 1:
 {       }Mg           Map this function to list of cmdline args g:
   +a                  Convert item to number: 0 (falsey) if ?, else nonzero (truthy)
     |                 Logical OR
      y+1              Previous number +1
  Y                    Yank that value into y (it is also returned for the map operation)
Y                      After the map operation, yank the whole result list into y
                      Stage 2:
            W          While loop, with the condition:
               MNy      min(y)
              P         printed (when y is empty, MN returns nil, which produces no output)
                  POy  Inside the loop, pop the leftmost item from y

```
> 3 votes

# Answer
# Brachylog, ~~43~~ ~~27~~ ~~24~~ 22 bytes

*-2 bytes thanks to Unrelated String*

```
Ė|a₀ᶠ⟨{a₁+0}ᶜ+⌉⟩ᵐa₁ᶠ⌋ᵐ

```

Uses 0 as the blank value. Try it online!

### How?

Lots of prefixes and suffixes.

We want to perform a two-step process that goes like this:

```
[0, 1, 0, 0, 0, 3, 0, 0]
[1, 1, 2, 3, 4, 3, 4, 5]
[1, 1, 2, 3, 3, 3, 4, 5]

```

For the first step, we look at each prefix of the list:

```
[0]
[0, 1]
[0, 1, 0]
...
[0, 1, 0, 0, 0, 3, 0, 0]

```

We're going to map each prefix to what its last number *would* be if we had already completed step 1:

```
[1] -> 1
[1, 1] -> 1
[1, 1, 2] -> 2
...
[1, 1, 2, 3, 4, 3, 4, 5] -> 5

```

Observe that nonzero final numbers stay the same, while final zeros are replaced with the result of counting up from the last previous nonzero number (or from 1, if there is no previous nonzero number). Since the list is nondecreasing, the last previous nonzero number is simply the max of the prefix, so our calculation boils down to (max value) + (number of trailing 0s). We collect all the results in a list, and step 1 is completed.

For step 2, we simply take each suffix of the step 1 result and replace it with its minimum.

### Code with explanation

```
Ė|a₀ᶠ⟨{a₁+0}ᶜ+⌉⟩ᵐa₁ᶠ⌋ᵐ

Ė                       If input is empty list, output is empty list
 |                      Otherwise
  a₀ᶠ                   Find all (nonempty) prefixes of input list
                ᵐ       For each prefix:
                         Find how many 0s it ends with:
      {    }ᶜ             Count the number of ways to satisfy this predicate:
       a₁                  Get a suffix
         +                  whose sum
          0                 is 0
                           The numbers are nonnegative, so this means they are all 0
              ⌉          Get the maximum number in the prefix
     ⟨       + ⟩         Add that to the number of trailing 0s
                 a₁ᶠ    Find all (nonempty) suffixes of the resulting list
                    ⌋ᵐ  Take the minimum of each

```
> 3 votes

# Answer
## Python 2 with NumPy, 163 bytes

Saved 8 bytes thanks to @wythagoras

Zeros used to mark empty spots

```
import numpy
l=[1]+input()
z=numpy.nonzero(l)[0]
def f(a,b):
 while b-a-1:a+=1;l[a]=l[a-1]+1;l[a]=min(l[a],l[b])
i=1
while len(z)-i:f(z[i-1],z[i]);i+=1
print l[1:]

```

More readable with comments:

```
import numpy
l=[1]+input()           # add 1 to the begining of list to handle leading zeros
z=numpy.nonzero(l)[0]   # get indices of all non-zero values
def f(a,b):             # function to fill gap, between indices a and b
    while b-a-1:
        a+=1
        l[a]=l[a-1]+1   # set each element value 1 larger than previous element
        l[a]=min(l[a],l[b])   # caps it by value at index b
i=1
while len(z)-i:
    f(z[i-1],z[i])      # call function for every gap
    i+=1
print l[1:]             # print result, excluding first element, added at the begining

```
> 2 votes

# Answer
# PHP, ~~95~~ ~~77~~ ~~71~~ ~~69~~ 68 bytes

```
for($p=1;$n=$argv[++$i];)echo$p=$n>0?$n:++$p-in_array($p,$argv)," ";

```

takes input from command line arguments, prints space separated list. Run with `-nr`.

**breakdown**

```
for($p=1;$n=$argv[++$i];)   # loop through arguments
    echo$p=                     # print and copy to $p:
    $n>0                            # if positive number
        ?$n                             # then argument
        :++$p                           # else $p+1 ...
            -in_array($p,$argv)         # ... -1 if $p+1 is in input values
    ," ";                       # print space

```

`$n` is truthy for any string but the empty string and `"0"`.
`$n>0` is truthy for positive numbers - and strings containing them.
> 2 votes

# Answer
## JavaScript (ES6), 65 bytes

```
a=>a.map(e=>a=e||-~a).reduceRight((r,l)=>[r[0]<l?r[0]:l,...r],[])

```

Because I wanted to use `reduceRight`. Explanation: The `map` replaces each falsy value with one more than the previous value, then the `reduceRight` works back from the end ensuring that no value exceeds the following value.
> 1 votes

# Answer
# Java 8, ~~199~~ 164 bytes

```
a->{for(int l=a.length,n,j,x,i=0;i<l;)if(a[i++]<1){for(n=j=i;j<l;j++)if(a[j]>0){n=j;j=l;}for(j=i-3;++j<n-1;)if(j<l)a[j+1]=j<0?1:a[j]+(l==n||a[n]>a[j]|a[n]<1?1:0);}}

```

Modifies the input-array instead of returning a new one to save bytes.
Uses `0` instead of `?`.

Try it online.

**Explanation:**

```
a->{                      // Method with integer-array parameter and no return-type
  for(int l=a.length,     //  Length of the input-array
      n,j,x,              //  Temp integers
      i=0;i<l;)           //  Loop `i` over the input-array, in the range [0, length):
    if(a[i++]<1){         //   If the `i`'th number of the array is 0:
                          //   (And increase `i` to the next cell with `i++`)
      for(n=j=i;          //    Set both `n` and `j` to (the new) `i`
          j<l;j++)        //    Loop `j` in the range [`i`, length):
        if(a[j]>0){       //     If the `j`'th number of the array is not 0:
          n=j;            //      Set `n` to `j`
          j=l;}           //      And set `j` to the length to stop the loop
                          //    (`n` is now set to the index of the first non-0 number
                          //     after the `i-1`'th number 0)
      for(j=i-3;++j<n-1;) //    Loop `j` in the range (`i`-3, `n-1`):
        if(j<l)           //     If `j` is still within bounds (smaller than the length)
          a[j+1]=         //      Set the `j+1`'th position to:
            j<0?          //       If `j` is a 'position' before the first number
             1            //        Set the first cell of the array to 1
            :             //       Else:
             a[j]+        //        Set it to the `j`'th number, plus:
              (l==n       //        If `n` is out of bounds bounds (length or larger)
               ||a[n]>a[j]//        Or the `n`'th number is larger than the `j`'th number
               |a[n]<1?   //        Or the `n`'th number is a 0
                1         //         Add 1
               :          //        Else:
                0);}}     //         Leave it unchanged by adding 0

```
> 1 votes

# Answer
# Perl 6, 97 bytes

```
{my $p;~S:g/(\d+' ')?<(('?')+%%' ')>(\d*)/{flat(+($0||$p)^..(+$2||*),(+$2 xx*,($p=$2)))[^+@1]} /}

```

Input is either a list of values, or a space separated string, where `?` is used to stand in for the values to be replaced.

Output is a space separated string with a trailing space.

Try it

## Expanded:

```
{                       # bare block lambda with implicit parameter ｢$_｣

    my $p;              # holds the previous value of ｢$2｣ in cases where
                        # a number is sandwiched between two replacements

    ~                   # stringify (may not be necessary)
    S                   # replace
    :global
    /
        ( \d+ ' ' )?    # a number followed by a space optionally ($0)

        <(              # start of replacement

          ( '?' )+      # a list of question marks
          %%            # separated by (with optional trailing)
          ' '           # a space

        )>              # end of replacement

        (\d*)           # an optional number ($2)

    /{                  # replace with the result of:

        flat(

          +( $0 || $p ) # previous value or 0
          ^..           # a range that excludes the first value
          ( +$2 || * ), # the next value, or a Whatever star

          (
            +$2 xx *,   # the next value repeated endlessly

            ( $p = $2 ) # store the next value in ｢$p｣
          )

        )[ ^ +@1 ]      # get as many values as there are replacement chars
    } /                 # add a space afterwards
}

```
> 1 votes

# Answer
## Q, 63 bytes

`{1_(|){if[y>min x;y-:1];x,y}/[(|){if[y=0;y:1+-1#x];x,y}/[0,x]]}`

Essentially the same algorithm as Ørjan Johansen's Haskell answer.

* Assumes ? = 0.
* Inserts a 0 at the start of the array in case of ? at start.
* Scans the array replacing 0 with 1+previous element.
* Reverses the array and scans again, replacing elements greater than previous element with previous element.
* Reverses and cuts the first element out (the added 0 from the beginning).

Use of min vs last was used to save one byte, since can assume the last element will be the min element given the descending sort of the array.
> 1 votes

# Answer
# TI-Basic (TI-84 Plus CE), 81 bytes

```
not(L<sub>1</sub>(1))+L<sub>1</sub>(1→L<sub>1</sub>(1
For(X,2,dim(L<sub>1</sub>
If not(L<sub>1</sub>(X
1+L<sub>1</sub>(X-1→L<sub>1</sub>(X
End
For(X,dim(L<sub>1</sub>)-1,1,-1
If L<sub>1</sub>(X)>L<sub>1</sub>(X+1
L<sub>1</sub>(X+1→L<sub>1</sub>(X
End
L<sub>1</sub>
```

A simple port of Ørjan Johansen's Haskell answer to TI-Basic. Uses 0 as null value. Takes input from L1.

Explanation:

```
not(L<sub>1</sub>(1))+L<sub>1</sub>(1→L<sub>1</sub>(1 # if it starts with 0, change it to a 1
For(X,2,dim(L<sub>1</sub>     # starting at element 2:
If not(L<sub>1</sub>(X              # if the element is zero
1+L<sub>1</sub>(X-1→L<sub>1</sub>(X            # change the element to one plus the previous element
End
For(X,dim(L<sub>1</sub>)-1,1,-1 # starting at the second-last element and working backwards
If L<sub>1</sub>(X)>L<sub>1</sub>(X+1           # if the element is greater than the next
L<sub>1</sub>(X+1→L<sub>1</sub>(X               # set it equal to the next
End
L<sub>1</sub>                   # implicitly return
```
> 1 votes

# Answer
# Python 2, ~~144~~ ~~124~~ 119 bytes

```
l=input()
for n in range(len(l)):a=max(l[:n]+[0]);b=filter(abs,l[n:]);b=len(b)and b[0]or-~a;l[n]=l[n]or a+(b>a)
print l

```

Try it online!

---

Uses `0` instead of `?`
> 0 votes

# Answer
# JavaScript (ES6), 59

A function with an integer array as input. The empty spots are marked with `0`

```
a=>a.map((v,i)=>v?w=v:(a.slice(i).find(x=>x)<=w?w:++w),w=0)

```

**Test**

```
var F=
a=>a.map((v,i)=>v?w=v:(a.slice(i).find(x=>x)<=w?w:++w),w=0)

;[[2, 4, 10]
,[1, 0, 3]
,[1, 0, 4]
,[]
,[8]
,[0]
,[0, 0, 0]
,[0, 1]
,[0, 2]
,[0, 3]
,[45, 0]
,[1, 0, 0, 0, 1]
,[3, 0, 0, 0, 0, 30]
,[1, 0, 2, 0, 3, 0, 4]
,[1, 0, 3, 0, 5, 0, 7]
,[1, 0, 3, 0, 5, 0, 0, 7]
,[1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 0, 4, 0, 0, 6]
,[98, 0, 0, 0, 102, 0, 104]]
.forEach(a=>{
  console.log(a+'\n'+F(a))
})
```
> 0 votes

# Answer
# C# (.NET Core), 182 bytes

Using the same strategy as Ørjan Johansen.

Uses 0 in the input list to mark the unknown var.

```
l=>{if(l[0]<1)l[0]=1;int j;for(j=0;j<l.Length;j++)l[j]=l[j]==0?l[j-1]+1:l[j];for(j=l.Length-2;j>=0;j--)l[j]=l[j]>l[j+1]?l[j+1]:l[j];foreach(var m in l) System.Console.Write(m+" ");};

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-p`, 99 bytes

```
s,(\d+ )?\K((\? )+)(?=(\d+)),$d=$1;$l=$4;$2=~s/\?/$d<$l?++$d:$l/rge,ge;($d)=/.*( \d+)/;s/\?/++$d/ge

```

Try it online!
> 0 votes

---
Tags: code-golf, number, arithmetic, integer
---


title: Create a Boolean Calculator

text:
# Question
Title: Create a Boolean Calculator
Our boolean operators are `AND`, `OR`, `XOR`, `NAND`, `NOR`, `XNOR` and, in conjunction with one of those operators, `NOT`.

Our numbers are \\$1\\$ and \\$0\\$.

The challenge is to write a program or function that calculates the results of the input.

## Input

A string, array or other input format of your choice; containing alternating numbers and operators, e.g. `1 NOR 1` or `["1","OR","0","AND","1"]` or `0XOR0XNOR1`.

**As an exception, `NOT` must always come directly after another operator (e.g. `0 AND NOT 1`).**. You can't implement `NOT` by itself, and you won't ever get a chain of multiple NOTs (so `1 AND NOT NOT 0` is an invalid input).

The input must contain the *strings* for the operators (upper or lower-case is fine); no other representation can be used e.g. `.+^¬||&&` etc.

## Output

Return or print a single number (\\$1\\$ or \\$0\\$), derived using the calculation below. Invalid input can lead to any output you choose, or none.

## Calculation

We're ignoring any precedence rules here - just calculate them in the order they come in (i.e. left-to-right) - as if someone was typing it into a calculator and pressing Enter after each number. `NOT` is the only one that might cause some difficulties with that logic, as you need to figure out what it's `NOT`-ing before you can apply the other operator.

## Truth Tables

```
INPUT   OUTPUT
A   B   AND NAND OR NOR XOR XNOR
0   0    0   1   0   1   0   1
0   1    0   1   1   0   1   0
1   0    0   1   1   0   1   0
1   1    1   0   1   0   0   1

IN OUT
A  NOT A
0    1
1    0

```

## Examples

* `1 NOR 1` = `0`
* `1 NOR NOT 0` = `0` (equivalent to \\$1\\$ NOR \\$1\\$)
* `1 NOR NOT 0 AND 1` = `0` (equivalent to \\$0\\$ (from above) AND \\$1\\$)
* `1 NOR NOT 0 AND 1 OR 1` = `1` (equivalent to \\$0\\$ (from above) OR \\$1\\$)
* `1 NOR NOT 0 AND 1 OR 1 XNOR 1` = `1` (equivalent to \\$1\\$ (from above) XNOR \\$1\\$)
* `1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0` = `1` (equivalent to \\$1\\$ (from above) NAND \\$1\\$)
* `1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0 XOR NOT 0` = `0` (equivalent to \\$1\\$ (from above) XNOR NOT \\$0\\$ = \\$1\\$ XNOR \\$1\\$ = \\$0\\$)

## Scoring

This is code-golf, but with a twist.

Your score is the number of bytes in your code, *divided by* the number of operators your code implements. Smallest score wins.

For example, if you only implement `AND`, your score is the number of bytes of your code.

If you implement `AND`, `OR`, `XOR`, `NAND`, `NOR`, `XNOR`, `NOT` (the full list of operators); then you get to divide the number of bytes by 7.

You must implement at least one operator, and you cannot implement `NOT` by itself; as it *must* be preceded by another, different operator and so doesn't count as implemented otherwise.

*Just because someone has a low score already, don't let that put you off trying to get the best score for your language! It would be interesting to compare across different numbers of implemented operators too - e.g. you might have a bad score for 2 operators, but you might be able to implement 7 really efficiently.*

# Answer
> 18 votes
# Python, 3 bytes ÷ 1 op = score 3

```
min

```

Try it online!

Implements `AND`, with inputs like `["1", "AND", "0", "AND", "0"]`. Simply takes the smallest string value, which is "0" if present and "1" otherwise. Since "AND" is later alphabetically, it can be ignored.

Another solution is `all`, using inputs like `[1, "AND", 0, "AND", 0]` since only `0` is Falsey. Python 2 could also do `min` with such inputs, since it has numbers as smaller than strings, whereas Python 3 refuses to compare them.

# Answer
> 13 votes
# Pyth, 1 byte ÷ 2 = 0.5

```
v

```

Try it online!

This works for `and` and `not`. Works by evaluating the input as python code

# Answer
> 9 votes
# Python 3, ~~16~~ 4 bytes / 2 = 2 score

```
eval

```

Try it online!

This works for `and` and `not` in any combinations. It partially works for `or` but only when not used in conjunction with `and` in certain cases due to operator precedence in Python. As such cases exist, my official score will only be divided by two (if half-points are allowed, this could maybe be divided by 2.5 instead to get a final score of 1.6)

# Answer
> 8 votes
Sorry to report that the task is trivial in some language, but anyway here it is.

# , 2 bytes, score 2 ÷ 1 = 2

```
".

```

Try it online!

Implements any one of AND, OR, or XOR. The three are defined in the J standard library as infix functions, so calling `".` (eval) on the string automagically evaluates the given expression as-is. The only problem is that J evaluates from right to left, so the three cannot be used at once.

Since it is boring, here are some attempts at adding features one at a time:

# , 10 bytes, score 10 ÷ 3 = 3.33

```
[:".|.&.;:

```

Try it online!

Implements all of AND, OR, and XOR. Since all six operators (except NOT) are symmetric, in order to fix the evaluation order, it suffices to reverse the order of words.

```
[:".|.&.;:  NB. Input: the expression with space-separated tokens
            NB. Example input '1 AND 1 XOR 0'
      &.;:  NB. Split into words ['1', 'AND', '1', 'XOR', '0']
    |.      NB. Reverse the order of words ['0', 'XOR', '1', 'AND', '1']
      &.;:  NB. Join the words back, with spaces in between '0 XOR 1 AND 1'
[:".        NB. Eval it

```

At this point, adding a feature is a matter of defining a named infix function.

# , 18 bytes, score 18 ÷ 4 = 4.5

```
NOR=:+:
[:".|.&.;:

```

Try it online!

Adds NOR (`+:`) to the list.

# , 26 bytes, score 26 ÷ 5 = 5.2

```
XNOR=:=
NOR=:+:
[:".|.&.;:

```

Try it online!

Adds XNOR (`=`) to the list.

# , 35 bytes, score 35 ÷ 6 = 5.83

```
NAND=:*:
XNOR=:=
NOR=:+:
[:".|.&.;:

```

Try it online!

Adds NAND (`*:`) to the list.

Using the same strategy to add NOT is a bit more tricky, since the word order would look like `1 NOT AND 1` instead of `1 AND NOT 1`, and it should negate the number on its left. I solved it by making it a "conjunction", which has higher precedence over regular functions or "verbs" and consumes two tokens on the both sides of it. It is defined as

```
NOT=:2 :'y v-.u'

```

and it evaluates like this: given `0 NOT AND 1`, `u`, `v`, `y` become `0`, `AND`, `1` respectively, and `y v-.u` becomes `1 AND -. 0` (where `-.` is a prefix function for logical negation), successfully negating the number on its left before applying the infix function.

# , 52 bytes, score 52 ÷ 7 = 7.43

```
NOT=:2 :'y v-.u'
NAND=:*:
XNOR=:=
NOR=:+:
[:".|.&.;:

```

Try it online!

# Answer
> 7 votes
# 05AB1E, score: 1 (1 byte, 1 operator)

```
ß

```

Input as a list of strings for each digit/operator.
Implements `AND`.

Port of *@xnor*'s Python answer.

Try it online or verify a few more test cases.

**Explanation:**

```
ß    # Pop the (implicit) input-list and leave its minimum,
     # which is "0" if the input contains a "0", or "1" otherwise
     # (after which this is output implicitly as result)

```

---

# 05AB1E, score: ~7.857 (55 bytes, 7 operators)

```
1ÝÂ„€– ìs:„€ƒ€—#„nxvDyìì}„&~SD'_«ì'^õšD'_«ìì:#ðš2ôí˜J.V

```

Input is a single lowercase string.
Implements all 7 operators.

Try it online or verify all test cases.

**Explanation:**

***Step 1:*** Replace the `not 1`/`not 0` with `0`/`1` respectively:
I.e. `1 nor not 0 and 1 or 1 xnor 1 nand 0 xor not 0` is converted to `1 nor 1 and 1 or 1 xnor 1 nand 0 xor 1`.

```
1Ý                   # Push list [0,1]
  Â                  # Bifurcate it (short for Duplicate & Reverse copy): [1,0]
   „€–               # Push dictionary string "not "
       ì             # Prepend it in front of both: ["not 1","not 0"]
        s            # Swap so the [0,1] is at the top of the list again
         :           # Replace all ["not 1","not 0"] with [0,1] in the (implicit) input

```

***Step 2:*** Replace all other operations `xnor`/`xor`/`nand`/`nor`/`and`/`or` with `^_`/`^`/`&_`/`~_`/`&`/`~` respectively:
I.e. `1 nor 1 and 1 or 1 xnor 1 nand 0 xor 1` is converted to `1 ~_ 1 & 1 ~ 1 ^_ 1 &_ 0 ^ 1`.

```
„€ƒ€—                # Push dictionary string "and or"
     #               # Split it on spaces: ["and","or"]
      „nx            # Push string "nx"
         v           # Loop `y` of its characters:
          D          #  Duplicate the list at the top of the stack
           yì        #  Prepend the current letter to each string in the list
             ì       #  Prepend-merge the lists together
         }           # Stop the loop. We now have the list:
                     #  ["xnand","xnor","xand","xor","nand","nor","and","or"]
„&~                  # Push string "&~"
   S                 # Convert it to a list of characters: ["&","~"]
    D                # Duplicate it
     '_«            '# Append "_" to each: ["&_","~_"]
        ì            # Prepend-merge it: ["&_","~_","&","~"]
         '^         '# Push "^"
           õš        # Convert it to a list, and prepend an empty string: ["","^"]
             D       # Duplicate it
              '_«   '# Append "_" to each: ["_","^_"]
                 ì   # Prepend-merge it: ["_","^_","","^"]
                  ì  # Prepend-merge it: ["_","^_","","^","&_","~_","&","~"]
:                    # Replace all ["xnand","xnor","xand","xor","nand","nor","and","or"]
                     # with ["_","^_","","^","&_","~_","&","~"]

```

`&~^` are builtins for bitwise AND, OR, and XOR respectively. And `_` is the `==0` builtin (which converts `0` to `1` and vice-versa).

***Step 3:*** Convert it to Reverse Polish notation:
I.e. `1 ~_ 1 & 1 ~ 1 ^_ 1 &_ 0 ^ 1` is converted to `1 1~_1&1~1^_0&_1^`.

```
 #                   # Split the string by spaces
  ðš                 # Prepend a leading " " to the list
    2ô               # Split the list into parts of size 2
      í              # Reverse each pair
       ˜J            # Flattened join everything together

```

***Step 4:*** Execute/evaluate it as 05AB1E code, and output the result:
I.e. `1 1~_1&1~1^_0&_1^` results in `0`.

```
         .V          # Evaluate/execute it as 05AB1E code
                     # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `„€–`  is `"not "` and `„€ƒ€—` is `"and or"`.

# Answer
> 7 votes
# Python 2, score 15.714 (~~132~~ ... ~~114~~ 110 bytes, 7 operators)

Input is a single string with lowercase operators.

```
b=c=d=49
for a in input().replace('t ','a').split():a=hash(a);c,d=[a|d,a&d,a^d^1][b%65%3]^b%45,c;b=a
print~c&1

```

Try it online!

The code uses the following numbers produced by Python 2's `hash` function:

```
+--------+----------------------+-----+--------+--------+
| string |    h=hash(string)    | h&1 | h%65%3 | h%45&1 |
+--------+----------------------+-----+--------+--------+
| and    |  1453079729200098176 |     |      0 |      0 |
| nand   | -4166578487142698835 |     |      0 |      1 |
| or     |    14208085359128317 |     |      1 |      0 |
| nor    |  5261102140395498078 |     |      1 |      1 |
| xor    | -5999452984713080668 |     |      2 |      0 |
| xnor   |   485507670233933377 |     |      2 |      1 |
|        |                      |     |        |        |
| 0      |           6144018481 |   1 |        |        |
| 1      |           6272018864 |   0 |        |        |
| noa0   | -4166584487129698722 |   0 |        |        |
| noa1   | -4166584487129698721 |   1 |        |        |
+--------+----------------------+-----+--------+--------+

```

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~43~~ 36 bytes ÷ 6 = 6

Thank you user41805 for the idea of combining definitions that are negations of each other and to tsh for noticing stray spaces.

```
DNAN←~DNA←∧
RON←~RO←∨
ROX←~RONX←=
⍎⌽

```

Try it online!

Since APL is right-to-left, we define the functions with reversed names, then reverse the expression () and execute it ().

---

# APL (Dyalog Unicode), ~~57~~ 50 bytes ÷ 7 = 7.14

Thank you user41805 for the idea of combining definitions that are negations of each other and to tsh for noticing stray spaces.

```
DNAN←~DNA←∧
RON←~RO←∨
ROX←~RONX←=
TON←{⍵ ⍵⍵~⍺⍺}
⍎⌽

```

Try it online!

Since APL is right-to-left, we define the functions with reversed names, then reverse the expression () and execute it (). NOT (`TON`) requires special treatment. We define it as a dyadic operator (`{``}`) because this makes it bind stronger to its operands. We then negate the left (original right) operand (`~⍺⍺`) and apply the right operand (`⍵⍵` — originally on its left) with the right argument ( originally from its left) as left argument. The arguments' sides doesn't matter since all functions are commutative.

# Answer
> 3 votes
# Japt, 1 byte ÷ 1 = 1

```
e

```

Try it online!

Implements only `and`. Works by checking if every element in the input has a truthy value.

# Answer
> 3 votes
# FEU, 33 bytes, 2 operations, score 16.5

```
m/NOT 0/1/NOT 1/0/.*1.*/1/[^1]+/0

```

Try it online!

Implements `NOT` and `OR`

# Answer
> 2 votes
# Retina 0.8.2, 84 bytes, score 12

```
NOT0
1
NOT1
0
^(0A|1NO|(0NA|1O))[A-Z]+.
$#2
}`^(1A|0O|0XO|1XN)[A-Z]+

}`^.[A-Z]+
NOT

```

Try it online! Link includes test suite that deletes spaces from the input for the convenience of the user. Explanation:

```
NOT0
1
NOT1
0

```

Handle the NOT operator.

```
^(0A|1NO|(0NA|1O))[A-Z]+.
$#2

```

`0 AND` and `1 NOR` are always `0`, while `0 NAND` and `1 OR` are always `1`, regardless of the RHS.

```
}`^(1A|0O|0XO|1XN)[A-Z]+

```

`1 AND`, `0 OR`, `0 XOR` and `1 XNOR` leave the RHS unchanged. Repeat the above operations until an operation that inverts the RHS is reached.

```
}`^.[A-Z]+
NOT

```

Replace this operation with a `NOT` and loop around to start processing operations again.

# Answer
> 2 votes
# APL (Dyalog Extended), 2 bytes ÷ 1 = 2

```
~⍲

```

Try it online!

(nand) returns 1 if and only if argument has a 0 anywhere (it ignores all other data)

`~` negates that

---

# APL (dzaima/APL), 2 bytes ÷ 1 = 2

```
1∊

```

Try it online!

Simply asks *is there any 1 in the argument?*

# Answer
> 2 votes
# Perl 5, 86 bytes / 7 operators = 12.29

```
s/not/!/g;s/\d//;$\=1*$1;$\=eval"$\ $_"=~s/(.*?[^a])n(.*)/!($1$2)/r for/.*?\d/g}{$\|=0

```

Try it online!

# Perl 5, 9 bytes / 3 operators (`or`, `xor`, `not`) = 3

```
$_=0|eval

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES7), 77 bytes / 7 operators = 11

Expects a string with no separator, such as `"1NORNOT0"`.

```
f=s=>1/s?s:f(s.replace(/..*?\d/,s=>10142470953/2**(parseInt(s,36)%873%34)&1))

```

Try it online!

Or try all possible sub-expressions.

### How?

We use a recursive function to simplify the input string `s` until we get a single digit. When this happens, `1/s` is either `1` or `Infinity`, which are both truthy.

As long as `s` still contains at least one operator, we use the following regular expression to isolate the next sub-expression:

```
/..*?\d/
 .         a single character (must be 0 or 1)
  .*?      followed by several characters, non-greedily
     \d    followed by a digit

```

We use this hash function (which was brute-forced) to get the result of the sub-expression and replace it in `s`:

```
10142470953 / 2 ** (parseInt(s, 36) % 873 % 34) & 1

```

# Answer
> 1 votes
# SimpleTemplate, 361 bytes ÷ 4 operators = 90.25

It is a very big piece of code, but was very challenging!

```
{@fnP S}{@fnT.AND a,b}{@ifa}{@ifa is equalb}{@return1}{@/}{@/}{@return"0"}{@/}{@fnT.OR a,b}{@incbyb a}{@ifa}{@return1}{@/}{@return"0"}{@/}{@fnT.XOR a,b}{@ifa is equalb}{@return1}{@/}{@return"0"}{@/}{@whileS matches"@([01])(AND|X?OR)(NOT)?([01])@"P}{@callT.[P.2]intoR P.1,P.4}{@ifP.3}{@setT 1,0}{@setR T.[R]}{@/}{@callstr_replace intoS P.0,R,S}{@/}{@returnS}{@/}

```

This implements the AND, OR, XOR and NOT operators.

This was entirely implemented **without** using `AND`, `OR` and `XOR`, as those don't exist in my language, at all!

It was even more challenging due to a bug in the compiler, where `{@return 0}` returns null ... :/ 6 bytes right there ...

---

You can try it on: http://sandbox.onlinephpfunctions.com/code/cb1855c48e83924bd7c81f4cda95f032c23b4abe

---

**Usage:**

Simply call the function P and pass a single string without spaces.

Returns either 0 or 1, or the whole string for invalid inputs.

Example:

```
{@call P into result "1ORNOT0"}
{@echo result}

```

---

**Ungolfed:**

Since this is a massive mess, I've also prepared an human readable version:

```
{@fn parse string}
    {@fn this.AND a, b}
        {@if a}
            {@if a is equal to b}
                {@return 1}
            {@/}
        {@/}
        {@return "0"}
    {@/}

    {@fn this.OR a, b}
        {@inc by b a}
        {@if a}
            {@return 1}
        {@/}
        {@return "0"}
    {@/}

    {@fn this.XOR a, b}
        {@if a is equal to b}
            {@return 1}
        {@/}
        {@return "0"}
    {@/}

    {@while string matches "@([01])(AND|X?OR)(NOT)?([01])@" pieces}
        {@call this.[pieces.2] into result pieces.1, pieces.4}
        {@if pieces.3}
            {@set tmp 1, 0}
            {@set result tmp.[result]}
        {@/}
        {@call str_replace into string pieces.0, result, string}
    {@/}

    {@return string}
{@/}

```

This works exactly the same way, except the function is called "parse".

---

---

**Alternative**:

Below is a SUPER boring one that has EVERYTHING pre-calculated, but has a score of 276/7 = 39.428571428571... (428571 is recurring).

```
{@fnP S}{@setL.AND"001"}{@setL.NAND"110"}{@setL.OR"011"}{@setL.NOR"100"}{@setL.XOR"010"}{@setL.XNOR"101"}{@whileS matches"@([01])(N?AND|X?N?OR)(NOT)?([01])@"P}{@ifP.3}{@setT"10"}{@setP.4 T.[P.4]}{@/}{@incbyP.4 P.1}{@callstr_replace intoS P.0,L.[P.2].[P.1],S}{@/}{@returnS}{@/}

```

It implements all operators, but ... It is kinda cheating...

Below it the ungolfed version:

```
{@fn parse string}
    {@set table.AND 0, 0, 1}
    {@set table.NAND 1, 1, 0}
    {@set table.OR 0, 1, 1}
    {@set table.NOR 1, 0, 0}
    {@set table.XOR 0, 1, 0}
    {@set table.XNOR 1, 0, 1}

    {@while string matches "@([01])(N?AND|X?N?OR)(NOT)?([01])@" pieces}
        {@if pieces.3}
            {@set tmp 1, 0}
            {@set pieces.4 tmp.[pieces.4]}
        {@/}
        {@inc by pieces.4 pieces.1}
        {@set values table.[pieces.2]}
        {@call str_replace into string pieces.0, values.[pieces.1], string}
    {@/}

    {@return string}
{@/}

```

# Answer
> 1 votes
# sed, 8 bytes ÷ 1 = 8

```
/0/c0
c1

```

Try it online!

Implements only `and`.

## Explanation

```
/0/c0   # Set contents of line to 0 if line contains 0
c1      # Otherwise set contents to 1

```

# Answer
> 1 votes
# Haskell, \\$225 \div 4 = 56.25\\$

```
b(_:'A':'0':s)=b('0':s)
b(c:'A':_:s)=b(c:s)
b(_:'O':'1':s)=b('1':s)
b(c:'O':_:s)=b(c:s)
b('N':'0':s)=b('1':s)
b('N':_:s)=b('0':s)
b('0':'X':'0':s)=b('0':s)
b('1':'X':'1':s)=b('0':s)
b(_:'X':_:s)=b('1':s)
b x=x
f=(b.map(!!0))

```

Defines a function `f`, which given a list of the format `["1","AND","0"]` returns either `"1"` or `"0"`. Implements `AND`, `OR`, `NOT`, and `XOR`.

# Answer
> 0 votes
# Wolfram Language (Mathematica), 62 bytes ÷ 6 = 10.33

```
Boole@ToExpression[Capitalize@#~StringRiffle~"~"]/.a:0|1:>a>0&

```

Try it online! Pure function. Takes a list of lowercase strings as input and returns 0 or 1 as output. Supports every operation except NOT.

---

### Wolfram Language (Mathematica), 87 bytes ÷ 7 = 12.43

```
Boole@ToExpression@StringReplace[Capitalize@#~StringRiffle~"~","t~"->"t@"]/.a:0|1:>a>0&

```

Try it online! Similar to the previous solution, but it also supports NOT.

---

### Wolfram Language (Mathematica), 15 bytes ÷ 1 = 15

```
Boole@*FreeQ[0]

```

Try it online! Function. Takes a list of strings and integers as input and returns 0 or 1 as output. Only supports AND.

# Answer
> 0 votes
# JavaScript (V8), 141 bytes ÷ 7 operators, score 20.14

```
f=i=>'01'[i]||f(i.replace(/NOT./,n=>'10'[n[3]]).replace(/(.)(..)\D*(.)/,(_,a,o,b)=>({AN:a&b,OR:a|b,XO:a^b,NA:a&b^1,NO:(a|b)^1,XN:a^b^1})[o]))

```

Try it online!

Takes input as a string with capitalised operators and no padding, like `0AND1OR0`.

Recursively calculates the next value based on the first two characters of the operator. (not before replacing `NOT`s with their counterparts)

# Answer
> 0 votes
# Japt v2.0a0, 36 bytes ÷ 7 ≈ 5.14

```
e/..*?\d/@1&#e4#÷0953÷2pXn36 %873%34

```

Try it
Try all testcases
Try all possible sub-expressions

A direct port of @Arnauld's answer to Japt

## Explanation

```
e/..*?\d/@1&#e4#÷0953÷2pXn36 %873%34
e                                     // Repeatedly replace
 /..*?\d/                             // the regex /..*?\d/g with output of
         @                            // a function which takes the match as arg named X
          1&#e4#÷0953÷2pXn36 %873%34  // and returns 1 & 10142470953 / 2 ** (parseInt(X, 36) % 873 % 34)

```

The expression `1 & 10142470953 / 2 ** (parseInt(X, 36) % 873 % 34)` was brute-forced by @Arnauld

# Answer
> 0 votes
# brainfuck, 130 bytes / 1 operator = 130

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

Try it online!

Link is for a readable, commented version. Only implements `AND`. Although technically all it does is print `1` unless there is a `0` in your input, in which case it prints `0`. It might be possible to shorten this by replacing the spots where I add/subtract 48 times, but I'm lazy, so I'm going to leave it as is.

# Answer
> 0 votes
# Scala,  ~~183 bytes~~ 164 bytes / 7 ops = ~23.43

```
"OR".+(_).split("(?<=\\d)")./:(0>1){(b,o)=>val s=o.replace("NOT","")
val c=s!=o^(o.last>48)
s.count(_==78)==1^(if(s toSet 65)!(b&c)else if(s toSet 88)b^c
else b|c)}

```

Try it online!

The operators are uppercase (whitespace doesn't matter), and the output is a `Boolean`.

---
Tags: code-challenge, parsing, logic
---


title: Tips for golfing in 1+

text:
# Question
Title: Tips for golfing in 1+
What general tips do you have for golfing in 1+? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to 1+ (e.g. "remove unnecessary whitespace" is not an answer).

Please post one tip per answer.

# Answer
> 4 votes
# Subroutines can have empty names

`(|1+1<)` is a valid definition for a subroutine, invoked as `()`.

# Answer
> 2 votes
# Instead of pushing 0 and compare, do something to other numbers

As 1 is the only literal in 1+ and there's no minus operation, pushing 0 would be expensive (`11+1<`). A better choice would be change other numbers, so 1 becomes a "relative" 0. For example, if you want to flip a bit, instead of `11+1<<`, you can `1+1<`.

# Answer
> 2 votes
# Use comments for conditionals

Found this while exploiting interpreter features. Apparently Parcly Taxel thinks comments and conditionals are similar because both of them begins with "co". The comment indicators `[]` are actually instructions because there's no such thing called parsers in 1+.

This trick can sometimes save you and a few bytes from the comparison mess.

Found while exploiting interpreter features, then made a Truth-Machine with it.

---
Tags: code-golf, tips
---