# Question
Title: Generate lowest degree polynomial from sequence
# Introduction

A sequence of numbers is passed in as the input. The program has to generate the lowest degree polynomial possible. This was my first programming project in college and it would be interesting to see how much smaller the solution could have been.

# Challenge

The input is a list of integers separated by a comma. The output is simply the equation that generates that sequence. The exact output of the equation is up to you i.e. no spaces are required between terms of the polynomial but it has to be human readable. The equation has to be expressed with the variable x. The first integer in the supplied sequence will correspond with x = 1, the second integer supplied would be x = 2 etc.

i.e.

> x^2

would result in the sequence

> 1,4,9,16 NOT 0,1,4,9

# Example Input and Output

Input:

> 5,14,27,44

Output:

> 2x^2 + 3x

# Edit

I marked the questions as duplicate, thanks for the head up.

# Answer
> 1 votes
# Pari/GP, 28 bytes

```
l->polinterpolate([1..#l],l)

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 30 bytes

```
InterpolatingPolynomial[##,x]&

```

Try it online!

---
Tags: code-golf, math, integer, polynomials, equation
---


title: Russian Nesting Quine

text:
# Question
Title: Russian Nesting Quine
A Russian nesting doll, more commonly known as a Matryoshka doll, is a doll which contains a smaller version of itself, which then contains another smaller version of itself, which contains a smaller version of itself,  which contains a smaller version of itself, which contains a smaller version of itself... \- until finally, the last one is empty.

Today your goal is to emulate this Russian tradition by writing a program or function that, when it contains itself N times, will print itself containing N-1 copies of itself times.

For example, the doll program `abcd` will have the N=3 program `abababcdcdcd`, which will print the N=2 program `ababcdcd`, which prints the original N=1 program `abcd`, which finally prints N=0, which is empty. This should theoretically work for any reasonable value of N.

Rules:

* Here is a TIO program to help generate doll programs based on your program
* Standard Quine Rules apply
* Standard Loopholes apply
* 'Contains' means directly in the center of the previous version, so your solution must have a positive even number of bytes. A program of length 10 will have a copy of the original inserted after the fifth byte, then another after the tenth byte etc.
* A single trailing whitespace is allowed in the output
* As this is , your goal is to make your N=1 program as short as possible.
* An explanation of your code would be appreciated

# Answer
> 10 votes
# Underload, 4 bytes

N=1: Try it online.

```
 ()S

```

N=2: Try it online.

```
 ( ()S)S

```

N=3: Try it online.

```
 ( ( ()S)S)S

```

**Explanation:**

Self-explanatory, but I add it anyway.

* `(...)S` prints anything between the parenthesis to STDOUT
* The space before it is a no-op to make the byte-count even and comply to the rules of the challenge.

# Answer
> 10 votes
# JavaScript, ~~36~~ 32 bytes

Takes advantage of the fact that `Function.prototype.toString()` takes no arguments and will therefore ignore any that are passed to it.

Partly inspired by user202729's solution.

```
f=_=>f.toString( ).slice(14,-16)

```

---

## Try it

```
o.innerHTML=["<span>Five</span>",(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16) ).slice(14,-16) ).slice(14,-16) ).slice(14,-16))(),"<span>Four</span>",(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16) ).slice(14,-16) ).slice(14,-16))(),"<span>Three</span>",(f=_=>f.toString(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16) ).slice(14,-16))(),"<span>Two</span>",(f=_=>f.toString(f=_=>f.toString( ).slice(14,-16) ).slice(14,-16))(),"<span>One</span>",(f=_=>f.toString( ).slice(14,-16))(),"<span>Thunderbirds Are Go!</span>"].join`\n`
```

```
span{font-weight:bold;font-size:16px;line-height:1.5em;text-transform:uppercase;}span:last-child{font-size:8px;}
```

```
<pre id=o></pre>
```

# Answer
> 7 votes
# JavaScript (Node.js), 46 bytes

Full program. So `console.log` is necessary.

Use an idea from this answer to save some bytes.

```
l=console.log;   g=_=>{};l((''+g).slice(4,-1))

```

Try it online! Try it online twice! Try it online, three times!

---

My approach is similar to that used in Kevin Cruijssen's answer, find a nestable structure (a function in this case).

# Answer
> 5 votes
# Jelly, 16 bytes

```
Ṿḣ-9Ḋð}“““““““““

```

Try it online!

Doubled: Try it online!

Tripled: Try it online!

---

Jelly doesn't have any nestable structure, but its string literals are auto-terminated.

```

Ṿḣ-9Ḋ    First chain. (monadic)
Ṿ        Uneal. (to string)
 ḣ-9     Take the ead, ends at the *-9*'th character.
    Ḋ    equeue, remove the first character.

     ð             Terminate the first chain, start a new one.
      }            Convert the last monadic chain to a dyadic one.
       “““““““““   String literal.
                   This matches the pattern <dyad> <nilad>, so applies
                   the the corresponding rules. This way a link can take data
                   to the right of it.

```

---

Will try different approaches to see if they can be shorter.

# Answer
> 4 votes
# DipDup, 2 bytes

```
[]

```

It pushes the list onto the stack, and prints it without the outmost brackets.

N = 1: Try it online!

N = 2: Try it online!

N = 3: Try it online!

# Answer
> 3 votes
# dc, 4 bytes

```
 []p

```

Similar to some other answers, since strings in `dc` have start (`[`) and end (`]`) delimiters (that is, `"` doesn't perform both duties, etc.), they're nestable without any real effort. `p` to print.

N=1: Try it online!

N=2: Try it nested!

N=3: Try it nesteder!

# Answer
> 2 votes
# Tcl, 12 bytes

```
puts {}

```

Try it online!

It's just another language that also has this.

---
Tags: code-golf, quine, source-layout
---


title: Escape from the tarpit (Cops)

text:
# Question
Title: Escape from the tarpit (Cops)
This is a challenge based around defining languages and proving they are Turing complete.

This is the cops' thread. The robbers' thread is here.

# Cops

As a cop, you will prepare two things:

* A formal specification of a programming language, or other computational system. (Computational systems are defined below.)
* A proof that your system is Turing complete, according to the somewhat strict definition below.

You will post your specification of your language, and the robbers will try to "crack" it by proving its Turing completeness. If your submission is not cracked within one week you can mark it as safe and post your proof. (Your answer can be invalidated if someone finds a flaw in your proof, unless you can fix it.)

This is a , so the winner will be the answer that has the most votes, and which is not cracked or invalidated. The challenge is open-ended - I won't be accepting an answer.

For the sake of this challenge, a computational system will be defined as four things:

* A "program set" `P`. This will be a countably infinite set, e.g. strings, integers, binary trees, configurations of pixels on a grid, etc. (But see the technical restriction below.)
* An "input set" `I`, which will also be a countably infinite set, and need not be the same set as `P` (although it can be).
* An "output set" `O`, which similarly will be a countably infinite set, and may or may not be the same as `P` or `I`
* A deterministic, mechanistic procedure for producing an output `o` from program `p` and input `i`, where `p`, `i` and `o` are members of `P`, `I` and `O` respectively. This procedure should be such that it could, in principle, be implemented on a Turing machine or other abstract model of computation. The procedure may, of course, fail to halt, depending on the program and its input.

The sets `P`, `I` and `O` must be such that you can express them as strings in a computable manner. (For most sensible choices this will not matter; this rule exists to prevent you from choosing strange sets, such as the set of Turing machines that don't halt.)

Turing completeness will be defined as the following:

* For any computable partial function `f` from `I` to `O`, there exists a program `p` in `P` such that given `p` and input `i`, the output is `f(i)` if `f(i)` has a value. (Otherwise the program doesn't halt.)

The word "computable" in the above definition means "can be computed using a Turing machine".

Note that neither rule 110 nor bitwise cyclic tag are Turing-complete by this definition, because they don't have the required input-output structure. Lambda calculus is Turing complete, as long as we define `I` and `O` to be the Church numerals. (It is not Turing-complete if we take `I` and `O` to be lambda expressions in general.)

Note that you don't have to provide an implementation of your language, but you are welcome to include one in your answer if you like. However, you shouldn't rely on the implementation to define the language in any way - the spec should be complete in itself, and if there is a contradiction between the spec and the implementation this should be treated as a bug in the implementation.

# Answer
# Blindfolded Arithmetic

Possibly a fairly easy language to start off with, relatively speaking. (There are limits on how difficult a language I can make because I have to prove it Turing-complete myself!)

For this language, the program set is the set of Blindfolded Arithmetic programs as given in the section "program" below, the input set is the set of positive integers, and the output set is the set of integers (the entire set, not just the positive integers).

This language is fairly interesting – maybe even practically useful – because it has a more or less total lack of control flow, being entirely based on computations on numbers you can't see. That makes it potentially useful as a language for implementing programs inside homomorphic encryption systems.

# Specification

Blindfolded Arithmetic is an esoteric programming language with the following specifications:

## Data storage

A state of a running Blindfolded Arithmetic program consists of six variables, each of which can store an integer. (There are no limits on how large or small these integers can get; in particular, they can go negative.) The variables are called `a`, `b`, `c`, `d`, `e`, and `i`.

At the start of the program, `a` to `e` inclusive are each initialised to 0, and `i` is initialised to a positive integer taken from user input. (If no input is available, `i` is initialised to 1.)

If the program ceases execution (this can only occur due to division by zero), the value of `i` immediately before the division was attempted is used as the program's output.

## Program

A Blindfolded Arithmetic program is a list of commands, each of which has one of the following forms (where *v* can be replaced by any variable name, potentially a different name each time it's used):

* *v* `=` *v* `+` *v*
* *v* `=` *v* `-` *v*
* *v* `=` *v* `*` *v*
* *v* `=` *v* `/` *v*

Note that each operand of the commands *must* be a variable; this language does not allow the use of literal integers.

Execution of the program is performed by running each of the commands in sequence, and then looping back to the start and continuing to run the commands in sequence again, ad infinitum (or until there's an attempt to divide by zero, which ends the program).

Each command has the same semantics as you'd expect from the notation, which is no different from that used by most practical programming languages: the values of the second and third variables metioned in the command are taken, an arithmetic operation (add/subtract/multiply/divide respectively for the four forms of command) is applied to them, and the resulting value stored into the first variable. Division here is integer division, rounding towards 0.

There is no control flow of any kind, other than program exit; the commands always cycle in sequence, up until a division by zero (if any) occurs and ends the program. In particular, there's no way to directly read variables, only to use them as a source of calculations whose results impact the values assigned to other variables.
> 12 votes

---
Tags: popularity-contest, cops-and-robbers, language-design
---


title: Generate Men of Culture

text:
# Question
Title: Generate Men of Culture
This challenge is inspired by the meme Men of Culture.

The meme involves blanking out parts of the original caption,

> Ah, I see you're a man of culture as well.

to make it appear as if the character is saying something else.

Your challenge is to write a program that, given an input, **show how the original sentence can be blanked out** to achieve the input string.

Rules:

* Use a `-` character to represent a blanked out character.
* You must not add additional letters to achieve the input string
* You may treat string comparisons as case-insensitive
* You may ignore whitespace in string comparisions
* If no substitution is possible, output a falsy value.
* You may substitute redundant whitespace with a `-` as well, although not required.
* Where multiple solutions are possible, you may output any of them.

Test cases:

Basic:

Example Meme 1

```
Ah, I see you're a well.
> Ah, I see you're a --- -- ------- -- well.

```

Example Meme 2

```
Ah, I see well.
> Ah, I see ------ - --- -- ------- -- well.

```

Edge case 1:

```
What did you just say about me, you little
> false

```

Edge case 2 (edited):

```
*no input*
> --- - --- ------ - --- -- ------- -- -----

```

Intermediate:

Example Meme 3

```
Ah, I see you're Orwell.
> Ah, I see you're - --- o- -----r- -- well.

```

Example Meme 4

```
Ah, ymca.
> Ah, - --- y----- - m-- -- c------ a- ----.

```

Example Meme 5

```
Ah, a manual.
> Ah, - --- ------ a man -- -u----- a- --l-.
OR: > Ah, - --- ------ a man -- -u----- a- ---l.

```

Harder:

Example Meme 6

```
tea.
> --- - --- ------ - --- -- ---t--e a- ----.

```

Example Meme 7

```
eeeee
> --- - -ee -----e - --- -- ------e -- -e---

```

TL;DR: Given an input string, output a string which represents how the original string should be modified to fit the input string, by using a "-" to represent a blanked out character. If a substitution is not possible, output a falsy value.

Code golf, so shortest code in bytes wins.

**Edit: Clarifications**

* **Ignore whitespace in string comparisions** means you can strip away whitespace before you compare strings. For instance, the inputs `Ah, a manual` and `Ah , a manual` are treated as equal. Other punctuation `, ' .` must be preserved. Similarly for output, `Ah, a manual` is equal to `Ah, amanual`.
* **substitute redundant whitespace** refers to the spaces present in the original caption. You don't need to replace them with "-", but if replacing nets you more points then go ahead.

# Answer
# \>\<\>, 94 bytes

```
"vAh, I see you're a Man of Culture as well.
0/i~ <r
!\:?!^:}=0={:@*:@"-"$?$~}$:@?
<>~i+0)?;>o

```

Try it online!

Case-sensitive, doesn't ignore whitespace or punctuation and outputs an empty string if the input is invalid. If you want to try other strings, you can just modify the first line after the `"v`, as long as it doesn't contain a `"` or a null byte.
> 6 votes

# Answer
# Jelly, ~~58~~ ~~55~~ ~~48~~ 45 bytes

```
“¬²Ẉ,ȷCIbƝɼeỴƤ/ɓIŒ;ṫṚS⁶_ŀỤ ṂB⁾÷ƈ»Ḣ”-1ị⁼ɗ?@€xṆ

```

Try it online!

---

More readable version:

```
“Ah, I see you're a man of culture as well.”Ḣ”-1ị⁼ɗ?@€xṆ

```

String compression breakdown:

```
Ah, I{short: see}{short: you}'re a{short: man} of{long: culture} as{short: we}ll.

```
> 5 votes

# Answer
# Retina 0.8.2, 117 bytes

```
^.
¶Ah, I see you're a Man of Culture as well.¶$&
{+i`¶(\W|(\w))(.*¶)(?(2)\W*\2)
$1¶$3
}1`¶\w
-¶
.*¶.*¶.*\w.*|¶.*¶.*

```

Try it online! Could save 1 byte by requiring case-sensitivity. Could save 3 bytes by returning `--, - --- ---'-- - --- -- ------- -- ----.` on empty input. Explanation:

```
^.
¶Ah, I see you're a Man of Culture as well.¶$&

```

Prepend the desired text to the input.

```
{+i`¶(\W|(\w))(.*¶)(?(2)\W*\2)
$1¶$3

```

Move as many characters from the desired text to the result as possible. If the character is a letter then it also needs to match the next letter in the input, which is then deleted.

```
}1`¶\w
-¶

```

If there is no matching letter in the input, change it to a `-` and try again.

```
.*¶.*¶.*\w.*|¶.*¶.*

```

If there are still letters left in the input, delete everything, otherwise delete the remainder of the input.
> 5 votes

# Answer
# Python 2, ~~126~~ 114 bytes

```
i=input()
r=''
for c in"Ah, I see you're a man of culture as well.":x=c==i[:1];r+=c*x or'-';i=i[x:]
print(i=='')*r

```

Try it online!

---

# Python 2, ~~108~~ 106 bytes

Input is a list of chars.

```
lambda i:''.join(c==`i`[2:3]and i.pop(0)or'-'for c in"Ah, I see you're a man of culture as well.")*(i==[])

```

Try it online!
> 3 votes

# Answer
# JavaScript (Node.js), 135 bytes

```
x=>!!x&&(t="Ah, I see you're a Man of Culture as well.".replace(/./g,c=>c>' '?/^(.)\1/i.test(c+x)?(x=x.slice(1).trim(),c):'-':c),!x&&t)

```

Try it online!

If "may" mean either do or not do is okay, then

# JavaScript (Node.js), 106 bytes

```
x=>x&&(t="Ah, I see you're a Man of Culture as well.".replace(/./g,c=>c==x[0]?(x=x.slice(1),c):'-'),!x&&t)

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), 122 120 bytes

```
x=>"Ah, I see you're a Man of Culture as well.".replace(/./g,c=>c>' '?/^(.)\1/i.test(c+x)?(x=x.slice(1).trim``,c):'-':c)

```

Try it online!

# Explanation :

```
x =>                 // It takes in 'x' as parameter for function a string
    "Ah, I see you're a Man of Culture as well.". // What the actual is
            .replace(                             // Now we are gonna replace
                    /./g,     // selects everything
                    c =>      // lambda function with param c
                        c > ' ' ?
                        /^(.)\1/i.test(           // does it all
                            c + x ) ?            // checks if there is a match
                            (x=x.slice(1). // returns everything from 1 to end in an array
                                trim`` ,   // removes whitespaces
                            c : '-' : c)   // and done

```

---

Can be reduced further but replaces whitespaces with '-' as well. If this is acceptable then

# JavaScript (Node.js), 112 bytes

```
x=>"Ah, I see you're a Man of Culture as well.".replace(/./g,c=>/^(.)\1/i.test(c+x)?(x=x.slice(1).trim``,c):'-')

```

Try it online!

Reduced even further , only replaces whitespaces that are after the given string with '-'.

# JavaScript (Node.js), 105 bytes

```
x=>"Ah, I see you're a Man of Culture as well.".replace(/./g,c=>/^(.)\1/i.test(c+x)?(x=x.slice(1),c):'-')

```

Try it online!
> 2 votes

# Answer
# Haskell, 182 174 172 171 170 169 bytes

```
import Data.Char
t=toLower
a!b=(b:)<$>a
""%l=Just$'-'<$l
l@(a:b)%(c:d)|t a==t c=b%d!c|1>0=l%d!'-'
_%_=mempty
(%"Ah, I see you're a man of culture as well.").concat.words

```

Try it online!

Ungolfed:

```
import Data.Char

template = "Ah, I see you're a man of culture as well."

-- strip spaces
preprocess :: String -> String
preprocess = filter (/=' ')

-- case-insensitive character comparison
a#b = (toLower a) == (toLower b)

strike' :: String -> String -> Maybe String
strike' "" "" = Just ""  -- base case
strike' _ "" = Nothing   -- chars are exhausted, impossible to convert
strike' "" rem = Just $ '-' <$ rem  -- full match, strike rest of chars
strike' cur@(x:xs) (r:rs)
    | x # r     =   (r:) <$> strike' xs rs  -- character matches; pop a char
    | otherwise = ('-':) <$> strike' cur rs -- no match; strike char, don't pop

strike :: String -> Maybe String
strike xs = strike' (preprocess xs) template

```
> 2 votes

# Answer
# Brain-Flak, ~~764~~ 600 bytes

```
(((<>)))([]((((((([][][]()){}[]){})[][]){}))[[]()])[][]())([[]](([][](([][]){})[]){}())[[]])(([()()][]([[]]([()]([[]](((([()][][][])[]){}[]())[])[]))()()()))[[]])((([[][][]]((([](([()()()][]){})){})(()()()()){}())[[]])[]){})((((()((([][]){}())((()()()){}){})[[][][]]))){}{}())((()(((([]()()()())())){}{}()())[[][]]){}[])(([(()()()){}](((((()()()()){}[]))){}{}))((()()){}()){})(([()][][]([()()()][])))(((([][][]())[([]()()){}()])[]())[[]])([[]]((([]()())(()()()()){}){})()()()){([{}]<>({})){(<{}(((((()()()()())){}{})){}{})>)}{}(<({}<(<()>)<>{({}<>)<>}>{})>)<>{({}<>)<>}{}<>}{}<>{{{}}<>}<>{({}<>)<>}<>

```

Try it online!

Big improvements thanks to Jo King, especially in the string construction but also a few logical tweaks in the main body. Explanation from him

It's case-sensitive (so "Ah, I see you're Orwell." doesn't match but "Ah, I see you're orwell." does), whitespace in input is *not* ignored, and unmatched whitespace in original string is converted to `-`. By my understanding, all of those are valid options.

Explanation:

```
(476 bytes of much improved stack manipulation) #Push string

{ #While string
  ([{}]<>({})) #Check whether the top characters are equal
  {(<{}(((((()()()()())){}{})){}{})>)}{}  #If characters are not equal, push - on top of input
  (<({}<(<()>)<>{({}<>)<>}>{})>)<>{({}<>)<>}{}<>  #Take top of input (either - or matched char) and add to output
}{}
<>{{{}}<>} #Pop both stacks if input is left over
<>{({}<>)<>}<> #Reverse output

```
> 2 votes

# Answer
# Prolog (SWI), 109 bytes

```
[]+[]+[].
I+[B|X]+[C|O]:-(I=[B|J],B=C;I=J,C=45),J+X+O.
I-O:-I+`Ah, I see you're a man of culture as well.`+O.

```

Try it online!

Case-sensitive and whitespace sensitive. The `-/2` predicate is the main predicate with its first argument being the input string and the second argument being the output string.
> 1 votes

# Answer
# JavaScript (Node.js), 103 bytes

```
s=>!s[i=0,r="Ah, I see you're a man of culture as well.".replace(/./g,c=>c==s[i]&&++i||c-1?c:'-'),i]&&r

```

Try it online!

Case sensitive.
> 0 votes

# Answer
# Pyth, 78 bytesSBCS

```
V." y°äz ÂµÿéiSs¾ýØC[ócõ!ó5§n"=b.x@zZkIqbN=+kN=hZ.?=+k\-))I<Zlz!z.?k

```

**Test suite**
Unprintable characters present in code, see link for correct version.
*Case sensitive, does not ignore whitespace.*
> 0 votes

# Answer
# Perl 5 `-F`, 192 bytes

```
@q="Ah, I see you're a man of culture as well."=~/./g;while($x=shift@F){$x=~/\w/||next;while($_=shift@q){push@r,/\W/?$_:/\Q$x/i?$_:'-';$r[-1]=~/\w/i&&last}@q||last}say!$x&&@r,map/\w/?'-':$_,@q

```

Try it online!
> 0 votes

---
Tags: code-golf, string
---


title: Cyclic strings, hidden programs

text:
# Question
Title: Cyclic strings, hidden programs
Write 3 programs that do the following task:

Let A, B, C source codes of those three programs;

* if A runs BC is produced as output,
* if B runs CA is produced,
* if C runs AB is produced;

so each program writes a string (cycled for each program) and hides itself from it.

Additional, but essential constraints:

* standard loopholes are forbidden;
* each program must be at least 1 byte long;
* each of three programs *must* be written in a different language;

It would be nice if your submission had this format:

### Language A (size of A) - Language B (size of B) - Language C (size of C) - Score

```
A B C
<extra stuff>

```

Winner is someone who get the minimum score, which is the sum of sizes of three programs.

# Answer
> 3 votes
# Befunge-98, Gol\>\<\> and Wumpus 47\*3 = 141 bytes

```
"r75*1-47*0.@o&r84#o&]=74#]=\`/KHj '!_@#,k.'g00

```

Try it in Befunge! Try it in \>\<\>! Try it in Wumpus!

That's right, it's the same program three times over! When run in any of the above languages, it prints the source code twice, which is the other two programs concatenated.

### How It Works:

```
Befunge code:
  "r                               j '!_@#,k.'g00

  "   Wrapping string literal over code
   r  Reflect the pointer
  "   Wrapping string literal
                                              g00   Fetch " from cell 0,0
                                          ,k.'      Print 47 characters
                                       _@#          If the next character is 0, exit
                                      !             Otherwise, set it to 0
                                   j '              And jump back to the beginning

Gol><> code:
  "r75*1-47*0.                \`/KH

  "             Wrapping string literal
   r            Reverse stack
    75*1-       Push "
         47*0.  Jump to cell 28,0
                              \  Continue right
                               `/K   Duplicate the top 47 characters on the stack
                                  H  Halt and output stack contents

Wumpus code:
  "r75*1-47*0.@o&r84#o&]=74#]=\

  "r75*1-47*0.  Exact same function as the ><> code, but with a bouncing string literal
                              \  Reflect left
                            ]=   Push a copy of the " to the bottom of the stack
                         74#     Push 47
                       ]=        Push a copy of the 47 to the bottom of the stack
                     o&          Print the top 47 characters
                  84#            Push a '0' to make up for the missing 0 at the end
               o&r               Reverse the stack and print the top 47 characters
              @                  And terminate

```

# Answer
> 0 votes
## JScript, VBScript, Windows Batch, 345 bytes

```
a=new ActiveXObject("scripting.filesystemobject");b=a.opentextfile(".js");c=b.readline();d=b.readline();a.createtextfile(".bat").write("@echo "+d.substr(2)+">.vbs\n@echo '"+c+">>.vbs")
//set a=createobject("scripting.filesystemobject"):set b=a.opentextfile(".vbs"):c=b.readline:d=b.readline:a.createtextfile(".js").write(mid(d,2)+chr(10)+"//"+c)
```

Name the file .js, then .vbs and then .bat will be created.

---
Tags: code-golf, quine
---


# Question
Title: Count the number of ways of putting balls into bins
In this task you are given an odd number of white balls and the same number of black balls. The task is to count all the ways of putting the balls into bins so that in each bin there is an odd number of each color.

For example, say we have 3 white balls. The different ways are:

```
(wwwbbb)
(wb)(wb)(wb)

```

for the two different possibilities.

If we have 5 white balls the different ways are:

```
(wwwwwbbbbb)
(wwwbbb)(wb)(wb)
(wwwb)(wbbb)(wb)
(wb)(wb)(wb)(wb)(wb)

```

You can take the input, which is a single integer, in any way you like. The output is just a single integer.

Your code must be fast enough so that you have seen it complete for 11 white balls.

You can use any language or library that you like.

# Answer
# Pari/GP, 81 bytes

```
p=polcoeff;f(n)=p(p(prod(i=1,n,prod(j=1,n,1+(valuation(i/j,2)==0)*x^i*y^j)),n),n)

```

For more efficiency, replace `1+` with `1+O(x^(n+1))+O(y^(n+1))+` (the first `O` term alone already helps a lot).

Try it online! (earlier 86 byte version with a pair of unneeded parens and without the `p=` abbreviation)

### Old version, 90 bytes

```
f(n)=polcoeff(polcoeff(taylor(1/prod(i=0,n,prod(j=0,n,1-x^(2*i+1)*y^(2*j+1))),x,n+1),n),n)

```

Computing `f(11)` needs a bigger stack size, the error message will tell you how to increase it. It's more efficient (but less golfy) to replace the two `n` that appear as second arguments to `prod` with `(n-1)/2`.
> 5 votes

# Answer
# Python 3, 108 bytes

```
C=lambda l,r,o=():((l,r)>=o)*l*r%2+sum(C(l-x,r-y,(x,y))for x in range(1,l,2)for y in range(1,r,2)if(x,y)>=o)

```

Recursively enumerates all sets, making sure to not get duplicates by always generating the sets in order. Reasonably fast when memoized using `C = functoools.lru_cache(None)(C)`, but this is not necessary for `n = 11`.

Call `C(num_white, num_black)` to get your result. First couple of `n`:

```
1: 1
3: 2
5: 4
7: 12
9: 32
11: 85
13: 217
15: 539
17: 1316
19: 3146
21: 7374

```

To generate the results:

```
def odd_parts(l, r, o=()):
    if l % 2 == r % 2 == 1 and (l, r) >= o:
        yield [(l, r)]

    for nl in range(1, l, 2):
        for nr in range(1, r, 2):
            if (nl, nr) < o: continue
            for t in odd_parts(l - nl, r - nr, (nl, nr)):
                yield [(nl, nr)] + t

```

E.g. for (7, 7):

```
[(7, 7)]
[(1, 1), (1, 1), (5, 5)]
[(1, 1), (1, 1), (1, 1), (1, 1), (3, 3)]
[(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)]
[(1, 1), (1, 1), (1, 1), (1, 3), (3, 1)]
[(1, 1), (1, 3), (5, 3)]
[(1, 1), (1, 5), (5, 1)]
[(1, 1), (3, 1), (3, 5)]
[(1, 1), (3, 3), (3, 3)]
[(1, 3), (1, 3), (5, 1)]
[(1, 3), (3, 1), (3, 3)]
[(1, 5), (3, 1), (3, 1)]

```
> 7 votes

# Answer
# Python 3, ~~180~~ 172 bytes

```
def f(n):
 r=range;N=n+1;a=[N*[0]for _ in r(N)];R=r(1,N,2);a[0][0]=1
 for i in R:
  for j in R:
   for k in r(N-i):
    for l in r(N-j):a[k+i][l+j]+=a[k][l]
 return a[n][n]

```

Try it online!

Straightforward implementation of the generating function. Long but (somewhat) efficient. O(n4) time, O(n2) memory.

The resulting array `a` contains all results of all sizes up to `n`, although only `a[n][n]` is returned.
> 2 votes

# Answer
# Python 2, ~~168~~ 181 bytes

```
from itertools import*
r,p=range,product
def f(n):
 a,R=eval(`[[0]*n]*n`),r(1,n,2);a[0][0]=1
 for i,j in p(R,R):
  for k,l in p(r(n-i),r(n-j)):a[k+i][l+j]+=a[k][l]
 return a[-1][-1]

```

Try it online!
> 1 votes

---
Tags: code-golf, combinatorics
---


title: Four Spiraling Axes

text:
# Question
Title: Four Spiraling Axes
Take the numbers `0, 1, 2, 3, 4, ...` and arrange them in a clockwise spiral, starting downward, writing ***each digit*** in its own separate square.

Then, given one of four distinct and consistent ASCII characters (your choice) representing an axis, and an input integer `n`, output the first `n` terms of the sequence described by selecting squares along the corresponding axis.

For example, below is the arranged spiral up to partway through `29`. Suppose we use `u / d / l / r` for our four characters, representing `up / down / left / right`. Then, given `u` as input, we output `0, 5, 1, 4 ...` (the positive y-axis) up to the `n`th term. If we were instead given `l` as input, then it would be `0, 3, 1, 1 ...` up to the `n`th term.

```
  2---3---2---4---2---5---2
  |                       |
  2   1---3---1---4---1   6
  |   |               |   |
  2   2   4---5---6   5   2
  |   |   |       |   |   |
  1   1   3   0   7   1   7
  |   |   |   |   |   |   |
  2   1   2---1   8   6   2
  |   |           |   |   |
  0   1---0---1---9   1   8
  |                   |   |
  2---9---1---8---1---7   2

```

These are sequences on OEIS:

### Examples

```
d 19
[0, 1, 1, 8, 3, 7, 6, 2, 1, 5, 1, 1, 6, 2, 2, 1, 3, 4, 0]

r 72
[0, 7, 1, 7, 4, 2, 8, 1, 1, 3, 1, 2, 0, 2, 3, 1, 3, 4, 6, 5, 5, 5, 7, 7, 8, 8, 9, 6, 8, 1, 1, 1, 2, 3, 1, 8, 0, 6, 1, 7, 0, 9, 2, 8, 4, 3, 2, 1, 1, 7, 2, 6, 2, 1, 3, 3, 5, 5, 3, 2, 2, 0, 4, 3, 2, 5, 4, 6, 5, 0, 5, 1]

u 1
[0]

```

## Rules

* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* If you're using integers to represent the four axes, you can use negative integers without breaking the rules.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 5 votes
# Python 2, ~~94~~ ~~89~~ ~~84~~ ~~83~~ ~~74~~ ~~72~~ 70 bytes

I used WolframAlpha and determined that an upper bound of 5n \> 4n2+3n seems to be enough. It can be changed to 9n at no cost. For trying larger inputs, use `9*n*n` instead of `5**n` to avoid running out of memory.

```
lambda d,n:["".join(map(str,range(5**n)))[x*(4*x+d)]for x in range(n)]

```

**Try it online!**

The inputs for directions are:

* 3: right
* -3: down
* -1: left
* 1: up

*Saved 14 bytes thanks to Rod*
*Saved 2 bytes thanks to Jonathan Allan*

# Answer
> 1 votes
# MATL, 32 bytes

```
tE1YLtn:qVXzw)3Lt3$)iX!w:qyfYm+)

```

Input is `n`, `a`, where `a` represents the axis as follows:

* `0`: left;
* `1`: up;
* `2`: right;
* `3`: down.

Output is a string.

Try it online! Or verify all test cases.

# Answer
> 1 votes
will work for considerable n (like +1000)

# JavaScript (Node.js), 104 bytes

```
f=(d,n)=>--n?[...f(d,n),C(n*(4*n+d))]:[0]
C=(n,N=i=0)=>n>N?C(n-N,(p=10**i)*9*++i):+((p+--n/i|0)+"")[n%i]

```

Try it online!

### Explanation

* 3: right
* -3: down (-3 is legit according to comments)
* -1: left
* 1: up (like @mbomb007)

C- nth digit of Champernowne's constant

## \________________________________________________________

Less efficient method (wont work for 1000+)

# JavaScript (Node.js), 81 bytes

```
f=(d,n)=>eval(`for(r=[],s=i=I="";I<n;)(s+=i++)[u=I*(4*I+d)]&&r.push(s[I++,u]),r`)

```

Try it online!

# Answer
> 1 votes
# Jelly,  ~~19~~  18 bytes

Uses the 5n trick from mbomb007's Python answer

```
4,0jḅɗ@€ị5*D€FʋṖ0;

```

A dyadic link taking `n` on the left and `d` and integer from: `[-3,-1,1,3]:[v,<,^,>]`

**Try it online!**

A 20 byte alternative that is both much faster and does not segfault for such small n is:

```
²×5D€ƲFị@4,0jḅɗ@€Ṗ0;

```

**Try it online!**

### How?

```
4,0jḅɗ@€ị5*D€FʋṖ0; - Link: integer, n; integer, d
     ɗ@€           - last three links as a dyad with sw@pped arguments for €ach (of implicit range [1,n])
4,0                -   literal list [4,0]
   j               -   join with d = [4,d,0]
    ḅ              -   convert from base n = 4*n^2+d*n+0
        ị          - index into...
              ʋ    - last four links as a monad:
         5         -   five
          *        -   exponentiate = 5^n
           D€      -   decimal list of each (in implicit range [1,5^n])
            F      -   flatten into a single list of the digits
               Ṗ   - pop (drop the final element)
                0; - prepend a zero

```

# Answer
> 0 votes
# Stax, 13 bytes

```
â╞ê←τ"(]]⌐┘?N

```

Run and debug it

It takes input with the direction, followed by the count. Right, up, left, and down are `1`, `3`, `5`, and `7` respectively. It takes a full minute to run the three provided test cases.

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


title: Print valid arithmetic expressions

text:
# Question
Title: Print valid arithmetic expressions
Recursively define a "valid arithmetic expression":

1. Any natural number is a valid arithmetic expression.
2. If `s` is a valid arithmetic expression, then so is `(-s)`.
3. If `p` and `q` are valid arithmetic expressions, then so is `(p+q)`.

In the above, a "natural number" is recursively defined as follows:

1. `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` are natural numbers.
2. If a natural number `n` is not `0`, then `n0` `n1` `n2` `n3` `n4` `n5` `n6` `n7` `n8` `n9` are natural numbers.

Alternatively, via the regex `/^(0|[1-9][0-9]*)$/`

Examples of valid arithmetic expressions:

```
0
314
(-7)
(0+0)
(314+(-314))

```

Examples of invalid arithmetic expressions:

```
01
-5
5+10

```

---

The challenge is to **print every valid arithmetic expression line by line**, i.e. create a program that will output strings line by line with the constraint that every valid arithmetic expression is eventually printed, and that no invalid arithmetic expression is ever printed.

The valid arithmetic expressions can be printed more than once.

The challenge is to do so in as few bytes as possible, since this is .

Standard loopholes apply.

# Answer
> 1 votes
# Jelly, ~~...~~ 33 bytes

```
⁾()j
p`j”+Ç$€;;”-;ÇƊ€;®‘©¤Ṅ€
WÇ1¿

```

Try it online!

Wow, writing a correct submission is **hard**.

---

Python pseudocode equivalent:

```
import itertools

# Jelly: ⁾()j
def wrap_in_parentheses(x):
 return str(x).join(['(',')'])
 # or equivalently, `return '('+str(x)+')'

# Jelly: p`j”+Ç$€;;”-;ÇƊ€;®‘©¤Ṅ€
register = 0
def expand_and_print(expressions):
 # Jelly: p`
 result = list(itertools.product(expressions, repeat=2))

 # Jelly: j”+Ç$€
 result = [wrap_in_parentheses('+'.join(expr)) for expr in result]

 # Jelly: ;
 result.extend(expressions)

 # Jelly: ;”-;ÇƊ€
 result.extend([wrap_in_parentheses('-'+expr) for expr in expression])

 # Jelly: ;®‘©¤
 global register
 register += 1
 result.append(register)

 # Jelly: Ṅ€
 for expr in result:
  print(expr)

 return result

# Jelly: WÇ1¿
expressions = ['0']
while 1:
 expressions = expand_and_print(expressions)

```

# Answer
> 1 votes
# JavaScript ES6, 79 bytes

```
for(x=[n=0];;++n)x.map(i=>x.map(j=>x.push(n,`(-${i})`,`(${i}+${j})`))+alert(i))

```

# Answer
> 1 votes
# Python, 241 bytes

```
g=lambda n,s=0:s<6 and(l+r for x in(["\x13 8"]+list("I-x</"))[s]for a in range(n)for l in g(a,ord(x)%12)for r in g(n-a,ord(x)//12))or[]if n^1else s>7and["(-)+"[s-8]]or list("0123456789"[s==7:])*(s%6<2)
i=1
while i:print("\n".join(g(i)));i+=1

```

This isn't too short, but it's a table-driven approach that's semi-automatically generated from a CFG I wrote for this language. It's unreasonably fast (speed sacrificed for bytes) :)

---
Tags: code-golf, string, grammars
---


title: Overlapping Strings

text:
# Question
Title: Overlapping Strings
# Challenge

A simple challenge: given two or more strings, output all of the substrings that are in each string.

# Rules

* Input is always a comma separated list of strings
* Strings should be outputted from longest to shortest length without duplicates
* Strings should preserve whitespace

# Examples

```
Input: aaa,aa
Output:
aa
a

Input: ababa,aba
Output:
aba
ab
ba
a
b

Input: Hello\, world!, Hello world!
Output:
 world!
world!
 world
 worl
world
orld!
Hello
orld
rld!
ello
 wor
Hell
worl
ell
rld
 wo
ld!
llo
wor
orl
Hel
d!
ll
 w
lo
rl
wo
or
He
el
ld
o
l
r
H
e
d
!
w

```

# Answer
# 05AB1E, 9 bytes

```
€Œ.»ÃÙéR»

```

Try it online!

**Explanation**

```
€Œ         # get the substrings of each
  .»Ã      # reduce by intersection
     Ù     # remove duplicates
      é    # sort by length
       R   # reverse
        »  # join on newline

```
> 2 votes

# Answer
# Jelly, 6 bytes

```
Ẇ€f/QṚ

```

Try it online!

```
Ẇ€f/QṚ  Main Link
 €      For each string
Ẇ       Get all substrings
   /    Reduce this list of lists by
  f     Filter (intersection)
    Q   Remove duplicates
     Ṛ  Reverse

```
> 1 votes

# Answer
# Pyth, 8

```
_{@Fm.:d

```

## Explanation

```
        Q  # Implicit input list of 2 strings
    m.:d   # get lists of all substrings of each input string
  @F       # intersection
 {         # deduplicate
_          # reverse

```

Online test.
> 1 votes

---
Tags: code-golf, string
---


title: Quine of orders

text:
# Question
Title: Quine of orders
Write a program that, when run in different languages, outputs a different byte permutation of the code in each language. The exact source code is counted as one permutation.

Here "different language" can be different version(Py 2 and Py 3) or different standard flags. It's different output that forces different version.

Proper quine rules apply for the program in each language. Your score is calculated as `(Language count)^6/(Code length in bytes)`, with a higher score being better.

**Sample:**

If your code is `AAB` and running in three different languages returns `ABA`, `AAB` and `AAB`, then its score is `2^6/3`(only one of the two `AAB` count). It's fine if `ABA` is meaningless.

# Answer
# Befunge-98, \>\<\>, Gol\>\<\>, Fission, Wumpus, Cardinal, Beeswax and Alice Score: 86/88 = 2978.909

```
"65*4+059*$!#.39*0jp2+'Wk,@ ''5&.'\d&o@o&88#+\@ol?!,'.'0.6'!+Ox,++tttt=++%-$#}.6~.F4*`*R

```

Try it in Befunge! Try it in \>\<\>! Try it in Gol\>\<\>! Try it in Fission! Try it in Wumpus! Try it in Cardinal! Try it in Beeswax! Try it in Alice!

Verification!

Lots of 2D languages, all abusing wrapping string literals. The difference in outputs are thus:

\>\<\>, Gol\>\<\> and Befunge-98 all print the code backwards (except for the `"`), with the last three characters in different positions, `R*"`, `O"*` and `"R*` respectively. Beeswax also has the code backwards, but the last three characters are interspersed in the first section of the output. Alice is mostly backwards, except for all the escaped characters (`'`,`\` and `"`) moved to the front instead.

Wumpus is the only actual quine, Fission puts the `"` at the end of the code instead of the beginning, and Cardinal puts the `"` between the `0` and the `5` near the start.

Proof of different permutations

## Explanations:

### Befunge-98:

```
"  Wrapping string literal pushes all other characters + a space to the stack
 65*4+  Push " to the stack
      059*$!#.39*0j   Push 1,27 to the stack
                   p  Pops the top three values of the stack (27,1,34)
                    2+  Adds 2 to the space to make "
                      'Wk,@  Prints the top 88 characters of the stack and terminates

```

### \>\<\> and Gol\>\<\>:

To be honest, I didn't do much here. The only difference between the execution of these two languages is the `@` command, which rotates the top three values of the stack in different ways for each language.

```
"  Wrapping string literal pushes all other characters to the stack
 65*4+  Push 34 (") to the stack
      059*$!#.  Jump to cell 45,0
                                   \@  Rotate the top three values of the stack
                                     ol?!,'.'0.  Output the whole stack, ending in a divide by 0/stack underflow error

```

### Fission:

```
 "............R  Spawn a pointer going right

 "  Switch to printing mode and print every other character
 "  Switch off printing mode
  6  Teleport to other 6
 "........6'!+O   Print the "

```

### Wumpus:

```
"  Bouncing string literal
 65*4+  Push a (")
      059*$!#.   Push 0 and jump to cell 0,45
                                        \  Reflect off mirror
                                       +   Add 0 to top of stack
                                 @o&88#    Print the top 88 characters of the stack

```

### Cardinal:

```
                                 %   Spawn two pointer going left/right (up/down despawn immediately)
                                  -$  Right pointer jumps to cell -1,0
                      x,++tttt=++     Left pointer prints "
"  While right pointer switches to print mode and prints the code

```

### Beeswax:

```
 "................*`*   Spawn pointers going in every direction
                        Every other * also spawns pointers, but they do nothing
                   `    Turn on print mode for two of the pointers going in different directions
                        This prints everything but the `
          #}.6~.F4*     Print a `

```

### Alice:

```
"  Wrapping string literal pushes all other characters to the stack
   Except 's and mirrors
 65*4+  Push " to the stack
      059*$!#.  Does nothing
              39*0j  Jumps to cell 39,0
                         ''5&.    Push ' and duplicate it 5 times
                              '\  Push \
                                d&o@  Print the whole stack

```
> 10 votes

# Answer
## Perl 5, Ruby, JavaScript (Chrome), PHP, Python 2, Python 3, 1206 bytes, score 66/1206 = 38.6865671641791

```
q=1//2;s=+0;s|0;"/.__id__;#";_="""q=1//2;s=+0;s|0;"/.__id__;#";_={0}{1}{0};R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q={0}{2}{0};print(_.format(Q,_,q[0:-12]+R,"%"))""";R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q="""|;#<?ob_end_clean();
eval($_='"$t"?0?[$q=37 .chr+113 .chr+38 .chr,$p=(96 .chr+39 .chr)*4,$n=10 .chr,$s=39 .chr*12,$S=34 .chr*3]:eval("printf=console.log;c=String.fromCharCode;$q=c(96);$p=c(37,113,38,39).repeat(4);$n=c(10);$s=c(39).repeat(12);$S=c(34,34,34)"):[]?[$q=q(!g)^PA,$p=HARHARHARHAR^od2od2od2od2,$n=R^X,$s=bbbbbbbbbbbb^EEEEEEEEEEEE,$S=hhh^JJJ]:[$q=O^h,$p=str_repeat(RHa3^w9GS,4),$n=R^X,$s=str_repeat(b^E,12),$S=HHH^jjj];//#');printf($x='q=1//2;s=+0;s|0;"/.__id__;#";_=%7$sq=1//2;s=+0;s|0;"/.__id__;#";_={0}{1}{0};R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q={0}{2}{0};print(_.format(Q,_,q[0:-12]+R,"%8$s"))%7$s;R=chr((39,34)[1/2>0])*12;Q=chr((39,34)[1/2==0])*3;q=%7$s|;#<?ob_end_clean();%5$seval($_=%3$s%1$s%3$s);printf($x=%3$s%2$s%3$s,$_,$x,$q,$p,$n,$s,$S,"%8$s",![]||([]+[])?$n:"");//#%4$s%6$s%7$s;print(_.format(Q,_,q[0:-12]+R,"%8$s"))%9$s',$_,$x,$q,$p,$n,$s,$S,"%",![]||([]+[])?$n:"");//#`q&%`q&%`q&%`q&%''''''''''''""";print(_.format(Q,_,q[0:-12]+R,"%"))

```

Validate Perl, Ruby, PHP, Python 2 and Python 3 online!

**Note**: running the above program in the Inspector console in Chrome (which appears to support positional arguments to `console.log`) returns the correct program.

### Explanation

This turned out a lot longer than I'd hoped and I made my life a little harder too, so I'm likely to keep tinkering with it. I'd like to add in more languages too, but I need to find something that doesn't mind a `$` sigil...

This is pretty much a standard quine format where the calculation of the quote to use is a little different for each language: in Ruby `%q&` is used, PHP uses `'`, JavaScript (Node.js) makes use of ``` and Perl 5 utilises `q(`...`)`. Because only the quotes change, the rest of the program is still executable and valid syntax in each language. Python 2 and 3 are wrapped around the previous program using `"""` for Python 2 and `'''` for Python 3.

The resultant Perl and Ruby programs aren't standard quines, additional `q`/`%q`s are added each iteration, but the first program returns correctly.

The results are:

* Perl 5:
`eval($_=q&`...`q&);printf($x=q&`...`q&,`...`);//#'%`'%`'%`'%`''''''''''''"""` ...
* Ruby:
`eval($_=%q&`...`%q&);printf($x=%q&`...`%q&,`...`);//#`'`'`'`'''''''''''''"""` ...
* JavaScript (Chrome):
`eval($_=`` ...``);printf($x=``... ``,`...`);//#%q&'%q&'%q&'%q&'''''''''''''"""` ...
* PHP:
`eval($_='`...`');printf($x='`...`',`...`);//#`q&%`q&%`q&%`q&%''''''''''''"""` ...
* Python 2:
...`_="""`...`""";`...`q="""`...`''''''''''''""";print(_.format(Q,_,q[0:-12]+R,"%"))`
* Python 3:
...`_='''`...`''';`...`q='''`...`""""""""""""''';print(_.format(Q,_,q[0:-12]+R,"%"))`

I've re-worked this a lot, I hope I haven't missed anything key here. I still have quite a way to go to be anywhere near Jo King's score...
> 6 votes

# Answer
# Jelly, and , 2<sup>6</sup>/14 = 4.57

```
1Ɗṙ@“1Ɗṙ@ȮṾ”ȮṾ

```

Try it in Jelly!

Try it in M!

`Ɗṙ@ȮṾ1“Ɗṙ@ȮṾ1”` in Jelly

`1Ɗṙ@ȮṾ“1Ɗṙ@ȮṾ”` in M
> 2 votes

# Answer
# Python 2 and Python 3, 2<sup>6</sup>/61 =1.05

```
s='s=%r;print(s%%s[::(1/2>0)*2-1])';print(s%s[::(1/2>0)*2-1])

```

Try it in Python 2!

Try it in Python 3!

Saved 12 bytes thanks to Jo King.

**Python 2 prints**

```
s=')]1-2*)0>2/1(::[s%%s(tnirp;r%=s';print(s%s[::(1/2>0)*2-1])

```

**Python 3 prints**

```
s='s=%r;print(s%%s[::(1/2>0)*2-1])';print(s%s[::(1/2>0)*2-1])

```

This uses the fact that `1/2` is `.5` in Python 3 and `0` in Python 2.
> 2 votes

# Answer
# Bash/GolfScript, 72 bytes, score 2<sup>6</sup>/72 = 8/9 (~0.888...)

```
.~0 ()
{
    declare "-f" @* ".~0" " ()
 "+@n.;
    echo '.~0;'
}
.~0;

```

Contains a single trailing space on the first two lines.

Try it online in Bash.
Try it online in GolfScript.

Simply modification of *@jimmy23013*'s answer for the "*Write a Polyquine*" challenge. The modification that was done was removing the trailing space after the third line, and changing `\n"+@n.;` to `\n "+@n;`.

Bash will print lines 1 and 2 like this:

```
.~0 ()    <- Trailing space
{         <- Trailing space

```

And GolfScript will print lines 1 and 2 like this:

```
.~0 ()   <- No trailing space
 {       <- Both leading and trailing space

```

Here the base program, Bash output, and GolfScript outputs respectively with the new-lines replaced with `\n`:

```
.~0 () \n{ \n    declare "-f" @* ".~0" " ()\n "+@n.;\n    echo '.~0;'\n}\n.~0;
.~0 () \n{ \n    declare "-f" @* ".~0" " ()\n "+@n.;\n    echo '.~0;'\n}\n.~0;
.~0 ()\n { \n    declare "-f" @* ".~0" " ()\n "+@n.;\n    echo '.~0;'\n}\n.~0;

      ^^^ Note the difference here

```
> 1 votes

---
Tags: code-challenge, quine, polyglot
---


title: Render an ASCII maze

text:
# Question
Title: Render an ASCII maze
look! It's an ASCII maze! Soo coolzors, amazeballs and stuff.

```
+-+-----+---+
| |     |   |
| |  ++   | |
| |  ++ +-+ |
|       |   |
+-------+ | |
|         | |
+---------+-+

```

But, but, but... it's a pain to work out which direction all the parts of the maze are going. I just want to draw the layout and the maze make itself sooper kul without loads of time.

What if I could just draw this in...

```
#############
# #     #   #
# #  ##   # #
# #  ## ### #
#       #   #
######### # #
#         # #
#############

```

That would be soo sweet!

---

The rules (Because rules is cools):

* Write code to convert a string into an ascii maze and output the result.
* Any non-whitespace character will be read as a wall.
* Each char of wall will decide which character to be based on it's neighbours (only in North, South, East and West directions).
    + If a char has no non-whitespace neighbours, it will be a plus sign (+).
    + If a char has neighbours in both vertical (North-South) and horizontal (East-West) directions, it will be a plus sign (+).
    + If a char has neighbours only in a vertical (North-South) direction, it will be a pipe symbol (|).
    + If a char has neighbours only in a horizontal (East-West) direction, it will be a minus sign (-).
* The Input can be a single string (with lines separated by newline characters, or an array of strings).
* All input characters will be printable ASCII characters, you don't need to deal with extended charsets.
* Use any old language you please.
* If there is white space before a line, it should be the same amount on each line. Any white space after each line of output is fine.
* Attempt to solve it with the smallest number of bytes.

---

# Test cases:

## 1: Frame

Input:

```
##########
#        #
#        #
#        #
##########

```

Output:

```
+--------+
|        |
|        |
|        |
+--------+

```

## 2: Classic maze

Input:

```
#################
        #       #
# ##### # ##### #
#   # # #     # #
# # # # ##### # #
#   # #       # #
### # ####### # #
#   # #    #  # #
# ### # ## # ##
#     # ##    #
#################

```

Output:

```
--------+-------+
        |       |
| --+-+ | ----+ |
|   | | |     | |
| + | | +---- | |
|   | |       | |
+-- | +----+- | |
|   | |    |  | |
| --+ | ++ | -+
|     | ++    |
+-----+-++----+--

```

## 3: Green eggs, man.

Input:

```
I do not like green eggs and ham.
I do not like them, sam I am.
Would you like them here or there?
I would not like them anywhere!

```

Output:

```
| ++ +++ ++++ +++++ +++- -++ ----
| ++ +++ ++++ +++++ +++ + +++
+-+++ +++ ++++ ++++ ++++ ++ +++---
| +++-+ +++ ++++ ++-+ +++++++++

```

## 4: Icicles

Input:

```
Word Icicle!
Word Icicle
Word  cicle
 ord  cicle
 ord   icle
 ord   i le
 or    i le
 or    i l
 or      l
 or
  r

```

Output:

```
++++ ++++++-
++++ ++++++
++++  +++++
 +++  +++++
 +++   ++++
 +++   | ++
 ++    | ++
 ++    | |
 ++      |
 ++
  |

```

# Answer
> 11 votes
# APL (Dyalog Unicode), ~~57~~ 35 bytesSBCS

–22 thanks to a novel solution by ngn.

Anonymous tacit function taking a character matrix as argument.

```
{⊃'+-|+'↓⍨2⊥5 4 2⊃¨⊂⍱∘⌽⍨' '≠,⍵}⌺3 3

```

Try it online!

`{``}⌺3 3` on each 3-by-3 neighbourhood, apply the following function:

`,⍵` ravel (flatten)

`' '≠` Boolean where non-space

`⍱∘⌽⍨` that NOR it's reverse (incl. neither top NOR bottom, neither left NOR right)

`5 4 2⊃¨⊂` pick 5th, 4th, and 2nd element from that entire list
i.e. empty self, no vertical, no horizontal

`2⊥` evaluate in base-2 (binary)
i.e. ≥4:empty self; 3:no neighbours; 2:no horizontal neighbours; 1:no vertical; 0: has both

`'+-|+'↓⍨` drop that many elements from this string
i.e. empty self:; alone:`+`; vertical neighbour(s) only:`|+`; horizontal:`-|+`; both:`+-|+`

pick the first element (pad with space if non are available)
i.e. empty self:; alone:`+`; vertical neighbour(s) only:`|`; horizontal:`-`; both:`+`

---

# Old solution

Anonymous tacit function taking a character matrix as argument.

```
{' +-|+'⊃⍨1⍳⍨(' '=5⊃,⍵),(∧/,⊢)∨/2 2⍴1⌽' '≠(9⍴0 1)/,⍵}⌺3 3

```

Try it online!

`{``}⌺3 3` on each 3-by-3 neighbourhood, apply the following function:

`,⍵` ravel (flatten)

`(``)/` filter using the following mask:

`9⍴0 1` cyclically reshape `[0,1]` to length 9 (selects N, W, E, S)

`' '≠` Boolean where non-space

`1⌽` rotate one step left; `[W,E,S,N]`

`2 2⍴` reshape to 2-by-2 matrix; `[[W,E],[S,N]]`

`∨/` row-wise OR reduction: `[horizontal,vertical]`

`(``)` apply the following tacit function:

the identity; `[horizontal,vertical]`

`∧/,` preceded by its AND reduction; `[both,horizontal,vertical]`

`(``),` prepend the following:

`,⍵` ravel (flatten) the neighbourhood

`5⊃` pick the 5th element (itself)

`' '=` Boolean if space (i.e. empty)

Now we have `[empty,both,horizontal,vertical]`

`1⍳⍨` index of leftmost 1 (gives 5 if no neighbours at all)

`' +-|+'⊃⍨` use that to pick symbol

# Answer
> 6 votes
# Python 2, ~~181~~ 168 bytes

thanks to Leaky Nun for -13 bytes

```
m=input()
f=lambda x,y:(['']+m+[''])[y+1][x:x+1]>' '
print[[(c<'!')*' 'or'+-|+'[f(x+1,y)|f(x-1,y)|2*f(x,y+1)|2*f(x,y-1)]for x,c in enumerate(r)]for y,r in enumerate(m)]

```

Try it online!

# Answer
> 6 votes
# JavaScript (ES6), 110 bytes

I/O format: array of strings.

```
a=>a.map((s,y)=>s.replace(/\S/g,(_,x)=>'+|-+'[[-1,p=0,1,2].map(c=>p|=(a[y+c%2]||0)[x+~-c%2]>' '?c&1||2:0)|p]))

```

Try it online!

Or **108 bytes** by using a matrix of characters instead.

# Answer
> 5 votes
# MATLAB, 113 110 101 bytes

```
function F(A)
B=A>32
c=[1 1 1]
f=@(c)conv2(B,c,'s')>1
h=f(c)
v=f(c')
char((13*h+92*v-94*(h&v)).*B+32)

```

Converts input to logical, applies convolution in horizontal and vertical and combines the outputs to make the corresponding chars.

3 bytes saved by @Adriaan for telling me that you can clog the output in PPCG :P

9 bytes saved thanks to numerous @flawr comments!

# Answer
> 3 votes
# , ~~49~~ 47 bytes

Thanks to *FrownyFrog* for -2 bytes!

```
' +|-+'{~~:&' '*1+h&.|:+2*h=:g&.|.*g=:' '=#{.}.

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 92 bytes

```
\S
0
(?<=(.)*)0(?=(?>.*\n(?<-1>.)*)0)|0(?=(.)*)(?<=0(?>(?<-2>.)*\n.*))
1
T`d`+|`\b.\b
T`d`-+

```

Try it online! Requires rectangular input. Link includes test cases. Explanation:

```
\S
0

```

Change all non-spaces to `0`s.

```
(?<=(.)*)0(?=(?>.*\n(?<-1>.)*)0)|0(?=(.)*)(?<=0(?>(?<-2>.)*\n.*))
1

```

Look for all `0`s with another `0` immediately above or below in the same column and change them to a 1. The `1`s are now the places with vertical neighbours, while the `0`s have no vertical neighbours.

```
T`d`+|`\b.\b

```

Look for all digits with no horizontal neighbours. The `0`s have no vertical neighbours either, so they become `+`s, while the `1`s have vertical neighbours, so they become `|`s.

```
T`d`-+

```

The remaining digits have horizontal neighbours. The `1`s also have vertical neighbours, so they become `+`s, while the `0`s only have horizontal neighbours, so they become `-`s.

# Answer
> 1 votes
# Python 3, 336 bytes

```
def g(s):
 h,j,s=' +|-+','',s.splitlines()
 s+=['']
 for n in range(len(s)):
  s[n]+=' '
  for i in range(len(s[n])-1):
   l,r,k=s[n][i-1],s[n][i+1],0
   try:u=s[n-1][i]
   except:u=' '
   try:d=s[n+1][i]
   except:d=' '
   if not s[n][i]==' ':
    k+=1
    if not u==d==' ':k+=1
    if not l==r==' ':k+=2
   j+=h[k]
  j+='\n'
 print(j)

```

Try it online!

I had to use a lot of code to deal with edge case errors.

# Answer
> 1 votes
# C (gcc), 143 bytes

```
char**y,*z,h,v;f(char**x){for(y=x;*y;++y)for(z=*y;*z;++z)if(*z-32){h=z[1]-32|z[-1]-32;v=y[1][z-*y]-32|y[-1][z-*y]-32;*z=h?v?43:45:(v?'|':43);}}

```

Try it online!

The function f modifies an array of strings in-place. The area around the array must be padded with spaces (a bit constrained). Even though this doesn't exactly meet the requirements most solutions are using, it does conform to the rules if we say that we represent a newline with two spaces (and take array of strings ending in newlines).

### Ungolfed

```
f(char**x){
    char **y;
    for (y = x; *y; ++y) {
        char *z;
        for (z = *y; *z; ++z) {
            if (*z != ' ') {
                if (z[1] != ' ' || z[-1] != ' ') {
                    // Horizontal exists
                    if (y[1][z-*y] != ' ' || y[-1][z-*y] != ' ')
                        // Vertical exists
                        *z = '+';
                    else
                        *z = '-';
                } else {
                    // Horizontal doesn't exist
                    if (y[1][z-*y] != ' ' || y[-1][z-*y] != ' ')
                        // Vertical exists
                        *z = '|';
                    else
                        *z = '+';
                }
            }
        }
    }
}

```

This was a fun challenge of pointer arithmetic. Using C-style pointer iteration it is easy to get the horizontal neighbors, but the vertical ones were tougher. Luckily the y pointer is still around (which points to the initial value of z) so I can deduce my index from it and use that to access the same element on a different row. It felt very wrong writing `y[-1][z-*y]` as it flies in the face of any reasonable style!

---
Tags: code-golf, ascii-art
---


title: ASCII Mountain Range

text:
# Question
Title: ASCII Mountain Range
This is a CC-BY-SA challenge from the CCSC Mid-South Programming Contest 2018.
**Author(s):** Brent Yorgey
**Source:** Consortium for Computing Sciences in Colleges Mid-South Programming contest 2018
https://ccsc18.kattis.com/problems/ccsc18.mountainrange

---

> Good news: you have been hired to do all the special effects for a film! One of the scenes will take place outside, on a windswept plain with a towering mountain range in the background. Your job is to turn a description of the mountain range into a rendered image.
>
> The bad news: the film’s producers have an extremely small budget, and so they can’t afford luxuries like rendered 3D graphics made up of pixels. Hence, you will be making your image out of ASCII characters.

Write a function or full program to produce mountain range ASCII art according to the spec below. This is ; tie breaker is earlier submission.

## Input

You will receive a list of 5-tuples in any standard input format for PPCG and/or your language. Each 5-tuple is the values (x, h, z, t, s) representing one mountain of the range you will draw.

* x is the x-coordinate of the mountain's peak, with 1≤x≤199.
* h is the height of the mountain, with 1≤h≤100.
* z indicates the relative distance of the mountain from the viewer, with 1≤z≤m. The smaller the value of z, the closer the mountain is to the viewer. Closer mountains hide ones that are farther away.
* t is the height of the treeline. The side of the mountain up to the treeline should be filled with trees, represented by the ASCII character `Y`.
* s is the height of the snowline. The side of the mountain above the snowline should be filled with snow, represented by the ASCII character `*`.

The base of each mountain will not extend beyond 0 or 200 horizontally; you may assume that 0≤x−h and x+h≤200. The height of each mountain is no more than 100, so all mountains will fit within a 100x200 grid. The snow and trees will not overlap or exceed the height of the mountain; you may assume that 0≤t≤s≤h. All numbers are non-negative, and all z-values will be unique.

## Output

The output should consist of an ASCII drawing of the specified mountain range. Each mountain is triangular in shape with its sides drawn using `/` and `\` characters. For example, here is a mountain of height 4:

```
   /\
  /  \
 /    \
/      \

```

This mountain has x-coordinate 4, since the horizontal distance from the left margin to its peak is 4 units.

Trees and snow should fill the interior of the mountain but not obscure the sides of the mountain. For example, here is a mountain with height 6, treeline height 2, and snowline height 3:

```
     /\
    /**\
   /****\
  /      \
 /YYYYYYYY\
/YYYYYYYYYY\

```

That is, the trees extend from the base of the mountain up to a height of 2 units, and the snow starts at a height of 3 units and extends to the top of the mountain.

Mountains with a smaller z-coordinate may hide all or part of a mountain with a larger z-coordinate; see the third sample input/output below.

Leading whitespace is significant, and should be as specified by the x-position and width of the drawn mountains. Leading/trailing newlines are allowed, and any amount of spaces after each line.

## Examples

(8, 5, 1, 2, 3)

```
       /\
      /**\
     /    \
    /YYYYYY\
   /YYYYYYYY\

```

(2, 2, 1, 0, 1)

```
 /\
/  \

```

(8, 5, 2, 2, 3), (2, 2, 1, 0, 1), (9, 8, 3, 1, 4), (17, 4, 4, 4, 4)

```
        /\
       /**\
      /****\
     /*/\***\
    / /**\   \  /\
   / /    \   \/YY\
 /\ /YYYYYY\   \YYY\
/  \YYYYYYYY\YYY\YYY\

```

If you find other interesting examples, please share in your answers!

# Answer
# Python 2, ~~194~~ ~~191~~ 186 bytes

```
g=map(list,[' '*200]*100)
for x,h,z,t,s in sorted(input(),key=lambda m:-m[2]):
 for i in range(h):g[-h+i][x+~i:x-~i]=['/']+[' *Y'[(i<h-s)-(i>=h-t)]]*2*i+['\\']
for l in g:print''.join(l)

```

Try it online!

Prints the whole 100x200 grid.
> 4 votes

# Answer
# Charcoal, 79 bytes

```
  ＡθＷθ«≔⊟Φθ⁼§κ²⌈Ｅθ§μ²ι≔Φθ¬⁼κιθ≔§ι¹ηＪ§ι⁰±η≔⟦§ι⁴⁻η§ι³η⟧ζＦY *«≔⊟ζεＧ↘ε←⊗ε↗εκ→»Ｐ↘η←↙η

```

Try it online! Link is to verbose version of code. Note: Leading space used to force the required indentation. Explanation:

```
ＡθＷθ«

```

Loop while the input array is not empty.

```
≔⊟Φθ⁼§κ²⌈Ｅθ§μ²ι

```

Find the most distant mountain in the array.

```
≔Φθ¬⁼κιθ

```

Remove it from the array.

```
≔§ι¹η

```

Get the height of the mountain.

```
Ｊ§ι⁰±η

```

Jump to the top of the mountain.

```
≔⟦§ι⁴⁻η§ι³η⟧ζ

```

Get the snowline, treeline and height.

```
ＦY *«

```

Loop over the trees, bare mountain and snow.

```
≔⊟ζεＧ↘ε←⊗ε↗εκ→»

```

Draw a trapezium of the desired height.

```
Ｐ↘η←↙η

```

Draw the sides of the mountain.
> 2 votes

# Answer
# Ruby, 133 bytes

```
->a{r=[];a.sort_by{|x|-x[2]}.map{|x,h,z,t,s|h.times{|i|(r[i]||=?\s*200)[x-j=h-i,j*2]=?/+" Y*"[i<t ?1:i<s ?0:2]*~-j*2+?\\}};r.reverse}

```

Try it online!

Anonymous lambda. Takes input as array of parameter arrays for mountains, returns array of strings.

## Walkthrough

```
->a{                 #Input array is a
 r=[];               #Initialize the output array
 a.sort_by{|x|-x[2]} #Sort by decreasing distance
 .map{|x,h,z,t,s|    #Loop through the mountains
  h.times{|i|        #For each mountain fill h lines starting from the ground
   (r[i]||=?\s*200)  #If we haven't yet been so high, initialize with spaces
   [x-j=h-i,j*2]=    #Take a slice from x-(h-i) for double length of h-i
    ?/+" Y*"[i<t ?1:i<s ?0:2]*~-j*2+?\\ #Draw the sides of the mountain (/\),
  } #with (h-i-1)*2 of the appropriately selected filler symbols in the middle
 };r.reverse         #Reverse to the top->bottom order suitable for printing
}

```
> 2 votes

# Answer
# C (clang), ~~284~~ ~~261~~ ~~257~~ 252 bytes

```
a,b,*z,i,j,k,o;c(*a,*b){return b[2]-a[2];}f(*m,n){qsort(m,n,5*sizeof *m,c);for(i=101;--i>0;puts(""))for(j=0;++j<200;putchar(o))for(o=32,k=0;k<n;z=&m[5*k++],a=z[0]-z[1]+i,b=z[0]-~z[1]-i,o=z[1]/i&&j/a&&b/j?"/\\*Y "[j==a?0:j==b?1:i>z[4]?2:z[3]/i?3:4]:o);}

```

Try it online!

# Credits:

**-3** bytes Thanks Kevin Cruijssen

`f()` takes these params:

`m`: array of integers with all mountains' parameters
`n`: number of mountains

`m` should be a flat array of specifying `x, h, z, t` and `s` for mountains with each mountain's parameters appended to this array.

`f()` prints full 100x200 grid of ASCII scenery render.

# Ungolfed:

```
a,b,*z,i,j,k,o;
c(*a,*b){return b[2]-a[2];}             //comaprison function for sort by z-order
f(*m,n){
 qsort(m,n,5*sizeof(*m),c);             //sort mountains by z-order
 for(i=100;i>0;i--,puts("")) {          //for each row
  for(j=1;j<200;j++){                   // for each pixel in this row
   o=' ';                               //initialize pixel to background pixel value
   for(k=0;k<n;k++) {                   // for each mountain, in z-order distant to close
    z=&m[5*k];                          //start pointer for mountain's params
    a=z[0]-z[1]+i;                      //min x limit of mountain on this line
    b=1+z[0]+z[1]-i;                    //max x limit of mountain on this line
    o=z[1]/i && j/a && b/j ? "/\\*Y "[j==a?0:j==b?1:i>z[4]?2:z[3]/i?3:4]:o;
                                        //calculate pixel value ovrwriting previous mountain if necessary
   }
   putchar(o);                  //print pixel value
  }
 }
}

```
> 2 votes

# Answer
# JavaScript (Node.js), 265 243 229 210 204 203 bytes

```
a=>a.sort((x,y)=>y[2]-x[2]).map(([x,h,,t,s])=>{for(y=h;y--;)for(i=h+x-y;i--;)(d=R[y]=R[y]||[])[i]=i<x-h+y?d[i]||" ":"Y *\\/"[i>x-h+y?i<h+~y+x?y<t?0:y<s?1:2:3:4]},R=[])&&R.map(x=>s=x.join``+`
`+s,s="")&&s

```

Try it online!
> 1 votes

---
Tags: code-golf, ascii-art
---


title: Ice Golf Challenge

text:
# Question
Title: Ice Golf Challenge
The goal of this challenge is to write a program or function that returns the least amount of strikes needed to complete a given course.

### Input

* The layout of the course can be passed in any suitable way and format you prefer. (read from the console, passed as an input parameter, read from a file or any other, multiline-string, string array, two-dimensional character/byte array).
* The start position of the ball and the hole can be passed as input too, it doesn't have to be parsed from the input. In the test-cases they are included in the course to make sure there is no confusion about the actual position.
* You can remap the input characters to something else, as long as they are still recognisable as distinct characters (e.g. printable ASCII characters).

### Output

* The program must return the lowest possible score (least amount of strikes needed to reach the hole) for any course passed as input in a sensible format (string, integer, float or a haiku describing the result)
* If the course is impossible to beat, return `-1` (or any other **falsy** value of your choice that wouldn't be returned for a beatable course).

### Example:

In this example positions are notated 0-based, X/Y, left-to-right, top-down - but you can use any format you like since the result is completely format-independent anyways.

Input:

```
###########
#     ....#
#      ...#
#  ~    . #
# ~~~   . #
# ~~~~    #
# ~~~~    #
# ~~~~  o #
# ~~~~    #
#@~~~~    #
###########

Ball (Start-Position): 1/9
Hole (End-Position):   8/7

```

Output:

```
8

```

## Rules and fields

The course can consist of the following fields:

* `'@'` **Ball** \- The start of the course
* `'o'` **Hole** \- The goal of the course
* `'#'` **Wall** \- Ball will stop when it hits a wall
* `'~'` **Water** \- Must be avoided
* `'.'` **Sand** \- Ball will stop on sand immediately
* `' '` **Ice** \- Ball will continue to slide until it hits something

The basic rules and restrictions of the game:

* The ball can't move diagonally, only left, right, up and down.
* The ball will not stop in front of water, only in front of walls, on sand and in the hole.
    + Shots into the water are invalid/impossible
    + The ball will stay in the hole, not skip over it like it would on ice
* The course is always rectangular.
* The course is always bordered by water or walls (no boundary checks required).
* There is always exactly one ball and one hole.
* Not all courses are possible to beat.
* There might be multiple paths that result in the same (lowest) score.

## Loopholes and Winning Condition

* Standard loopholes are forbidden
* Programs must terminate
* You can't make up additional rules (hitting the ball so hard it skips over water, rebounds off a wall, jumps over sand fields, curves around corners, etc.)
* This is , so the solution with the least amount of characters wins.
* Solutions must be able to handle all provided test-cases, if this is impossible due to restrictions of the used language please specify that in your answer.

## Test cases

Course #1 (2 strikes)

```
####
# @#
#o~#
####

```

Course #2 (not possible)

```
#####
#@  #
# o #
#   #
#####

```

Course #3 (3 strikes)

```
~~~
~@~
~.~
~ ~
~ ~
~ ~
~ ~
~.~
~o~
~~~

```

Course #4 (2 strikes)

```
#########
#~~~~~~~#
#~~~@~~~#
##  .  ##
#~ ~ ~ ~#
#~. o .~#
#~~~ ~~~#
#~~~~~~~#
#########

```

Course #5 (not possible)

```
~~~~~~~
~...  ~
~.@.~.~
~...  ~
~ ~ ~.~
~ . .o~
~~~~~~~

```

### More Test cases:

https://pastebin.com/Azdyym00

# Answer
# JavaScript (ES6), 174 bytes

Takes input in ~~curling~~ currying syntax `([x, y])(a)`, where **x** and **y** are the 0-indexed coordinates of the starting position and **a\[ \]** is a matrix of integers, with `0` = ice, `1` = wall, `2` = sand, `3` = hole and `4` = water

Returns `0` if there's no solution.

```
p=>a=>(r=F=([x,y],n,R=a[y],c=R[x])=>R[c&(R[x]=4)|n>=r||[-1,0,1,2].map(d=>(g=_=>(k=a[v=Y,Y+=d%2][h=X,X+=~-d%2])||g())(X=x,Y=y)>3?0:k>2?r=-~n:F(k>1?[X,Y]:[h,v],-~n)),x]=c)(p)|r

```

Try it online!

### Commented

```
p => a => (                       // given the starting position p[] and the matrix a[]
  r =                             // r = best result, initialized to a non-numeric value
  F = (                           // F = recursive function taking:
    [x, y],                       //   (x, y) = current position
    n,                            //   n = number of shots, initially undefined
    R = a[y],                     //   R = current row in the matrix
    c = R[x]                      //   c = value of the current cell
  ) =>                            //
    R[                            // this will update R[x] once the inner code is executed
      c & (R[x] = 4) |            //   set the current cell to 4 (water); abort if it was
      n >= r ||                   //   already set to 4 or n is greater than or equal to r
      [-1, 0, 1, 2].map(d =>      //   otherwise, for each direction d:
        (g = _ => (               //     g = recursive function performing the shot by
          k = a[                  //         saving a backup (h, v) of (X, Y)
            v = Y, Y += d % 2][   //         and updating (X, Y) until we reach a cell
            h = X, X += ~-d % 2]) //         whose value k is not 0 (ice)
          || g()                  //
        )(X = x, Y = y)           //     initial call to g() with (X, Y) = (x, y)
        > 3 ?                     //     if k = 4 (water -> fail):
          0                       //       abort immediately
        :                         //     else:
          k > 2 ?                 //       if k = 3 (hole -> success):
            r = -~n               //         set r to n + 1
          :                       //       else:
            F(                    //         do a recursive call to F():
              k > 1 ?             //           if k = 2 (sand):
                [X, Y]            //             start the next shots from the last cell
              :                   //           else (wall):
                [h, v],           //             start from the last ice cell
              -~n                 //           increment the number of shots
            )                     //         end of recursive call
      ), x                        //   end of map(); x = actual index used to access R[]
    ] = c                         // restore the value of the current cell to c
)(p) | r                          // initial call to F() at the starting position; return r

```
> 6 votes

# Answer
# Python 3, 273 bytes

```
def p(g,c,d,k=0):
	while 1>k:c+=d;k=g.get(c,9)
	return-(k==2)or c-d*(k==3)
def f(g):
	c={q for q in g if g.get(q,9)>4};I=0;s=[c]
	while all(g.get(q,9)-4for q in c):
		c={k for k in{p(g,k,1j**q)for k in c for q in range(4)}if-~k}
		if c in s:return-1
		s+=[c];I+=1
	return I

```

Try it online!

-41 bytes thanks to ovs
-1 byte thanks to Jonathan Frech
> 5 votes

# Answer
# C#, ~~461~~ 418 bytes

This is just a non-competitive reference implementation to (hopefully) revive this challenge:

**Golfed by Kevin Cruijssen**

```
int P(string[]C){int w=C[0].Length,i=0,l=c.Length;var c=string.Join("",C);var h=new int[l];for(var n=new List<int>();i<l;n.Add(i++))h[i]=c[i]!='@'?int.MaxValue:0;for(i=1;;i++){var t=n;n=new List<int>();foreach(int x in t){foreach(int d in new[]{-1,1,-w,w}){for(int j=x+d;c[j]==' ';j+=d);if(c[j]=='#'&h[j-d]>s){h[j-d]=s;n.Add(j-d);}if(c[j]=='.'&h[j]>s){h[j]=s;n.Add(j);}if(c[j]=='o')return s;}}if(n.Count<1)return -1;}}

```

**Ungolfed**

```
int IceGolf(string[] course)
{
    // Width of the course
    int w = course[0].Length;

    // Course as single string
    var c = string.Join("", course);

    // Array of hits per field
    var hits = new int[c.Length];

    // Fields to continue from
    var nextRound = new List<int>();

    // Initialize hits
    for (int i = 0; i < hits.Length; i++)
    {
        if (c[i] != '@')
            // All fields start with a high value
            hits[i] = Int32.MaxValue;
        else
        {
            // Puck field starts with 0
            hits[i] = 0;
            nextRound.Add(i);
        }
    }

    for (int s = 1; ; s++)
    {
        // clear the fields that will be used in the next iteration
        var thisRound = nextRound;
        nextRound = new List<int>();

        foreach (int i in thisRound)
        {
            // test all 4 directions
            foreach (int d in new[] { -1, 1, -w, w })
            {
                int j = i+d;

                // ICE - slide along
                while (c[j] == ' ')
                    j += d;

                // WALL - stop on previous field
                if (c[j] == '#' && hits[j-d] > s)
                {
                    hits[j-d] = s;
                    nextRound.Add(j-d);
                }

                // SAND - stop
                if (c[j] == '.' && hits[j] > s)
                {
                    hits[j] = s;
                    nextRound.Add(j);
                }

                // HOLE return strikes
                if (c[j] == 'o')
                    return s;
            }
        }

        // No possible path found
        if (nextRound.Count == 0)
            return -1;
    }
}

```

Try it online
> 2 votes

---
Tags: code-golf, game, grid, path-finding, maze
---


title: Recovering Range Parameters

text:
# Question
Title: Recovering Range Parameters
## Description

You are given the results of a range function where every element has been rounded down to the nearest whole number. Your goal is to recover the original list.

For example, the following function (in Python3) will produce an input for your program:

```
from numpy import arange, floor
def floored_range(A, B, C):
    return list(floor(arange(A, B, C)))

```

The output of your program should be a valid guess of the original data. Here, valid guess means that it must exactly match the input when floored and it must be a possible output of a range function (ie, when graphed it must form a perfectly straight line).

## Examples

```
Input: [1,2,3,4]
Output: [1,2,3,4]

Input: [1,2,3,4]
Output: [1.9,2.7,3.5,4.3]

Input: [1,2,3,4,5,5]
Output: [1.9,2.7,3.5,4.3,5.1,5.9]

Input: [1,1,2,2,3,3,4,4]
Output: [1,1.5,2,2.5,3,3.5,4,4.5]

Input: [1,1,2,3,3,4]
Output: [1,1.7,2.4,3.1,3.8,4.5]

Input: [56, 54, 52, 50, 48, 45, 43, 41, 39, 37, 35, 32, 30, 28, 26, 24, 22, 19, 17, 15, 13, 11]
Output: [56.7  , 54.541, 52.382, 50.223, 48.064, 45.905, 43.746, 41.587,
   39.428, 37.269, 35.11 , 32.951, 30.792, 28.633, 26.474, 24.315,
   22.156, 19.997, 17.838, 15.679, 13.52 , 11.361]

```

# Answer
> 3 votes
# Octave, 82 bytes

```
function y=f(x)
while any(floor(y=linspace(x(1)+rand,x(end)+rand,numel(x)))-x),end

```

Running time is non-deterministic, but the code ends in finite time with probability 1.

**Try it online!**

### Explanation

The code defines a `function` of `x` that outputs `y`. The function consists of a `while` loop.

In each iteration, the right amount (`numel(x)`) of linearly spaced values are generated (`linspace`), starting at `x(1)+rand` and ending at `x(end)+rand`. These two calls to the `rand` function give random offsets between `0` and `1`, which are applied to the initial and final values of `x`.

The loop is repeated for as long as `any` of the `floor`ed results differs (`-`) from the corresponding entry in `x`.

# Answer
> 3 votes
# Python 3, 189 bytes

```
def f(l):
 R=range(len(l));e=1-1e-9
 for j in R:
  for I in range(j*4):
   i=I//4;L=[((l[i]+I//2%2*e)*(x-j)-(l[j]+I%2*e)*(x-i))/(i-j)for x in R]
   if[x//1 for x in L]==l:return L
 return l

```

Try it online!

Cubic time.

Has some numerical issues.

# Answer
> 3 votes
# , 86 bytes

```
function(n){while(any(n-(x=seq(n[1]+runif(1),tail(n,1)+runif(1),l=sum(n|1)))%/%1))0;x}

```

Try it online!

R port of Luis Mendo's answer; it does issue a number of warnings because of `any` coercing to `logical` but these can be ignored.

# Answer
> 1 votes
# Python 3, 168 bytes

```
def f(l):r=range(len(l));g=lambda n:[(l[b]+n-l[a])/(b-a)for a in r for b in r if b>a]or[0];s=(max(g(-1))+min(g(1)))/2;m=min(a*s-l[a]for a in r);return[a*s-m for a in r]

```

Try it online! Explanation: `g` calculates the limiting values for `C` that lie just outside the range for `A` and `B` to exist. The average is then taken to give a usable value for `C`, and then the lowest possible range is then generated.

# Answer
> 0 votes
# JavaScript (Node.js), 94 bytes, assuming input length \> 1

```
f=x=>(t=x.map(_=>a+=b,b=x[1]+(c=Math.random)(a=x[0]+c())-a,a-=b)).map(Math.floor)+''==x?t:f(x)

```

Try it online!

97 bytes

```
f=x=>(t=x.map(_=>a+=b,b=x[1]+(c=Math.random)(a=x[0]+c())-a||0,a-=b)).map(Math.floor)+''==x?t:f(x)

```

# Answer
> 0 votes
# Jelly, 31 bytes

```
ṾṚ”.;V×LḶ$}+©1ị$}IEȧḞ⁼¥ʋ
0ç1#®ḷ

```

Try it online!

**Warning**: Floating-point inaccuracies.

# Answer
> 0 votes
# Python 2, 212 bytes

```
def f(l):
 C=[(0,1.,0,1.)]
 for a,A,b,B in C:
  x,y=(A+a)/2,(B+b)/2;r=[l[0]+x+i*(l[-1]+y-l[0]-x)/(~-len(l)or 1)for i in range(len(l))];C+=[(x,A,y,B),(a,x,y,B),(x,A,b,y),(a,x,b,y)]
  if[n//1for n in r]==l:return r

```

Try it online!

---
Tags: code-golf
---


title: string char rotation

text:
# Question
Title: string char rotation
# Challenge :

Given a string rotate every char by its index. `e.g --> 'Hello' should be 'Hfnos'`.

---

# Input :

Input is given as string `s` length of string is `2 < s ≤ 100`. Input will either be alphabet , number or one of the following whitespace , ! , @ , # , $ , % , ^ , & , * , ( , )

---

# Output :

Output will be a string with all characters rotated by their index. Example given above.

---

# Examples :

```
Input                     Output

Hello World!              Hfnos%]vzun,
Who                       Wiq
PPCG                      PQEJ

```

---

# Note :

This is so shortest code in bytes in each language wins.

# Answer
## Haskell, ~~37~~ ~~36~~ 28 bytes

```
zipWith($)(iterate(succ.)id)

```

Try it online!

How it works

```
iterate(succ.)id     -- starting with the identity function 'id' this
                     -- creates an infinite list of function where the next
                     -- element has one more 'succ' (the successor function)
                     -- composed to it than the current element:
                     -- -> [id, succ.id, succ.succ.id, succ.succ.succ.id, ...]
zipWith ($) (   )    -- combine the above list and the input string
                     -- elementwise with the function application operator '$'.
                     -- 1st char c0:            id $ c0 =            c0
                     -- 2nd char c1:       succ.id $ c1 =       succ c1
                     -- 3rd char c2:  succ.succ.id $ c2 = succ (succ c2)
                     -- etc.

```

Edit: -8 bytes thanks to @Angs
> 1 votes

# Answer
# Python 2, 47 bytes

```
lambda I:[chr(ord(c)+i)for i,c in enumerate(I)]

```

Try it online!
> -1 votes

# Answer
# Japt, 2 bytes

```
c+

```

Try it out here
> -2 votes

---
Tags: code-golf, string
---


title: The bug stops here

text:
# Question
Title: The bug stops here
Let's discover1 some bugs...

Write the shortest complete program possible that, when run on a **stable** release of an implementation of a language, demonstrates a bug in that implementation. Please specify which release and platform was used. This is code golf, so the shortest code (in bytes) wins.

* An implementation bug is any behavior that contradicts the language's official standard or specification.
* This does not include bugs in the language's standard library.

This is , so the shortest valid submission (measured in **bytes**) wins.

1 OK, you don't actually have to find the bug. But if you do, don't forget to file a bug report! :)

# Answer
> 5 votes
# Golfscript, 4

```
2-1?

```

This produces output of `1/2` in the interpreter downloaded from golfscript.com and `0.5`on web golfscript. There aren't supposed to be floats in golfscript, but the latest compiler has this on line 82: `Gint.new(@val**b.val)` and it seems to miss a cast to int.

# Answer
> 3 votes
# Taxi, 256 bytes

```
1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Go to Go More:n 2 l.

```

Try it online!

I'm not 100% sure this counts but, based on the map of Townsburg, `Go More` is the 2nd left when heading north from `Equal's Corner`. However, the little dead-end road that is the 1st left (the one that `Starchild Numerology` is on) doesn't have any nodes on it. Thus, as far as the official interpreter is concerned, it's not a road. Thus, `Go More` is actually the *first* left. If you run the above program, you'll get:

```
error: cannot drive in that direction

```

# Answer
> 2 votes
# Haskell (GHC 8.0.2 on TIO), ~~10~~ 9 bytes

-1 byte thanks to @Angs

```
f::()
f=w

```

Try it online!

I have no idea what's happening here. A constant with a type signature defined to be a nonexistent identifier causes an ICE ("impossible happened") on TIO Haskell.

# Answer
> 1 votes
# Bash, 11 bytes

```
$ bash --version
GNU bash, version 4.2.47(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$
$ $[2**63%-1]

Warning: Program '/bin/bash' crashed.

```

# Answer
> 1 votes
# Bash, 7 bytes

```
$ xxd bug.sh
0000000: 2431 3c3c 5f0a 01                        $1<<_..
$ bash bug.sh xxd 2>&-
0000000: 0a                                       .
$ dash bug.sh xxd 2>&-
0000000: 01                                       .

```

# Answer
> 1 votes
# SmileBASIC, 4 bytes

```
?1;?

```

This should be equivalent to:

```
PRINT 1;
PRINT

```

Printing the number `1` without a trailing linebreak, then moving to the next line.

However, it throws the error `Type mismatch(PRINT:3)` after printing `1`.

The bug is that PRINT only has 2 arguments, while the error refers to a third argument which doesn't exist.

# Answer
> 1 votes
# PHP 5.5, 31 bytes

```
(new GlobIterator("*"))->key();

```

When it is executed in an empty directory, it throws:

> Fatal error: Uncaught exception 'LogicException' with message 'The parent constructor was not called: the object is in an invalid state ' in Command line code on line 1

It shouldn't throw any exception. It doesn't throw any exception if the glob pattern (`*`) matches at least one file in the directory.

It is also present in PHP 5.3 and 5.4. PHP 5.3 cannot parse the code above, it requires the object created by `new` to be stored in a variable before running any of its methods (35 chars after stripping the unneeded white space characters):

```
$x = new GlobIterator("*");
$x->key();

```

It is bug #55701 and it has been fixed in July 2016 for PHP 5.6 and 7.0. It was also present in these versions until it was fixed. The versions released after the fix (7.1 and 7.2) don't have this bug.

It was not fixed for PHP 5.5 and older versions because they were already beyond their support phase at that time.

# Answer
> 1 votes
# Java 5 or 6, 12+ bytes

```
enum M{M;{/* Code here */}}

```

In Java versions 1 through 7, all1 Java programs should have an endpoint class containing a main-method:

```
class M{public static void main(String[]a){/* Code here */}}

```

And in Java 8 through 10 you should have this as well, or optionally an interface instead:

```
interface M{static void main(String[]a){/* Code here */}}

```

In Java versions prior to Java 7, it was due to a bug possible to use a static block instead like this: `class M{static{/* Code here */}}`, to run code without a main method. It will still give the following error to STDERR, but only after it has executed the code inside the static block:

> M
> java.lang.NoSuchMethodError: main
> Exception in thread "main"

In Java 5 and 6 this could also be done without static block in an `enum`, as displayed at the top of this answer, which is also mentioned on the *Tips for Golfing in Java* page by *@OlivierGrégoire*. Also mentioned on that tip page is that you can get rid of the error to STDERR by changing it to:

```
enum M{M;{/* Code here */System.exit(0);}}

```

This might be useful if a challenge states it isn't allowed to error and requires a full program (although in the current meta functions are allowed, and errors to STDERR after you've already completed the challenge are also allowed).

*1. Note that `java.applet.Applet` or `javafx.application.Application` classes can run independent without a main-method, although their general use is to be embedded inside another application.*

# Answer
> 0 votes
# J, 24 Bytes

```
(".@,quote)'(".@,quote)'

```

This works on all versions I've tried.

Infinite recursion should throw a stack error, for example, in `$: 0`. However, the `".` verb (eval) seems to fly under the radar, and this crashes the interpreter with a segmentation fault.

Based on the quine

```
(,quote)'(,quote)'

```

Try it online!

# Answer
> 0 votes
# C++ (gcc 4 or 5) + Boost, 94 bytes

I'm not sure exactly which versions of gcc this will or won't work on. The guy who originally reported the bug says the bug is present in gcc4 and gcc5, so I will take his word on it. Personally, I tested it with 5.4.0

```
#include <boost/any.hpp>
#include <cstdarg>
int a(const boost::any&x){}int b(va_list l){a(l);}

```

Attempting to compile this produces:

```
$ gcc gccbug.cpp
gccbug.cpp:3:50: internal compiler error: Segmentation fault
 int a(const boost::any&x){}int b(va_list l){a(l);}
                                                  ^
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-5/README.Bugs> for instructions.

```

---
Tags: code-golf
---


# Question
Title: Most destructive "forgot-to-enter-insert-mode" sequence in Vim
Pretend you have an arbitrary text file (which you may choose).

Give the sequence of keystrokes that is most destructive (\*) if it was intended to be inserted to the text, but instead was entered in normal mode (i.e. `i`/`a` was not pressed). You may not enter visual mode and not quit Vim.

Destructive is defined as follows: The ratio of changed/deleted characters by the number of necessary keystrokes.
You get bonus points if your changes cannot be undone by a fixed number of `u`ndos.

---

Example: Input file without line breaks. Input sequence: `d``f``s`.

# Answer
```
: 0,0 w
:r

```

ruins everything no undo
> 3 votes

# Answer
```
:set ul=-1
ggdG
:w

```

This clears contents of file and saves it. No undo is possible because `undolevel` is set to a negative number, which disables undo operation.

Edit: It's better to write `:g/^/d` instead of `ggdG`, because in the latter case you can use `p` (put) to roll-back the changes.
> 3 votes

# Answer
```
:set ul=-1
:%s///g
:r!head -c1G</dev/urandom
:w

```
1. Disables undo
2. Deletes characters
3. Reads 1G of data from /dev/urandom
4. Saves

Bending the rules, because I am adding characters (a character that isn't there and now is, means a character was changed). I can add as much characters as I want so this score is theoretically infinite.
> 2 votes

# Answer
5 bytes:

```
:bd!

```

followed by a press of enter.

Throws away the current state of the file you're editing from memory, so all unsaved changes in that file are lost. If you have other files open, they are not affected. This does not quit vim even if you have only one file open.
> 2 votes

---
Tags: code-challenge, vim
---


title: Digging quarry timelapse

text:
# Question
Title: Digging quarry timelapse
Do you love watching cool timelapses of constructions or other massive work done in minutes? Lets make one here.
We will be looking at an excavator digging quarry, making pictures each day to see whole progress. And your task is to show us this process!

Quarry is defined by the width of its first layer.
Excavator is defined by its capability to dig in one day.

## Input

Width of quarry. Integer number, always \>= 1.
Excavator dig speed. Integer number, always \>= 1.

## Output

Progress of digging quarry on each day. Started with flat untouched ground and finished with completed quarry.

## Rules

* On the last day there may be less units to dig, than excavator is capable of. Excessive work won't be used anywhere, so you should just output fully dug quarry.
* All days progress must be present in the output at once. You can't clear or overwrite previous day progress in the output.
* Trailing and leading newlines for each day output are acceptable in any reasonable number.
* This is , so make your code as compact as possible.

## Clarifications

Work starts with a flat ground. Length of displayed ground is width of quarry + 2. So there always will be one underscore character on both sides of quarry.

```
__________

```

Dug quarry is looking like this for even width:

```
_        _
 \      /
  \    /
   \  /
    \/

```

And like this for odd width

```
_       _
 \     /
  \   /
   \ /
    V

```

Here are examples of quarry progress:

```
_ _______
 V          dug 1 unit

_  ______
 \/         dug 2 units

_     ___
 \___/      dug 5 units

_       _
 \   __/    dug 10 units
  \_/

```

Full progress example. Quarry width: 8. Excavator speed: 4 units per day.

```
__________

_    _____
 \__/

_        _
 \______/

_        _
 \    __/
  \__/

_        _
 \      /
  \  __/
   \/

_        _
 \      /
  \    /
   \  /
    \/

```

## Cornercases

Excavator will need to dig on the last day exactly its capability (speed)

```
Width: 7, Speed: 3
Width: 10, Speed: 4

```

# Answer
# Stax, 65 bytes

```
Θ└R4∞√4Fµ■zJ┐╚▌▼ZJ╧fφ½à╘▲☼å♥s≥┤ÖòOúU╬ΩmPê|ë↕ƒ].Y┴↓á÷>}St☺┐B╒╞O☼╧O

```

Run and debug it

If first calculates the digging characters, in one flat string. Then it adds depth. For instance `"_V___"` is one day of digging, and `"_\V/_"` is the completed flat string.

It uses this method for doing one unit of digging.

1. Start with a single "\\", plus the appropriate number of "\_" characters.
2. If "V\_" is in the string, replace it with "/".
3. Otherwise, if "/\_" is in the string, replace it with "\_/".
4. Otherwise, if "\\\_" is in the string, replace it with "\V".
5. The new string is the result from one unit of digging. Repeat from step 2.

Here's the whole program unpacked, ungolfed, and commented.

```
'_*'\s+                 initial string e.g. "\_______"
{                       generator block to get each day's flat digging results
  {                     block to repeat digging within each day
    "V_\//__/\_\V"4/    replacement strings
    {[2:/|em|!H         find the first substring that exists and do replacement
  };*                   repeat digging within day specified number of times
gu                      get all unique results
                            when digging is complete, the result duplicates
{Dm                     drop the leading "\" characters from each result
F                       for each day's flat result, execute the rest of the program
  '_|S                  surround with "_"
  M                     split into chars; e.g. ["_", "\", "/", "_"]
  c|[                   copy and get all prefixes
  {                     mapping block to get "depth" of each character
    '\#                 get number of backslashes in this prefix (A)
    _1T'/#-             get number of forward slashes prior to last character of prefix (B)
    'V_H=+^             is the current character "V"? 1 for yes. (C)
  m                     map prefixes to A - B + C + 1
  \                     zip depths with original characters
  {E)m                  prefix each character with spaces; e.g. ["_", " \", " /", "_"]
  M                     transpose grid; e.g. ["_  _", " \/ "]
  m                     print each row

```

Run and debug it
> 1 votes

# Answer
# Retina 0.8.2, ~~163~~ 156 bytes

```
.+
$*_
(_+)¶(_+)
$2¶$1¶$1
r`__\G
$%`$&
¶
;
(?<=(_+);.*)(?<=;_+;\1*)_
¶$`_
m`^_+;
__
+`(>*)_(_+)(_+<?;)\2
$1_$.2$* $3¶$1>$2<;
T`>\_` \\`>+_
T`\\\_;<`V/_`.<|;

```

Try it online! Explanation:

```
.+
$*_

```

Convert the inputs to unary. This gives us `W¶S`.

```
(_+)¶(_+)
$2¶$1¶$1

```

Swap the inputs and duplicate the width. This gives us `S¶W¶W`.

```
r`__\G
$%`$&

```

Calculate the volume of the quarry. This gives us `S¶W¶V`.

```
¶
;

```

Join the inputs into one line. This gives us `S;W;V`.

```
(?<=(_+);.*)(?<=;_+;\1*)_
¶$`_

```

Calculate the amount of progress for each day on its own line. Each day has the format `S;W;D`, where `D` is `0` on the first line and increments by `S` each day until it reaches `V`.

```
m`^_+;
__

```

Delete `S` and increase `W` by 2 on each line. This gives us `G;D` for each day.

```
+`(>*)_(_+)(_+<?;)\2
$1_$.2$* $3¶$1>$2<;

```

While `D` is nonzero, dig either `D` or `G-2` from the line (so the first and last characters are always left), moving the depth to the next line. Each line is indented with one more `>` than the previous. Newly dug lines also include a `<`.

```
T`>\_` \\`>+_

```

Turn the indent into spaces and the following `_` into a `\`.

```
T`\\\_;<`V/_`.<|;

```

If a `<` is following a `\` then turn it into a `V`, if it's following a `_` then turn it into a `/`. Delete all the `<`s and `;`s.
> 4 votes

# Answer
# Python 2, 265 bytes

```
w,s=input();R=range((3+w)/2)
d=0
while d-s<sum(range(w%2,w+1,2)):
 q=[[' _'[i<1]]*(w+2)for i in R];D=d
 for i in R[:-1]:
  a=min(D,w-i*2);D-=a
  if a:q[i][1+i:1+i+a]=[' ']*a;q[i+1][1+i:1+i+a]=(['\\']+['_']*(a-2)+['/'])*(a>1)or['v']
 for l in q:print''.join(l)
 d+=s

```

Try it online!
> 1 votes

# Answer
* golf in progress

# JavaScript (Node.js), 329 315 307 300 301 298 285 275 260 254 bytes

* fixed solution duo to error on odd w(thanks to @Shaggy) + reduce by 2 bytes
* thanks to @Herman Lauenstein for reducing by 1 byte

```
(w,s)=>{h=[...Array(-~w/2+1|0)].map((x,i)=>[...(i?" ":"_").repeat(w)])
for(t=S="";t<s&&h.map((x,i)=>S+=(p=i?" ":"_")+x.join``+p+`
`);)for(y in t=s,h)for(x in D=h[y])if(D[x]=="_"&&t){(d=h[-~y])[x]=x^y?(d[x-1]=x^-~y?"_":"\\","/"):"v"
D[x]=" "
t--}return S}

```

Try it online!

### Explanation

```
(w,s)=>{
h=[...Array(-~w/2+1|0)]                       //the height of the quarry when finished is w/2+1 if even or (w+1)/2+1 if odd
.map((x,i)=>
    [...(i?" ":"_").repeat(w)]                //the first row is the _ w times (i will explain why w and not w+2 in the following lines) afterwards lets just fill with spaces so the output would be clear(when convertion to string)
    )
for(t=S="";                                   //t="" is like t=0(we actually need t to be different from s in the start and s>=1), S will hold the final output
t^s&&                                         //if t not equals s -> it means that now changes were made to the quarry->it means we finished digging
h.map((x,i)=>
S+=(p=i?" ":"_")+x.join``+p+`                 //here comes the reason for w and not w+2. because the border _XXXX_ are not to be touched i only add them to the output and not woking with them in the solution
                                              //that ways its much easier to replace the correct chars. so here i just add _ to either sides if its the first row otherwise space(to pad correctly).
                                              //in the end i add a new line to differ from the previous day
`);)
    for(y in t=s,h)                           //always update t back to s so we know weve passed a day
        for(x in D=h[y])
            if(D[x]=="_"&&t)                  //if the current cell is _ we need to work, but only if the day have yet to pass(t)
            {
                (d=h[-~y])[x]=                //updating the row below us because we just dug a hole
                x^y?                          //if x == y that means we are digging the first hole in the row below
                (d[x-1]=x^-~y?"_":"\\", //we want to update the row below and cell before([y+1][x-1]) only if its not the first cell(AKA not space). if v we need \ other wise _
                    "/")                          //other wise (x!=y) we put "/"
                :"v"                          //so we should put v (if they are equal)
                D[x]=" "                      //always remove the _ from the current one because we dug it
                t--}                          //decrement the counter for the day by one digging
return S}

```
> 1 votes

---
Tags: code-golf, ascii-art
---