title: Let's get ready for Halloween

text:
# Question
Title: Let's get ready for Halloween
I don't know about you all but I'm *not* preparing for Halloween––never did never will––but, my neighbor is, so we'll help her out.

She needs help figuring out which brand of candy she has, but she has so much candy she would not be able to finish before Halloween.

She has:

* Snickers
* KitKat
* Starburst
* GummyBears
* Twix

**Input**

A multiline string (or any other reasonable form) containing only letters and spaces.

**Output**

A falsy value if it is not a valid candy, or which candy it is if it is a candy.

**How to decide which candy it is**

A candy is valid if it says one of the above brands on it. However, it's not that simple, because this is a valid candy:

```
K i t
       K a
           t

```

A valid candy is one where:

* the letters are in order from left to right
* the letters are capitalized correctly
* the letters, going from left to right, do not *both* ascend and descend
* the letters with whitespace removed form one of the above brands

**This is , so shortest code in byte wins!**

**Examples**

Truthys:

```
1.
              kers
           c
        i
       n
    S

2.
  Kit K a t

3.
St a
    r b u
         r st

4.
         Bear s
G ummy

5.
T w i
                          x

```

Falsys:

```
1.
SNICKERS

2.
 C   n

   a   d y

3.
xiwT

4.
S C I
       ss o
              r       s

5.
Kit
Kat

```

# Answer
# Pyth - 72 bytes

I hope I caught all the edge cases. Will base compress candy list.

```
&sSIM_Bmxdh-d;fnd{TK.tQd}-sKdc"Snickers KitKat Starburst GummyBears Twix

```

Test Suite.
> 0 votes

# Answer
# JavaScript (ES6), ~~221~~ ~~218~~ ~~216~~ ~~212~~ ~~208~~ ~~205~~ 201 bytes

```
f=a=>(c=d=L=0,e=1,s=[],[...a].map(a=>a=='\n'?c=L=0:c++-(a!=' '&&(s[c]?e=0:(!L&&(d?d-1?e&=c>Q>d-3:d=c>Q>2:d=1),L=s[Q=c]=a)))),e&&'Snickers0KitKat0Starburst0GummyBears0Twix'.split(0).indexOf(s.join``)+1)

```

# Try it here.
> 1 votes

# Answer
## Racket 446 bytes

```
(let((lr list-ref)(ls list-set)(sl string-length)(ss substring)(l(string-split s "\n")))(let loop((changed #f))(for((i(sub1(length l))))
(let*((s(lr l i))(r(lr l(add1 i)))(n(sl s))(m(sl r)))(when(> n m)(set! l(ls l i(ss s 0 m)))(set! l(ls l(add1 i)
(string-append r(ss s m n))))(set! changed #t))))(if changed(loop #f)(begin(let*((l(for/list((i l))(string-trim i)))(l(string-join l))
(l(string-replace l " " "")))(ormap(λ(x)(equal? x l))cl))))))

```

Ungolfed:

```
(define (f s cl)
  (let ((lr list-ref)
        (ls list-set)
        (sl string-length)
        (ss substring)
        (l (string-split s "\n")))
    (let loop ((changed #f))
      (for ((i (sub1 (length l))))
        (let* ((s (lr l i))
               (r (lr l (add1 i)))
               (n (sl s))
               (m (sl r)))
               (when (> n m)
                 (set! l (ls l i (ss s 0 m)))
                 (set! l (ls l (add1 i)(string-append r (ss s m n))))
                 (set! changed #t))))
        (if changed (loop #f)
            (begin
              (let* ((l (for/list ((i l))
                          (string-trim i)))
                     (l (string-join l))
                     (l (string-replace l " " "")))
                (ormap (λ(x) (equal? x l)) cl)))
            ))))

```

Testing:

```
(f "
              kers
           c
        i
       n
    S"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "  Kit K a t"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "St a
    r b u
         r st "
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "         Bear s
G ummy"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "T w i
                          x"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "SNICKERS"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))
(f " C   n
          y
   a   d"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "xiwT"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "S C I
       ss o
              r       s"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

(f "Kit
Kat"
   (list "Snickers""KitKat""Starburst""GummyBears""Twix"))

```

Output:

```
#t
#t
#t
#t
#t
#f
#f
#f
#f
#t

```
> 1 votes

# Answer
## JavaScript (ES6), 139 bytes

```
a=>/^(Snickers|KitKat|Starburst|GummyBears|Twix)$/.test(a.reduce((s,t)=>s.replace(/./g,(c,i)=>c<'!'?t[i]:t[i]<'!'?c:'!')).replace(/ /g,''))

```

Accepts input as an array of space-padded strings.
> 1 votes

# Answer
# Python 2.7, 254 bytes

I'm sure this can be golfed more. Input is an array of lines `s`.

```
x=len
p=lambda a:x(a)-x(a.lstrip())
g=sorted
a=map(p,l)
j=''.join
z=[i.replace(' ','')for i in l]
if g(a)==a:q=j(z)
elif g(a)==a[::-1]:q=j(z[::-1])
else:q=''
if x(set(a))<x(a):q=''
print 1if q in('Snickers','KitKat','Starburst','GummyBears','Twix')else 0

```

Try it here!
> 0 votes

# Answer
# R, 199 chars

```
function(M){if(any(outer(z<-diff(apply(M,1,function(r)which.min(r==" ")))),z<0))return(F);C=c("Twix","KitKat","Starburst","Snickers","GummyBears");C[match(paste0(gsub(" ","",c(t(M))),collapse=""),C)}

```

Input is in the form of a character matrix.

`match` takes care of *which* candy it is (it checks capitalisation too).

To check that the letters are an "ascending" or "descending" sequence, we just need to check that the locations of the first non-space character (if there) in each row is increasing or decreasing. To do, this we

* take the first location of a nonspace character in each row, using `apply`
* take the `diff`. This might have some zero in it, otherwise should either be all positive or all negative
* name the `diff` `z`, and take the outer product with itself. If the diff had mixed positive and negative entries, there will be a negative entry somewhere in its outer product. If so, return FALSE.

Note that cases like

```
"    i "
"   w x"
"  T   "

```

will return an empty character vector (in particular not "Twix"), since `match` will be trying to match "Twxi".
> 0 votes

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


title: Import this into your own language

text:
# Question
Title: Import this into your own language
The Zen of Python must surely be one of the most beautiful Easter eggs in any language. (It is created by writing `import this`)

So why not create a version for your own language?

For those who don't have access to Python 2 or 3, your code should output the following:

```
The Zen of [YOUR LANGUAGE]

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

```

*The original was `The Zen of Python, by Tim Peters`.*

This is code-golf, so the shortest answer in bytes wins.

Standard loopholes apply, this includes no built-ins (if you are making a solution in Python, Pyth or another derivative of Python, the equivalent of `import this` is forbidden).

# Answer
# JavaScript (ES6) 665 bytes

```
f=a=>{for(_="._eds  ieaouobvishld itxplicpecial  idonesaty ennever th    to mplbetter   an explain, e Althgh If iemti`ThZ of JS__ButifuluglyEiicSiecoexCoexcoicFlntSparsedseRdabilcntsScas ar't sghbrk  rulpracticalbepuryError passiltlyUnlelsilcIn    facof ambiguy, refusthtemptigusTherbe-- and preferabll--waydo th wamanot b first unly'rDutchNowoft *right* nowhard'a badsy maba goodNampac arhking gre -- let'do morof  ose!`";G=/[-]/.exec(_);)with(_.split(G))_=join(shift());return eval(_).split`_`.join`
`}

```

Because of string compression, some characters cannot be displayed in this snippet. This is above script hex-encoded:

```
663D613D3E7B666F72285F3D222E5F1D65641D1C73201B20691B1A6561196F75186F627669181B177368186C64201669741578706C6963151470656369616C201320696419126F6E1165731061740F79200E656E0C6E657665720B2074680920746F20086D706C0762657474657209616E2006086578706C61696E2C2015056520041D416C746818676820031D496609046907656D0C740F69111A021A0601605468045A0C206F66204A535F5F421975746966756C0175676C791D45140169076963151D5369076501636F0765781D436F07657801636F0769630F1C466C0F016E10741C53706172736501640C73651D5219646162696C150E63186E74731D5313636173102061720C27742073130C186768086272196B090472756C100370726163746963616C150E62650F1B70757215791D4572726F721B160B207061731B73696C0C746C791D556E6C101B65146C0E73696C0C631C496E0904666163046F6620616D6269677515792C2072656675730474680474656D70740F691108677510731D546865720416620411652D2D20616E642070726566657261626C0E116C0E11042D2D1777617908646F20150374680F2077610E6D610E6E6F74206204170F20666972737420756E6C101B791827720444757463681D4E6F77010B030B1A6F66740C20062A72696768742A206E6F77026861726405271B6120626164120219737905206D610E62046120676F6F64121D4E616D107061631020617204110468116B696E67206772650F12202D2D206C6574271B646F206D6F72046F66096F73652160223B473D2F5B012D1D5D2F2E65786563285F293B2977697468285F2E73706C6974284729295F3D6A6F696E2873686966742829293B72657475726E206576616C285F292E73706C6974605F602E6A6F696E600D0A607D

```

It can be compiled using the following function:

```
f=a=>eval(a.match(/../g).map(a=>String.fromCharCode(parseInt(a,16))).join``)

```

# Demo
> 2 votes

---
Tags: code-golf, kolmogorov-complexity, python
---


title: Totally Invertible Submatrices

text:
# Question
Title: Totally Invertible Submatrices
*(inspired by this question over on Math)*

### The Definitions

Given an `n x n` square matrix **A**, we can call it `invertible` if there exists some `n x n` square matrix **B** such that **AB** = **BA** = **In**, with **In** being the identity matrix of size `n x n` (the matrix with the main diagonal `1`s and anything else `0`), and **AB** and **BA** representing usual matrix multiplication (I won't go into that here - go take a linear algebra class).

From that, we can call an `m x n` matrix **C** `totally invertible` if every `k x k` submatrix (defined below) of **C** is invertible for all `k > 1`, `k <= (smaller of m,n)`.

A submatrix is defined as the resulting matrix after deletion of any number of rows and/or columns from the original matrix. For example, the below `3x3` matrix **C** can be transformed into a `2x2` submatrix **C'** by removing the first row `1 2 3` and the middle column `2 5 8` as follows:

```
C = [[1 2 3]
     [4 5 6]    -->  C' = [[4 6]
     [7 8 9]]              [7 9]]

```

Note that there are many different submatrix possibilities, the above is just an example. This challenge is only concerned with those where the resulting submatrix is a `k x k` *square matrix*.

### The Challenge

Given an input matrix, determine if it is totally invertible or not.

### The Input

* A single matrix of size `m x n`, in any suitable format.
* Without loss of generality, you can assume `m <= n` or `m >= n`, whichever is golfier for your code, and take the input that way (i.e., you get a transpose operation for free if you want it).
* The input matrix size will be no smaller than `3 x 3`, and no larger than your language can handle.
* The input matrix will consist of only numeric values from **Z+** (the positive integers).

### The Output

* A truthy/falsey value for whether the input matrix is totally invertible.

### The Rules

* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### The Examples

```
Truthy

[[1 2 3]
 [2 3 1]
 [3 1 2]]

[[2 6 3]
 [1 12 2]
 [5 3 1]]

[[1 2 3 4]
 [2 3 4 1]
 [3 4 1 2]]

[[2  3  5  7  11]
 [13 17 19 23 29]
 [31 37 41 43 47]]

Falsey

[[1 2 3]
 [4 5 6]
 [7 8 9]]

[[1 6 2 55 3]
 [4 5 5 5  6]
 [9 3 7 10 4]
 [7 1 8 23 9]]

[[2 3 6]
 [1 2 12]
 [1 1 6]]

[[8 2 12 13 2]
 [12 7 13 12 13]
 [8 1 12 13 5]]

```

# Answer
> 5 votes
# Jelly, ~~26 24 23 20 19 17~~ 16 bytes

-1 byte thanks to @miles (unnecessary for each, , when taking determinants)
-2 bytes, @miles again! (unnecessary chain separation, and use of `Ð€` quick)

```
ZœcLÆḊ
œcÐ€JÇ€€Ȧ

```

**TryItOnline!** or all 8 tests

### How?

```
œcÐ€JÇ€€Ȧ  - Main link: matrix as an array, M
    J      - range of length -> [1,2,...,len(a)] (n)
  Ð€       - for each of right argument
œc         -     combinations of M numbering n
     Ç€€   - call the last link (1) as a monad for €ach for €ach
        Ȧ  - all truthy (any determinant of zero results in 0, otherwise 1)
                 (this includes an implicit flattening of the list)

ZœcLÆḊ - Link 1, determinants of sub-matrices: row selection, s
Z      - transpose s
   L   - length of s
 œc    - combinations of transposed s numbering length of s
    ÆḊ - determinant

```

# Answer
> 5 votes
# Mathematica 10.0, 34 bytes

```
#~Minors~n~Table~{n,Tr@#}~FreeQ~0&

```

A 6-tilde chain... new personal record!

# Answer
> 3 votes
# MATL, 57 bytes

```
tZyt:Y@!"@w2)t:Y@!"@w:"3$t@:)w@:)w3$)0&|H*XHx]J)]xxtZy]H&

```

Of course, you can Try it online!

Input should be in 'portrait' orientation (nRows\>=nColumns). I feel that this may not be the most efficient solution... But at least I'm leaving some room for others to outgolf me. I would love to hear specific hints that could have made this particular approach shorter, but I think this massive bytecount should inspire others to make a MATL entry with a completely different approach. Displays 0 if falsy, or a massive value if truthy (will quickly become Inf if matrix too large; for 1 extra byte, one could replace `H*` with `H&Y` (logical and)). Saved a few bytes thanks to @LuisMendo.

```
tZy  % Duplicate, get size. Note that n=<m.
%   STACK:  [m n], [C]
t: % Range 1:m
%   STACK:  [1...m], [m n], [C]
Y@   % Get all permutations of that range.
%   STACK:  [K],[m n],[C] with K all perms in m direction.
!"   % Do a for loop over each permutation.
%   STACK:  [m n],[C], current permutation in @.
@b   % Push current permutation. Bubble size to top.
%   STACK:  [m n],[pM],[C] with p current permutation in m direction.
2)t:Y@!" % Loop over all permutations again, now in n direction
%   STACK: [n],[pM],[C] with current permutation in @.
@w:" % Push current permutation. Loop over 1:n (to get size @ x @ matrices)
%   STACK: [pN],[pM],[C] with loop index in @.
3$t  % Duplicate the entire stack.
%   STACK: [pN],[pM],[C],[pN],[pM],[C]
@:)  % Get first @ items from pN
%   STACK: [pNsub],[pM],[C],[pN],[pM],[C]
w@:) % Get first @ items from pM
%   STACK: [pMsub],[pNsub],[C],[pN],[pM],[C]
w3$)  % Get submatrix. Needs a `w` to ensure correct order.
%   STACK: [Csub],[pN],[pM],[C]
0&|  % Determinant.
%   STACK: [det],[pN],[pM],[C]
H*XHx% Multiply with clipboard H.
%   STACK: [pN],[pM],[C]
]    % Quit size loop
%   STACK: [pN],[pM],[C]. Expected: [n],[pM],[C]
J)   % Get last element from pN, which is n.
%   STACK: [n],[pM],[C]
]    % Quit first loop
xxtZy% Reset stack to
%   STACK: [m n],[C]
]    % Quit final loop.
H& % Output H only.

```

---
Tags: code-golf, matrix, decision-problem, linear-algebra
---


title: Print the n-th digit of pi

text:
# Question
Title: Print the n-th digit of pi
**Task**

Given an input `n`, calculate the n-th decimal digit of pi

**Rules**

* Answer can be a full program or a function.
* Input must be taken from stdin or from function arguments.
* Output must be either sent to stdout, the return value of a function, or written to a file.
* all `n` values between 0 and 20000 must be supported (can be between 1 and 20001 for 1-indexed languages).
* **Built-ins to calculate pi cannot be used**. This includes pi constants (e.g. `math.pi` in Python) and built-in functions that return either the value of pi, or the n-th digit of pi. This means that an algorithm which calculates pi, or the n-th digit of pi must be implemented in your answer.
* Digits must be calculated at runtime.

First digit (0-th or 1-th, depending on the language) is 3.

This is code-golf, so shortest code in bytes wins.

**EDIT:**

This is not a duplicate of 'Find the n-th decimal of pi', since that challenge allowed built-ins. This one is focused around actually implementing an algorithm to find the digits, rather than relying on built-ins.

# Answer
> 8 votes
# Python 2, ~~182~~ 65 bytes

```
a=p=2*10**20004
i=3
while a:a=i/2*a/i;p+=a;i+=2
print`p`[input()]

```

**repl.it**

Uses the Leibniz formula to calculate 20000 correct digits (plus a handful to allow the algorithm to maintain accuracy) then prints the requested digit.

---

Previous (182):
"The Spigot Algorithm For Pi" of Stanley Rabinowitz and Stan Wagon has the added bonus that it will work for any `n` when implemented as a generator

```
p=lambda n,r=3,a=0,b=1,c=1,d=1,e=3,f=3,i=0:i>n and r or p(n,e,*[((2*b+a)*f,b*d,c*f,d+1,(b*(7*d)+2+(a*f))/(c*f),f+2,i),(10*(a-e*c),10*b,c,d,((10*(3*b+a))/c)-10*e,f,i+1)][4*b+a-c<e*c])

```

**repl.it** Reaches Python's default recursion limit for the 117th digit.

Here is a non-recursive version for 198 bytes:

```
def p(n):
 a=i=0;b=c=d=1;e=f=3
 while i<=n:
     r=e
     if 4*b+a-c<e*c:g=10*(a-e*c);e=((10*(3*b+a))/c)-10*e;b*=10;i+=1
     else:g=(2*b+a)*f;h=(b*(7*d)+2+(a*f))/(c*f);b*=d;c*=f;f+=2;d+=1;e=h
     a=g
 print r

```

**repl.it**

(first indent space, second indent tab), the digits could, of course, be generated by yielding `e` at the start of the `if` clause instead of tracking the last digit with `r`.

# Answer
> 1 votes
# Java 7, ~~260~~ 258 bytes

```
import java.math.*;int c(int n){BigInteger p,a=p=BigInteger.TEN.pow(20010).multiply(new BigInteger("2"));for(int i=1;a.compareTo(BigInteger.ZERO)>0;p=p.add(a))a=a.multiply(new BigInteger(i+"")).divide(new BigInteger((2*i+++1)+""));return(p+"").charAt(n)-48;}

```

Copy from my answer here. Java's built-in `Math.PI` has a precision of 15 decimal points, so I was already forced to use an algorithm for the other challenge anyway..

Used *@LeakyNun's* Python 2 algorithm.

**Ungolfed & test code:**

Try it here. (The ideone can't handle the last two test cases, but it works within 2 sec in the Eclipse IDE.)

```
import java.math.*;
class M{
  static int c(int n){
    BigInteger p, a = p = BigInteger.TEN.pow(20010).multiply(new BigInteger("2"));
    for(int i = 1; a.compareTo(BigInteger.ZERO) > 0; p = p.add(a), i++){
      a = a.multiply(new BigInteger(i+"")).divide(new BigInteger((2 * i++ + 1)+""));
    }
    return (p+"").charAt(n) - 48;
  }

  public static void main(String[] a){
    System.out.print(c(0)+", ");
    System.out.print(c(1)+", ");
    System.out.print(c(2)+", ");
    System.out.print(c(3)+", ");
    System.out.print(c(4)+", ");
    System.out.print(c(11)+", ");
    System.out.print(c(101)+", ");
    System.out.print(c(600)+", ");
    System.out.print(c(761)+", ");
    System.out.print(c(1001)+", ");
    System.out.print(c(10001)+", ");
    System.out.print(c(20001));
  }
}

```

**Output:**

```
3, 1, 4, 1, 5, 8, 8, 2, 4, 3, 5, 2

```

---
Tags: code-golf, math, pi
---


title: N in a row (or column)!

text:
# Question
Title: N in a row (or column)!
### N in a row

### Input:

The character and a 2-Dimensional array.

The array with a size of `N x N` where 1 \<= `N` \<= 26, it will be filled randomly like so:

`N` = 1

```
A

```

`N` = 2

```
B | A
-----
A | B

```

`N` = 3

```
A | B | C
----------
B | A | B
----------
C | A | C

```

As `N` increases by 1, so does the number of letters. A = 1, B = 2, C = 3. There will always be `N` number of each letter.
`N` = 3, there will be 3 As... 3 Bs... 3 Cs...
`N` = 4, there will be 4 As... 4 Bs... 4 Cs... 4 Ds...
`N` = 5, there will be 5 As... 5 Bs... 5 Cs... 5 Ds... 5 Es...

### Output:

The original matrix as well as a manipulated matrix where any given letter has `N` in a row (or column).

Manipulations occur by swapping two letters within the 2-D grid that are adjacent on the x or y axis. You may not swap characters over the boundaries of the array. I.E. You cannot swap Array\[0\]\[N-1\] with Array\[0\]\[0\]. You also may not swap characters diagonally.

### Objective:

Your job is to pick a character `C` to solve for given `N`. Swap characters within the matrix so that there are `N` of `C` in the same row or column.

### Examples:

`N` = 3, `C` = A

```
**A** | **B** | C
----------
B | A | B
----------
C | A | C

```

Swap array\[0\]\[0\] (A) with array\[1\]\[0\] (B) resulting in

```
B | **A** | C
----------
B | **A** | B
----------
C | **A** | C

```

Complete

`N` = 4, `C` = B

```
A | **B** | C | D
--------------
B | **D** | B | A
--------------
D | A | C | C
--------------
A | C | B | D

```

swap array\[1\]\[0\] (B) with array\[1\]\[1\] (D)

```
A | D | C | D
--------------
B | B | B | A
--------------
D | A | C | C
--------------
A | C | **B** | **D**

```

swap array\[2\]\[3\] (B) with array\[3\]\[3\] (D)

```
A | D | C | D
--------------
B | B | B | A
--------------
D | A | C | **C**
--------------
A | C | D | **B**

```

swap array\[3\]\[3\] (B) with array\[3\]\[2\] (C)

```
A | D | C | D
--------------
B | B | B | **A**
--------------
D | A | C | **B**
--------------
A | C | D | C

```

swap array\[3\]\[2\] (B) with array\[3\]\[1\] (A)

```
A | D | C | D
--------------
**B** | **B** | **B** | **B**
--------------
D | A | C | A
--------------
A | C | D | C

```

Complete!

Any letter can be chosen to solve for. As this is the shortest code wins!

Have Fun and Good Luck!

# Answer
> 1 votes
# Python 2, 270 bytes

```
from random import*
e=lambda s,n:all(sum(map(ord,l))!=n*65for l in s)
R,C,d=randint,choice,[-1,1]
def w(a):
 print a;n=len(a);
 while e(a,n)and e(zip(*a),n):
    if n==2:x,y,w,z=0,0,0,1
    else:x,y=R(1,n-2),R(1,n-2);w,z=x+C(d),y+C(d)
    a[y][x],a[z][w]=a[z][w],a[y][x]
 print a

```

Always chooses `A` as character to complete a row/col. Performs random swaps until goal is reached.

Accepts the matrix as list of lists, usage for testing:

```
A="""ADCD
BBBA
DACC
ACDB"""
a=[[c for c in l] for l in A.split('\n')]
w(a)

```

# Answer
> -1 votes
# R, ~~41~~ 40 bytes

This answer provides valid output, although it does not follow the algorithm suggested. Since a limitless number of swapping manipulations are permitted, restrictions on what manipulations are allowed (e.g. the diagonal restriction) are irrelevant, as any permutation of the matrix can be arrived at through a (possibly large) number of swaps. So, I've bypassed the "switching around" part of the matrix manipulation and just went straight to outputting a solved matrix.

Anonymous function that takes a matrix as input, and returns a list of the original matrix and the "solved" matrix.

```
function(m)list(m,array(sort(m),dim(m)))

```

Example input:

```
matrix(c("A","B","A","C","C","B","A","C","B"),3)

```

That is,

> \[,1\] \[,2\] \[,3\]
>
> \[1,\] "A" "C" "A"
>
> \[2,\] "B" "C" "C"
>
> \[3,\] "A" "B" "B"

Gives the following output:

```
[[1]]
     [,1] [,2] [,3]
[1,] "A"  "C"  "A"
[2,] "B"  "C"  "C"
[3,] "A"  "B"  "B"

[[2]]
     [,1] [,2] [,3]
[1,] "A"  "B"  "C"
[2,] "A"  "B"  "C"
[3,] "A"  "B"  "C"

```

While we're at it, here's a function to generate possible input matrices:

```
make_matrix = function(N) matrix(sample(rep(LETTERS[1:N], N)), N)

```

This function takes the first `N` letters of the alphabet, repeated `N` times (i.e. `N*N` characters) and randomly samples from them. The characters are then arranged into a matrix with `N` rows (and, implicitly, `N` columns).

Examples:

```
make_matrix(1)
     [,1]
[1,] "A"
> make_matrix(3)
     [,1] [,2] [,3]
[1,] "C"  "B"  "C"
[2,] "C"  "A"  "B"
[3,] "A"  "B"  "A"

```

And used with our function above (named `f`):

```
> f(make_matrix(10))
[[1]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,] "J"  "C"  "D"  "G"  "E"  "C"  "H"  "G"  "I"  "J"
 [2,] "C"  "D"  "A"  "C"  "H"  "A"  "A"  "E"  "H"  "I"
 [3,] "C"  "B"  "E"  "G"  "C"  "F"  "J"  "A"  "H"  "J"
 [4,] "I"  "E"  "F"  "I"  "B"  "G"  "E"  "F"  "F"  "C"
 [5,] "H"  "I"  "F"  "D"  "B"  "G"  "H"  "A"  "J"  "H"
 [6,] "J"  "E"  "D"  "J"  "A"  "D"  "B"  "D"  "G"  "B"
 [7,] "D"  "B"  "E"  "A"  "G"  "H"  "C"  "C"  "J"  "B"
 [8,] "H"  "D"  "I"  "J"  "B"  "I"  "I"  "F"  "E"  "I"
 [9,] "G"  "F"  "F"  "A"  "J"  "E"  "B"  "A"  "E"  "D"
[10,] "H"  "G"  "A"  "B"  "D"  "I"  "C"  "G"  "F"  "F"

[[2]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [2,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [3,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [4,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [5,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [6,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [7,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [8,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
 [9,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"
[10,] "A"  "B"  "C"  "D"  "E"  "F"  "G"  "H"  "I"  "J"

```

---
Tags: code-golf, array, matrix
---


title: Chaining Programs

text:
# Question
Title: Chaining Programs
# Challenge

In this challenge, you will be writing the first program, p1, of an infinite sequence of programs, in which running pn outputs/generates program pn+1. When concatenating the first n \>= 2 programs, the sequence should output `n`.

# Example

Let's say the first 4 programs are:

```
p1 p2 p3 p4

```

If I were to run `p1`, it should output:

```
p2

```

If I were to run `p1p2`, it should output:

```
2

```

If I were to run `p1p2p3p4` it should output:

```
4

```

If I were to run `p4`, it should generate the next program in the sequence:

```
p5

```

## Scoring

Your score is the byte count of the first `10` programs.

# Answer
# Pyth, 12

p1:

```
l"1

```

p2: `1`

p3: `1`

*etc..*

p1p2p3:

```
l"111

```

Output: `3`

**Explanation:**

```
l        length
 "1      string "1"

```

On first run, this outputs the length of a single character string, `1`. This also happens to be a valid Pyth program, outputting `1` again. Therefore, *pn+1* is always `1`. When the programs are chained, `p1` outputs the length of the chained programs, which will be `n`.
> 50 votes

# Answer
# Lua, ~~950~~ 900 bytes

```
s=io.open(arg[0]):read()if#s<95 then print(s)do return end end print(#s/90) do return end;

```

Ungolfed:

```
s=io.open(arg[0]):read'*a'
if #s < 96 then
    print(s)
    do return end
end
print(#s/90)
do return end;

```

Explanation:

The first line grabs the entire source of the program. Then we compare the length of the entire program to 1 + the length of one single program. If the size of the current program is smaller than this value, than the source is printed, which is the next program, p2, and we exit. Each iteration is just a quine. When several of these are put together, the the conditional fails, and we print the length of the concatenated program divided by the length of one program, which is the number of concatenated programs, n.
> 10 votes

# Answer
# Vitsy, 14 bytes

Similar to the Pyth and Jolf answers, I'm mapping strings. The only difference is that I use the line wrapping features to make sure I always get the right length.

p1

```
'l3-N
```

p2

```
1
```

Replace 1 with *any* single number.

p3 and so on match this pattern, and you can do this until `Integer.MAX_VALUE`, the integer restriction of the language.

Explanation:

```
'l3-N
'     Wrap around the line until finding another '. Since no ' is found before the
      End of the line, it wraps around.
 l    Get the length of the stack.
  3-  Subtract three.
    N Output as number.
```

Try it online!
> 4 votes

# Answer
# Vitsy, 19 bytes

Not dealing with strings here, but using method tricks.

### p1

```
1ml1-\+N
1
```

### p2

```
1
```

### p3

```
1
```

So on, so forth.

Explanation below:

```
1ml1-\+N
1m       Execute the first index of lines (the bit with the ones)
  l1-    Get the length minus 1.
     \+  Add them all up.
       N Output as number.

1        Push one to the stack.
```

Try it online!
> 4 votes

# Answer
# Seriously, 15 bytes

First program, 6 bytes (contains an unprintable):

```
5Ql-.

```

Hex Dump:

```
35516c2d2e7f

```

This program prints `1`: Try it online

The rest of the programs are all `1`, a valid program that prints itself just like the Pyth answer. The original program prints the length of its source code minus 5 and terminates immediately. `1`s appended to the end increase the length of the source code by 1 byte each time, but never get executed.
> 3 votes

# Answer
# Jolf, 14 bytes

Try it here!

```
a-lq4
a      print
  lq   the length of the source code
 -  4  minus 4

```

When executed, this prints `1`. Thus, `p2 = 1`. Executing `p2` yields `1`. So, for all `N > 1`, `pN = 1`.

Observe `p1p2`: `a-1q41`. This transpiles to:

```
alert(sub(length("a-lq41"),4));
1;

```

Since implicit printing is disabled after the first print, this prints `2`, as the length of the source code minus 4 is 2. And on and on and on.
> 2 votes

# Answer
# Ruby, 318 bytes

### p1:

```
x=DATA.readlines.size
_="_=%p;puts _%%_"
puts x>0?x+1:_%_
__END__

```

Each separate program pi outputs this one-line quine: `_="_=%p;puts _%%_";puts _%_`.

When you add these quines to the end of p1, they end up as lines in the `DATA` object because they are below the magic `__END__`.

Here's a test:

```
$ ruby chain.rb                                    # running p1
_="_=%p;puts _%%_";puts _%_

$ ruby -e '_="_=%p;puts _%%_";puts _%_'            # running p2
_="_=%p;puts _%%_";puts _%_

$ ruby -e '_="_=%p;puts _%%_";puts _%_'            # running p3
_="_=%p;puts _%%_";puts _%_

$ # Concatenating p2 and p3 to p1:
$ ruby -e '_="_=%p;puts _%%_";puts _%_' >> chain.rb
$ ruby -e '_="_=%p;puts _%%_";puts _%_' >> chain.rb

$ ruby chain.rb                                    # running p1p2p3
3

```

The ten first programs concatenated looks like this (318 bytes):

```
x=DATA.readlines.size
_="_=%p;puts _%%_"
puts x>0?x+1:_%_
__END__
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_
_="_=%p;puts _%%_";puts _%_

```
> 2 votes

# Answer
# C#, 2099 + 7 = 2106 bytes

First program (uses compiler flag `/main:A`):

```
class A{static void Main(){int a=System.Reflection.Assembly.GetEntryAssembly().GetTypes().Length;var b=@"class A{0}{{static void Main(){{var a=@""{1}"";System.Console.Write(a,{0}+1,a.Replace(""\"""",""\""\""""));}}}}";System.Console.Write(a>1?"{2}":b,0,b.Replace("\"","\"\""),a);}}

```

Second program:

```
class A0{static void Main(){var a=@"class A{0}{{static void Main(){{var a=@""{1}"";System.Console.Write(a,{0}+1,a.Replace(""\"""",""\""\""""));}}}}";System.Console.Write(a,0+1,a.Replace("\"","\"\""));}}

```

Third program:

```
class A1{static void Main(){var a=@"class A{0}{{static void Main(){{var a=@""{1}"";System.Console.Write(a,{0}+1,a.Replace(""\"""",""\""\""""));}}}}";System.Console.Write(a,1+1,a.Replace("\"","\"\""));}}

```

You get the idea.
> 1 votes

# Answer
# Javascript ES6, score ~~483~~ 455

Program 1, 77 bytes:

```
v=1;setTimeout(_=>alert(v>1?v:'a=_=>this.v?v++:alert("a="+a+";a();");a();'));

```

Program 2 and beyond, 42 bytes each:

```
a=_=>this.v?v++:alert("a="+a+";a();");a();

```
> 0 votes

# Answer
# PHP, 1470 bytes

Program 1: 219 bytes:

```
class O{public$n=1;function __destruct(){echo($n=$this->n)>1?$n:'if(!$o->n++)echo str_replace(chr(9),$a=aWYoISRvLT5uKyspZWNobyBzdHJfcmVwbGFjZShjaHIoOSksJGE9CSxiYXNlNjRfZGVjb2RlKCRhKSk7,base64_decode($a));';}}$o=new O();

```

progam 2 and beyond 139 bytes:

```
if(!$o->n++)echo str_replace(chr(9),$a=aWYoISRvLT5uKyspZWNobyBzdHJfcmVwbGFjZShjaHIoOSksJGE9CSxiYXNlNjRfZGVjb2RlKCRhKSk7,base64_decode($a));

```

use like:

```
php -r "class O{public$n=1;function __destruct(){echo($n=$this->n)>1?$n:'if(!$o->n++)echo str_replace(chr(9),$a=aWYoISRvLT5uKyspZWNobyBzdHJfcmVwbGFjZShjaHIoOSksJGE9CSxiYXNlNjRfZGVjb2RlKCRhKSk7,base64_decode($a));';}}$o=new O();"

```

Uses a slightly golfed version the php quine technique detailed here: http://10types.co.uk/the-lab/a-minimal-php-quine/
> 0 votes

---
Tags: code-challenge, code-generation
---


title: Perform several mathematic operations

text:
# Question
Title: Perform several mathematic operations
# The task:

You have to input 2 numbers and output the results of several operations done with them.

# Details:

Input 2 floating point numbers, x != 0 and y != 0 via stdin, command line or function arguments. Output x+y,
x\*y,
x^y (pow(x,y), not x XOR y),
x-y,
y-x,
x/y and
y/x on STDOUT separated by newlines, commas or spaces.

For languages which doesn't support floats, you may use an external library, implement them yourself or you can not participate :( Standard loopholes apply, the shortest code in bytes wins. Good luck!

# Answer
> 3 votes
# Dyalog APL, 15 bytes

Takes x as left argument and y as right argument.

```
+,×,*,-,-⍨,÷,÷⍨

```

Simply a long train of forks (3-trains):

`+,` the sum, followed by

`×,` the product, followed by

`*,` the exponentiation, followed by

`-,` the difference, followed by

`-⍨,` the swapped difference, followed by

`÷,` the ratio, followed by

`÷⍨` the swapped ratio

TryAPL online!

# Answer
> 1 votes
## Haskell, 44 bytes

```
x#y=mapM print[x+y,x*y,x**y,x-y,y-x,x/y,y/x]

```

Example: `4 # 5` prints

```
9.0
20.0
1024.0
-1.0
1.0
0.8
1.25

```

# Answer
> 1 votes
## Ruby, 40 bytes

```
->x,y{puts x+y,x*y,x**y,x-y,y-x,x/y,y/x}

```

# Answer
> 0 votes
# Scala, 68 bytes

```
(x:Float,y:Float)=>Seq(x+y,x*y,math.pow(x,y),x-y,x/y,y/x)map println

```

Pretty striaghtforward.

# Answer
> 0 votes
# Groovy, 36 bytes

```
{a,b->print([a+b,a-b,a/b,a*b,a**b])}

```

Output:

```
({a,b->print([a+b,a-b,a/b,a*b,a**b])})(5.034,2.0568)

```

Results in:

```
[7.0908, 2.9772, 2.4474912485, 10.3539312, 27.777623862468822]

```

# Answer
> 0 votes
# J, 15 bytes

Equivalent to this.

Takes x as left argument and y as right argument.

```
+,*,^,-,-~,%,%~

```

Simply a long train of forks (3-trains):

`+,` the sum, followed by

`*,` the product, followed by

`^,` the exponentiation, followed by

`-,` the difference, followed by

`-~,` the swapped difference, followed by

`%,` the ratio, followed by

`%~` the swapped ratio

# Answer
> 0 votes
## PowerShell v2+, 66 bytes

```
param($x,$y)$x+$y;$x*$y;[math]::Pow($x,$y);$x-$y;$y-$x;$x/$y;$y/$x

```

Very boring, does exactly what it says on the tin. Each statement (separated by `;`) is evaluated and left on the pipeline. At program completion, everything left on the pipeline is implicitly printed via `Write-Output`.

Long because PowerShell uses `$` to delineate variables, and it also doesn't have a `^` or `**` or equivalent operator, so we need a .NET call.

Note that the `Write-Output` will *display* as integer values, even if the input is floats. Running a `.GetType()` will show the output to be `System.Double` however.

```
PS C:\Tools\Scripts\golfing> .\perform-several-mathematic-operations.ps1 5.0 6.0
11
30
15625
-1
1
0.833333333333333
1.2

```

# Answer
> 0 votes
# C# - 106 bytes

```
void r(float x,float y){System.Console.WriteLine($"{x+y} {x*y} {Math.Pow(x,y)} {x-y} {y-x} {x/y} {y/x}");}

```

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


title: Tips for golfing in Cheddar

text:
# Question
Title: Tips for golfing in Cheddar
Cheddar is a high-level, functional + object-oriented programming language created by our user Downgoat designed to make programming easier, faster, and more intuitive.

What general tips do you have for golfing in Cheddar? I'm looking for ideas which can be applied to problems and which are also at least somewhat specific to Cheddar (e.g. "Remove unnecessary whitespace." is not an answer).

# Answer
# Use Functionized Properties

If you ever use just a property in a function:

```
A->A.long.property(n).foo.bar

```

You can use functionized properties to save some bytes:

```
@.long.property(n).foo.bar

```

You can reference the variable in the functionized property with `$0`.
> 3 votes

# Answer
## Use the String Operator for string sequences

I'm talking about the **`@"`** operator which does different things, all of which deal with strings. This has quite a bit of uses but this is one of my favorite uses:

Take a look at this:

```
@" [103, 111, 97, 116, 115] === "goats"

```

not that useful but the opposite is:

```
@"'goats' === [103, 111, 97, 116, 115]
'goats'.bytes // compare the above too

```

This is especially useful to **generate the alphabet**:

```
65@"90    // Uppercase Alphabet
97@"122   // Lowercase Alphabet
65@"90+97@"122 // Both cases
String.letters // Compare 97@"122 to this

```
> 2 votes

# Answer
## Curry

No not red curry (what other curry would you be thinking about ¬\_¬). I mean this type of curry:

```
a->b->

```

If you have a function taking two arguments. It's shorter to curry than to not:

```
(a,b)->
a->b->

```

Note: This is only shorter when you have **exactly two** arguments.
> 1 votes

# Answer
## Use default arguments

Declaring Cheddar variables can be quite the byte-waster:

```
->{var a=b+1}

```

luckily, you can (ab)use function default values for creating variables:

```
b=a+1->b

```

---

Here are some examples of uses:

```
let f= (a,b=a+1)->b
f(5) // 6

let f= a=Math.rand()->a
f() // 0.8757450950797647

```
> 1 votes

# Answer
# Use Functionized Operators and Bonding

This is a simple one. If you have anything like:

```
i->1+i

```

or any similar operation. You can shorten using functionized operators + bonding:

```
1&(+)

```
> 1 votes

# Answer
# Use the mapping operator

The `=>` maps LHS to RHS, due to it's precedence, this also means you can use it with ranges and use it multiple times:

```
a=>f
(a).map(f)

```

Additionally:

```
a=>f=>g           // This is equivilant to...
(a).map(f).map(g) // this

```
> 1 votes

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


title: A penny saved is a penny

text:
# Question
Title: A penny saved is a penny
# ...counted!

You will pass your program a variable which represents a quantity of money in dollars and/or cents and an array of coin values. Your challenge is to output the number of possible combinations of the given array of coin values that would add up to the amount passed to the code. If it is not possible with the coins named, the program should return `0`.

Note on American numismatic terminology:

* 1-cent coin: penny
* 5-cent coin: nickel
* 10-cent coin: dime
* 25-cent coin: quarter (quarter dollar)

**Example 1:**

Program is passed:

```
12, [1, 5, 10]

```

(12 cents)

Output:

```
4

```

There are 4 possible ways of combining the coins named to produce 12 cents:

1. 12 pennies
2. 1 nickel and 7 pennies
3. 2 nickels and 2 pennies
4. 1 dime and 2 pennies

**Example 2:**

Program is passed:

```
26, [1, 5, 10, 25]

```

(26 cents)

Output:

```
13

```

There are 13 possible ways of combining the coins named to produce 26 cents:

1. 26 pennies
2. 21 pennies and 1 nickel
3. 16 pennies and 2 nickels
4. 11 pennies and 3 nickels
5. 6 pennies and 4 nickels
6. 1 penny and 5 nickels
7. 16 pennies and 1 dime
8. 6 pennies and 2 dimes
9. 11 pennies, 1 dime, and 1 nickel
10. 6 pennies, 1 dime, and 2 nickels
11. 1 penny, 1 dime, and 3 nickels
12. 1 penny, 2 dimes, and 1 nickel
13. 1 quarter and 1 penny

**Example 3:**

Program is passed:

```
19, [2, 7, 12]

```

Output:

```
2

```

There are 2 possible ways of combining the coins named to produce 19 cents:

1. 1 12-cent coin and 1 7-cent coin
2. 1 7-cent coin and 6 2-cent coins

**Example 4:**

Program is passed:

```
13, [2, 8, 25]

```

Output:

```
0

```

There are no possible ways of combining the coins named to produce 13 cents.

---

This has been through the Sandbox. Standard loopholes apply. This is code golf, so the answer with the fewest bytes wins.

# Answer
# Jelly (fork), 2 bytes

```
æf

```

This relies on a branch of Jelly where I was working on implementing Frobenius solve atoms so unfortunately you cannot try it online.

## Usage

```
$ ./jelly eun 'æf' '12' '[1,5,10]'
4
$ ./jelly eun 'æf' '26' '[1,5,10,25]'
13
$ ./jelly eun 'æf' '19' '[2,7,12]'
2
$ ./jelly eun 'æf' '13' '[2,8,25]'
0

```

## Explanation

```
æf  Input: total T, denominations D
æf  Frobenius count, determines the number of solutions
    of nonnegative X such that X dot-product D = T

```
> 13 votes

# Answer
## Haskell, ~~37~~ 34 bytes

```
s#l@(c:d)|s>=c=(s-c)#l+s#d
s#_=0^s

```

Usage example: `26 # [1,5,10,25]` -\> `13`.

Simple recursive approach: try both the next number in the list (as long as it is less or equal to the amount) and skip it. If subtracting the number leads to an amount of zero, take a `1` else (or if the list runs out of elements) take a `0`. Sum those `1`s and `0`s.

Edit: @Damien: saved 3 bytes by pointing to a shorter base case for the recursion (which also can be found in @xnors answer).
> 18 votes

# Answer
## Mathematica, ~~35~~ 22 bytes

*Thanks to miles for suggesting `FrobeniusSolve` and saving 13 bytes.*

```
Length@*FrobeniusSolve

```

Evaluates to an unnamed function, which takes the list of coins as the first argument and the target value as the second. `FrobeniusSolve` is a shorthand for solving Diophantine equations of the form

```
a<sub>1</sub>x<sub>1</sub> + a<sub>2</sub>x<sub>2</sub> + ... + a<sub>n</sub>x<sub>n</sub> = b
```

for the `x<sub>i</sub>` over the non-negative integers and gives us all the solutions.
> 15 votes

# Answer
# Pyth, 8 bytes

```
/sM{yS*E

```

Raw brute force, too memory intensive for actual testing. This is O(2<sup>*mn*</sup>), where *n* is the number of coins and *m* is the target sum. Takes input as `target\n[c,o,i,n,s]`.

```
/sM{yS*EQQ      (implicit Q's)
      *EQ       multiply coin list by target
     S          sort
    y           powerset (all subsequences)
   {            remove duplicates
 sM             sum all results
/        Q      count correct sums

```
> 12 votes

# Answer
## JavaScript (ES6), ~~51~~ 48 bytes

```
f=(n,a,[c,...b]=a)=>n?n>0&&c?f(n-c,a)+f(n,b):0:1

```

Accepts coins in any order. Tries both using and not using the first coin, recursively calculating the number of combinations either way. `n==0` means a matching combination, `n<0` means that the coins exceed the quantity while `c==undefined` means that there are no coins left. Note that the function is very slow and if you have a penny coin then the following function is faster (don't pass the penny coin in the array of coins):

```
f=(n,a,[c,...b]=a)=>c?(c<=n&&f(n-c,a))+f(n,b):1

```
> 9 votes

# Answer
## Haskell, 37 bytes

```
s%(h:t)=sum$map(%t)[s,s-h..0]
s%_=0^s

```

Using some multiple of the first coin `h` decreases the required sum `s` to a non-negative value in the decreasing progression `[s,s-h..0]`, which then must be made with the remaining coins. Once there's no coins left, check that the sum is zero arithmetically as `0^s`.
> 9 votes

# Answer
## Perl, 45 bytes

Byte count includes 44 bytes of code and `-p` flag.

```
s%\S+%(1{$&})*%g,(1x<>)=~/^$_$(?{$\++})^/x}{

```

Takes the coin values on the first line, and the targeted amount on the second line :

```
$ perl -pE 's%\S+%(1{$&})*%g,(1x<>)=~/^$_$(?{$\++})^/x}{' <<< "1 5 10 25
26"
13

```

**Short explanations:**

```
-p                        # Set $_ to the value of the input,
                          # and adds a print at the end of the code.
s%\S+%(1{$&})*%g,         # Converts each number n to (1{$&})* (to prepare the regex)
                          # This pattern does half the job.
(1x<>)                    # Converts the target to unary representation.
  =~                      # Match against.. (regex)
    /^ $_ $               # $_ contains the pattern we prepared with the first line.
     (?{$\++})            # Count the number of successful matches
     ^                    # Forces a fail in the regex since the begining can't be matched here.
    /x                    # Ignore white-spaces in the regex
                          # (needed since the available coins are space-separated)
 }{                       # End the code block to avoid the input being printed (because of -p flag)
                          # The print will still be executed, but $_ will be empty,
                          # and only $\ will be printed (this variable is added after every print)

```
> 7 votes

# Answer
# JavaScript (ES6), 59 bytes

```
f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),0):1

```

Coins are input from highest to lowest, e.g. `f(26,[100,25,10,5,1])`. If you have a penny, remove it and use this much faster version instead:

```
f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),1):1

```

This uses a recursive formula much like @nimi's. I originally wrote this a few days ago when the challenge was still in the sandbox; it looked like this:

```
f=(n,c=[100,25,10,5])=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),1):1

```

The only differences being the default value of `c` (it had a set value in the original challenge), and changing the `0` in the `.reduce` function to `1` (this was two bytes shorter and a bazillion times faster than `c=[100,25,10,5,1]`).

---

Here's a modified version which outputs all combinations, rather than the number of combinations:

```
f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:[...x,...f(n-y,c.slice(i)).map(c=>[...c,y])],[]):[[]]

```
> 6 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
œċÐ€S€€Fċ

```

**Try it online!**

### How?

```
œċÐ€S€€Fċ - Main link: coins, target
  Ð€      - map over right argument, or for each n in [1,2,...,target]
œċ        - combinations with replacement, possible choices of each of n coins
    S€€   - sum for each for each (values of those selections)
       F  - flatten into one list
        ċ - count occurrences of right argument

```
> 6 votes

# Answer
# PHP, 327 Bytes

```
function c($f,$z=0){global$p,$d;if($z){foreach($p as$m){for($j=0;$j<=$f/$d[$z];){$n=$m;$n[$d[$z]]=$j++;$p[]=$n;}}}else for($p=[],$j=0;$j<=$f/$d[$z];$j++)$p[]=[$d[$z]=>$j];if($d[++$z])c($f,$z);}$d=$_GET[a];c($e=$_GET[b]);foreach($p as$u){$s=0;foreach($u as$k=>$v)$s+=$v*$k;if($s==$e&count($u)==count($d))$t[]=$u;}echo count($t);

```

Try it
> 5 votes

# Answer
## Axiom, ~~63~~ 62 bytes

1 byte saved by @JonathanAllan

```
f(n,l)==coefficient(series(reduce(*,[1/(1-x^i)for i in l])),n)

```

This approach uses generating functions. Probably that didn't help bring down the code size. I think this is the first time that in my playing with Axiom I went as far as defining my own function.

The first time the function is called it gives a horrendous warning, but still produces the correct result. After that, everything is fine as long as the list isn't empty.
> 5 votes

# Answer
# R, ~~81~~ ~~76~~ 63 bytes

Thanks to @rturnbull for golfing away 13 bytes!

```
function(u,v)sum(t(t(expand.grid(lapply(u/v,seq,f=0))))%*%v==u)

```

Example (note that `c(...)` is how you pass vectors of values to R):

```
f(12,c(1,5,10))
[1] 4

```

Explanation:

`u` is the desired value, `v` is the vector of coin values.

```
expand.grid(lapply(u/v,seq,from=0))

```

creates a data frame with every possible combination of 0 to k coins (k depends on the denomination), where k is the lowest such that k times the value of that coin is at least u (the value to achieve).

Normally we would use `as.matrix` to turns that into a matrix, but that is many characters. Instead we take the transpose of the transpose (!) which automatically coerces it, but takes fewer characters.

`%*% v` then calculates the monetary value of each row. The last step is to count how many of those values are equal to the desired value `u`.

Note that the computational complexity and memory requirements of this are horrific but hey, it's code golf.
> 5 votes

# Answer
# J, 27 bytes

```
1#.[=](+/ .*~]#:,@i.)1+<.@%

```

## Usage

```
   f =: 1#.[=](+/ .*~]#:,@i.)1+<.@%
   12 f 1 5 10
4
   26 f 1 5 10 25
13
   19 f 2 7 12
2
   13 f 2 8 25
0

```

## Explanation

```
1#.[=](+/ .*~]#:,@i.)1+<.@%  Input: target T (LHS), denominations D (RHS)
                          %  Divide T by each in D
                       <.@   Floor each
                             These are the maximum number of each denomination
                     1+      Add 1 to each, call these B
                ,@i.         Forms the range 0 the the product of B
             ]               Get B
              #:             Convert each in the range to mixed radix B
     ]                       Get D
       +/ .*~                Dot product between D and each mixed radix number
                             These are all combinations of denominations up to T
   [                         Get T
    =                        Test if each sum is equal to T
1#.                          Convert as base 1 digits to decimal (takes the sum)
                             This is the number of times each sum was true

```
> 3 votes

# Answer
# TSQL, 105 bytes

This can only handle up to one dollar with these 4 coin types. The ungolfed version can handle up to around 4 dollars, but very slow - on my box this takes 27 seconds. Result is 10045 combinations b.t.w.

Golfed:

```
DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)
;WITH c as(SELECT 0l,0s UNION ALL SELECT z,s+z FROM c,@t WHERE l<=z and s<@)SELECT SUM(1)FROM c WHERE s=@

```

Ungolfed:

```
-- input variables
DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)

-- query
;WITH c as
(
  SELECT 0l,0s
  UNION ALL
  SELECT z,s+z
  FROM c,@t
  WHERE l<=z and s<@
)
SELECT SUM(1)
FROM c
WHERE s=@
-- to allow more than 100 recursions(amounts higher than 1 dollar in this example)
OPTION(MAXRECURSION 0)

```

**Fiddle**
> 2 votes

# Answer
## tinylisp repl, 66 bytes

```
(d C(q((Q V)(i Q(i(l Q 0)0(i V(s(C(s Q(h V))V)(s 0(C Q(t V))))0))1

```

Recursive solution: tries using the first coin and not using the first coin, then adds the results from each. Exponential time complexity and no tail-recursion, but it computes the test cases just fine.

Ungolfed (key to builtins: `d` = define, `q` = quote, `i` = if, `l` = less-than, `s` = subtract, `h` = head, `t` = tail):

```
(d combos
 (q
  ((amount coin-values)
   (i amount
    (i (l amount 0)
     0
     (i coin-values
      (s
       (combos
        (s amount (h coin-values))
        coin-values)
       (s
        0
        (combos
         amount
         (t coin-values))))
      0))
    1))))

```

Example usage:

```
tl> (d C(q((Q V)(i Q(i(l Q 0)0(i V(s(C(s Q(h V))V)(s 0(C Q(t V))))0))1
C
tl> (C 12 (q (1 5 10)))
4
tl> (C 26 (q (1 5 10 25)))
13
tl> (C 19 (q (2 7 12)))
2
tl> (C 13 (q (2 8 25)))
0
tl> (C 400 (q (1 5 10 25)))
Error: recursion depth exceeded. How could you forget to use tail calls?!

```
> 2 votes

# Answer
# Actually, 15 bytes

Golfing suggestions welcome. Try it online!

```
╗;R`╜∙♂S╔♂Σi`Mc

```

**Ungolfing**

```
         Implicit input n, then the list of coins a.
╗        Save a to register 0.
;R       Duplicate n and create a range [1..n] from that duplicate.
`...`M   Map the following function over that range. Variable i.
  ╜        Push a from register 0.
  ∙        Push the i-th Cartesian power of a.
  ♂S       Sort each member of car_pow.
  ╔        Uniquify car_pow so we don't count too any duplicate coin arrangements.
  ♂Σ       Take the sum of each coin arrangement.
  i        Flatten the list.
c        Using the result of the map and the remaining n, push map.count(n).
         Implicit return.

```
> 1 votes

# Answer
# PHP, 130 bytes

```
function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));

```

99 byte recursive function (and 31 bytes of calling it) that repeatedly removes the value of the current coin from the target and calls itself with the new value and the other coins. Counts the number of times the target reaches 0 exactly. Run like:

```
 php -r "function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));" 12 1 5 10

```
> 1 votes

# Answer
## Racket 275 bytes

```
(set! l(flatten(for/list((i l))(for/list((j(floor(/ s i))))i))))(define oll'())(for((i(range 1(add1(floor(/ s(apply min l)))))))
(define ol(combinations l i))(for((j ol))(set! j(sort j >))(when(and(= s(apply + j))(not(ormap(λ(x)(equal? x j))oll)))(set! oll(cons j oll)))))oll

```

Ungolfed:

```
(define(f s l)
  (set! l              ; have list contain all possible coins that can be used
        (flatten
         (for/list ((i l))
           (for/list ((j
                       (floor
                        (/ s i))))
             i))))
  (define oll '())                    ; final list of all solutions initialized
  (for ((i (range 1
                  (add1
                   (floor             ; for different sizes of coin-set
                    (/ s
                       (apply min l)))))))
    (define ol (combinations l i))          ; get a list of all combinations
    (for ((j ol))                           ; test each combination
      (set! j (sort j >))
      (when (and
             (= s (apply + j))              ; sum is correct
             (not(ormap                     ; solution is not already in list
                  (lambda(x)
                    (equal? x j))
                  oll)))
        (set! oll (cons j oll))             ; add found solution to final list
        )))
  (reverse oll))

```

Testing:

```
(f 4 '[1 2])
(println "-------------")
(f 12 '[1 5 10])
(println "-------------")
(f 19 '[2 7 12])
(println "-------------")
(f 8 '(1 2 3))

```

Output:

```
'((2 2) (2 1 1) (1 1 1 1))
"-------------"
'((10 1 1) (5 5 1 1) (5 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 1 1 1 1 1))
"-------------"
'((12 7) (7 2 2 2 2 2 2))
"-------------"
'((3 3 2) (2 2 2 2) (3 2 2 1) (3 3 1 1) (2 2 2 1 1) (3 2 1 1 1) (2 2 1 1 1 1) (3 1 1 1 1 1) (2 1 1 1 1 1 1) (1 1 1 1 1 1 1 1))

```

Following recursive solution has some error:

```
(define (f s l)                      ; s is sum needed; l is list of coin-types
  (set! l (sort l >))
  (define oll '())                   ; list of all solution lists
  (let loop ((l l)
             (ol '()))               ; a solution list initialized
    (when (not (null? l))
        (set! ol (cons (first l) ol)))
    (define ols (apply + ol))        ; current sum in solution list
    (cond
      [(null? l) (remove-duplicates oll)]
      [(= ols s) (set! oll (cons ol oll))
                 (loop (rest l) '())
                 ]
      [(> ols s) (loop (rest l) (rest ol))
                 (loop (rest l) '())
                 ]
      [(< ols s) (loop l ol)
                 (loop (rest l) ol)
                 ])))

```

Does not work properly for:

```
(f 8 '[1 2 3])

```

Output:

```
'((1 1 1 2 3) (1 2 2 3) (1 1 1 1 1 1 1 1) (2 3 3) (1 1 1 1 1 1 2) (1 1 1 1 2 2) (1 1 2 2 2) (2 2 2 2))

```

(1 1 3 3) is possible but does not come in solution list.
> 1 votes

# Answer
# Jelly, 15 bytes

```
s+\Fṁḷ
2*BW;ç/Ṫ

```

Try it online! or Verify all test cases.

This was more of an exercise in writing an efficient version in Jelly without using builtins. This is based on the typical dynamic programming approach used to calculate the number of ways for making change

## Explanation

```
s+\Fṁḷ  Helper link. Input: solutions S, coin C
s       Slice the solutions into non-overlapping sublists of length C
 +\     Cumulative sum
   F    Flatten
     ḷ  Left, get S
    ṁ   Mold the sums to the shape of S

2*BW;ç/Ṫ  Main link. Input: target T, denominations D
2*        Compute 2^T
  B       Convert to binary, creates a list with 1 followed by T-1 0's
          These are the number of solutions for each value from 0 to T
          starting with no coins used
   W      Wrap it inside another array
    ;     Concatenate with D
     ç/   Reduce using the helper link
       Ṫ  Tail, return the last value which is the solution

```
> 1 votes

# Answer
# Python, 120 bytes

```
from itertools import*
lambda t,L:[sum(map(lambda x,y:x*y,C,L))-t for C in product(range(t+1),repeat=len(L))].count(0)

```

Bruteforces through all combinations of coins up to target value (even if the smallest is not 1).
> 0 votes

---
Tags: code-golf, math, combinatorics, counting, integer-partitions
---


title: Draw an ASCII-O'-Lantern for Halloween

text:
# Question
Title: Draw an ASCII-O'-Lantern for Halloween
Halloween is almost here, the holiday after which most people need to wean themselves off a hollow diet of sugar.

Write a program that takes in a positive integer. If the integer is less than 31 (1 through 30), output this ASCII-art jack-o'-lantern, looking to the right as if looking forward to Halloween:

```
 _____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|

```

If the input *is* 31 (the October date Halloween is on), output the same ASCII-o'-lantern, but looking left:

```
 _____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|

```

If the input is greater than 31, output a bloated-looking ASCII-o'-lantern who probably ate too much candy. He can face either left or right since queasyness can be disorientating. So output:

```
 _____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|

```

*or*

```
 _____I_____
| | | | | | |
| | |o| |o| |
| | | |^| | |
| | |XXXXX| |
|_|_|_|_|_|_|

```

Whichever you prefer. It may even be different for different numbers above 31.

**The shortest code in bytes wins.**

# Answer
> 9 votes
# 아희(Aheui), 914 bytes

```
붕빠뿌빠삮빠싸빠받따싼사주따반따퍄속맣이
숚뽀빠소뚜번범뻐터번선야챠슊산받발따다뿌
분뽀더번투빠뿌삮뿌다뿌쑬섣뽀빠뼈ㅇ뚜범쑬
받발따또싾솒빠쏟싿솓아삲쏠쑧뽀터벋터볼설
뿌뻐뻐뻐선썬뻐퍼섟썫선뻐퍼샧셗뺘쎣뺘뼈선
받따반타파빠빠받따받반타타싾삲빠빠빠빠뿌
숟썭뻐선썭뻐섣썭뻐선썭뻐섣썯터범떠범뻐선
빠싽술빠싽산빠싽삳빠싽숟삮쎨뿌서탸쥬싸셔
쀼이썭솓쀼섣싻이연우섞빠쏠뱐선반노쌹뻐숛
손빠쓞유삯쏢으산뽀쌹쏡야뼈섣싺이셗처솓썱
아솓썲솑쏢삱쏜빠쌄숞뚜범범섩뻐분터뿌뻐튜
번이손쎫ㅇ야샨우쌃이쀼뱔뿌떠뽀투또뿌뽀노
본떠벋뻐떠번떠숃볌쎬볌섩뿌빠뽀펴봄벌뽀뻐
샯이멓삭뭏ㅇㅇ이멓샥뎌뵥뿌븀범이멓삭뭏맣
맣이ㅇ몋섨희ㅇㅇㅇㅇㅇ먛뻐살뽀ㅇ솕멓샮속

```

Try it here! (please copy and paste the code manually)

Aheui might not be for golfing, but it's fun nonetheless. :)

**Outputs:**

N = 10

```
 _____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|

```

N = 31

```
 _____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|

```

N = 40

```
 _____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|

```

# Answer
> 8 votes
# JavaScript (ES6), ~~185~~ ~~142~~ ~~140~~ 136 bytes

Now you can tweet-a-pumpkin!

```
n=>` _____I_____
0 4 1
02421
0 |^| 1
031
|_|_|_|_|_|_|`.replace(/\d/g,x=>x-2?x-3?x^n>30?"| |":"| | |":n>31?"XXXXX":"VvVvV":n>31?"o":"^")

```

Probably still room for improvement...

# Answer
> 4 votes
# Jelly, 73 bytes

```
“ẋƥḷỊKNṇ&JƝ¡'Ɲṣ,c;|Ṙɗ.hṿ#⁴ɠ³Ṙṅ’b8ị“ I|o^Xv_”
<32ị“o^XV“vX”y¢s13µ¹U31=³¤?Y

```

Full program
**TryItOnline!**

Might be possible to golf this with the aid of bounce, `ŒḄ`.

### How?

```
“ẋƥḷỊKNṇ&JƝ¡'Ɲṣ,c;|Ṙɗ.hṿ#⁴ɠ³Ṙṅ’b8ị“ I|o^Xv_” - Link 1, Jack construction
“ẋƥḷỊKNṇ&JƝ¡'Ɲṣ,c;|Ṙɗ.hṿ#⁴ɠ³Ṙṅ’              - a base 250 integer
                               b8            - convert to base 8
                                 ị           - index into
                                  “ I|o^Xv_” - literal " I|o^Xv_"
                                             - makes this, without the line feeds:
                                                _____I_____
                                               | | | | | | |
                                               | |o| |o| | |
                                               | | |^| | | |
                                               | |XvXvX| | |
                                               |_|_|_|_|_|_|

<32ị“o^XV“vX”y¢s13µ¹U31=³¤?Y - Main link: n
<32                          - 1 if n is less than 32 else 0
   ị                         - index into
    “o^XV“vX”                - list of strings, ["o^XV","vX"]
             y               - map those characters (o->^ and X->V OR v->X) in string:
              ¢              -    call last link (1) as a nilad
               s13           - split into chunks of length 13
                  µ          - monadic chain separation
                          ?  - ternary if:
                         ¤   -     nilad and links as a nilad
                     31=³    -         31 equals first argument
                   ¹         -     identity (do nothing if true)
                    U        -     upend (reverse each if false)
                           Y - join with line feeds

```

# Answer
> 3 votes
# Ruby, 137 bytes

Face points left on and after the 31st.

```
->n{puts ' _____I_____',(0..4).map{|i|s=[?|]*7*' _'[i/4]
s[5-n/31*2,5]=' | | o| |o |^| VvVvV_|_|_'[i*5,5];s.tr('ovV','^vVoX'[n/32*3,3])}}

```

**Ungolfed in test program**

```
f=->n{
  puts ' _____I_____',                                #Draw top of pumpkin
  (0..4).map{|i|                                      #then 5 more lines
    s=[?|]*7*' _'[i/4]                                #of 7 | separated by space or _ .
    s[5-n/31*2,5]=' | | o| |o |^| VvVvV_|_|_'[i*5,5]  #Add a line of face with 'o' eyes and 'VvVvV' mouth.
    s.tr('ovV','^vVoX'[n/32*3,3])                     #Substitute characters as necessary.
  }
}

f[gets.to_i]

```

# Answer
> 2 votes
# Pyth - 84 bytes

Manual base compression.

```
+dj\Im*5\_2Xjb@_MBsMc5@L"^|_V ve"jC"mËÝ8|0càvll+Ç²Sïë¬Ê"7qQ31"Vve"?>Q31"XXo""Vv^

```

Test Suite.

# Answer
> 2 votes
# PHP, ~~178~~ ~~176~~ 171 bytes

```
$e="| | ";$b=($n=$argv[1]-31)?" |^":"^| ";$c=$n<1?VvVvV:XXXXX;$a=$n<1?$b:" |o";echo" _____I_____\n$e$e$e|\n| |$a|$a$e\n$e|$b$e|\n| |",$n?" |$c":"$c| ","$e\n|_|_|_|_|_|_|";

```

could save 5 bytes with physical linebreaks. Run with `-r`.

# Answer
> 2 votes
## Charcoal, 71 bytes

```
ＮβＡ‹β³²τＡ§o^τεＡ§XVτφＡ§XvτθＦ³«Ｐ↑⁵|_»↑⁵←I←×_⁵‖Ｏ→↙↙←←ε↙←^↖↓ε↓→φθφθφ¿⁼β³¹‖←

```

**Note**: This code does not work in the most recent commit as of posting, because string indexing is broken. It should, however, work in this version from October 25. It also runs successfully on the version currently on Try It Online.

### Explanation

Charcoal is a language designed for ASCII-art. Output is put onto a canvas, which is printed at the end of the program.

**Setup**

Get input and calculate face characters:

```
Ｎβ        Input number into beta
Ａ‹β³²τ    Assign beta<32 to tau for easy reuse
Ａ§o^τε    Assign appropriate eye character (selected via indexing into "o^") to epsilon
Ａ§XVτφ    Assign outside and middle mouth character to phi
Ａ§Xvτθ    Assign other mouth character to theta

```

**Draw the pumpkin**

```
Ｆ³«  »    Do this three times:
Ｐ↑⁵       Draw a 5-character line upward (using | by default); don't move the cursor
|_         Draw that string, rightward

```

After this loop, we have

```
| | |
| | |
| | |
| | |
|_|_|_

```

Next:

```
↑⁵         Draw a 5-character line upward
←I         Draw the stem leftward
←×_⁵       Draw 5 underscores leftward
‖Ｏ→       Reflect the canvas rightward, overlapping in the middle

```

Result:

```
 _____I_____
| | | | | | |
| | | | | | |
| | | | | | |
| | | | | | |
|_|_|_|_|_|_|

```

**Draw the face**

We will draw the face looking rightward and change it later if necessary.

```
↙↙←←ε      Move to the correct spot and draw the right eye (our right, pumpkin's left)
↙←^        Move to the correct spot and draw the nose
↖↓ε        Move to the correct spot and draw the left eye
↓→φθφθφ    Move to the correct spot and draw the mouth with alternating characters

```

Result (for input `31`):

```
 _____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|

```

Reflect if it's Halloween:

```
¿⁼β³¹      If beta equals 31:
‖←         Reflect canvas leftward

```

Final output:

```
 _____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|

```

# Answer
> 1 votes
## JavaScript (ES6), ~~163~~ 125 bytes

```
f=
n=>` _____I_____
3 5 4
30504
3 |^| 4
3121214
|_|_|_|_|_|_|`.replace(/\d/g,c=>(n>31?`oXX`:`^Vv`)[c]||(c-3^n>30?`| |`:`| | |`))
;
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```

Now shamelessly stealing @ETHproduction's trick for positioning the face. Encoding: `0` is an eye, `1` and `2` are teeth, `3` is the left side, `4` is the right side and `5` is the bridge of the nose.

# Answer
> 1 votes
# , 97 bytes

```
é|6i| Y5PÒ_r $.7|rIGÓ /_
3G3f r^jll.kll.5G3f RVvVvVLá
Àé*ñ30|l2GGkld$PñGñ31|l3GÓÞ/o
5GÓãv/XñÍª

```

Try it online!

I'm dissapointed with how long this turned out. It is more convoluted than usual since V can barely handle numbers, a *lot* of bytes come from creating hacky conditionals. I would post a detailed explanation, but it took a long time to come up with, so I might get around to it later. Here is a hexdump:

```
0000000: e97c 3669 7c20 1b59 3550 d25f 7220 242e  .|6i| .Y5P._r $.
0000010: 377c 7249 47d3 202f 5f0a 3347 3366 2072  7|rIG. /_.3G3f r
0000020: 5e6a 6c6c 2e6b 6c6c 2e35 4733 6620 5256  ^jll.kll.5G3f RV
0000030: 7656 7656 1b4c e10a c0e9 2af1 3330 7c6c  vVvV.L....*.30|l
0000040: 3247 1647 6b6c 6424 50f1 47f1 3331 7c6c  2G.Gkld$P.G.31|l
0000050: 3347 d3de 2f6f 0a35 47d3 e376 2f58 f1cd  3G../o.5G..v/X..
0000060: aa                                       .

```

FYI this will run *very* slowly. It will take about 10 seconds. I know why this happens, and I'm looking into fixes.

# Answer
> 1 votes
# Pyth, 76 bytes

```
+dX*11\_5\IjbmX.<.[14d"| "yqQ31<G3?>Q31"XXo""Vv^"c"
|c| |c
|^
|ababa"bt*7"_|

```

Try it online.

Uses no compression. (I tried using some to a version of the face data string, but it ended up the same length.)

# Answer
> 1 votes
# Java 7, 237 bytes

```
String c(int n){char a=n==31?94:n>31?'o':32,b=n<31?'^':32;return(" _____I_____ \n~~~~~~|\n~|"+a+"|"+b+"|"+a+"|"+b+"~|\n~~|"+(n>31?94:a)+"|"+b+"~~|\n~"+(n<31?"~|VvVvV|":n==31?"|VvVvV~|":"|XXXXX~|")+" |\n|_|_|_|_|_|_|").replace("~","| ");}

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(int n){
    char a = n == 31
              ? 94
              : n > 31
                 ? 'o'
                 : 32,
         b = n < 31
              ? '^'
              : 32;
    return (" _____I_____ \n~~~~~~|\n~|"+a+"|"+b+"|"+a+"|"+b+"~|\n~~|"
        +(n > 31
           ? 94
           :a)
        +"|"+b+"~~|\n~"
        +(n < 31
           ? "~|VvVvV|"
           : n == 31
              ? "|VvVvV~|"
              : "|XXXXX~|")
        +" |\n|_|_|_|_|_|_|")
      .replace("~", "| ");
  }

  public static void main(String[] a){
    System.out.println(c(12));
    System.out.println();
    System.out.println(c(31));
    System.out.println();
    System.out.println(c(100));
  }
}

```

**Output:**

```
 _____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|

 _____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|

 _____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|

```

# Answer
> 1 votes
## Groovy Script, ~~273~~ ~~265~~ ~~216~~ ~~202~~ 198 bytes

```
i=args[0]as int
a=i<32?'^| |^':'o| |o'
b=i<32?'VvVvV':'XXXXX'
j=i>30
print" _____I_____\n| | | | | | |\n| |${j?"$a| ":" |$a"}| |\n| | |${j?'^| ':' |^'}| | |\n| |${j?"$b| ":" |$b"}| |\n|_|_|_|_|_|_|"

```

Ungolfed version

```
i = args[0] as int
a = i < 32 ? '^| |^' : 'o| |o'
b = i < 32 ? 'VvVvV' : 'XXXXX'
j = i > 30
print """ _____I_____
| | | | | | |
| |${j ? "$a| " : " |$a"}| |
| | |${j ? '^| ' : ' |^'}| | |
| |${j ? "$b| " : " |$b"}| |
|_|_|_|_|_|_|"""

```

Try it here

### Edit

As Titus mentioned, I can save some size with `i < 32` instead of `i in 1..31`

### Edit 2

Removed all possible spaces around operators... Forgot to do so in the beginning

### Edit 3

Rewrote ternary conditions to use the saved variable, replaced `;` with newlines, removed explicit variable definition

### Edit 4

As Otávio mentioned, I can save another 4 bytes if I switch from `| |${j ? ' |^| | ' : ' | |^| '}| |` to `| | |${j ? '^| ' : ' |^'}| | |`

# Answer
> 1 votes
# C++, ~~222~~ ~~204~~ 194 bytes

-18 bytes thanks to Kevin Cruijssen and -10 bytes for explicit top part

```
using S=std::string;S f(int n){char L[80],o=2*(n>30),i=-1;while(i++<80)L[i]=47<i&i<53?88:i%2?'|':i==20|i==24|i==36?n<32|i>35?94:'o':(i-o)%14?i-o<55?32:95:10;return" _____I_____ "+S(L+o,L+70+o);}

```

Ungolfed

```
#include <string>

using S=std::string;
S f(int n){
 char L[80];
 int o=2*(n>30);
 for (int i=0;i<80;i++){
  L[i]=
   (47<i && i<53) ?
   'X' :
   (
    (i%2) ?
    '|' :
    (
     i==20||i==24||i==36 ?
     (n<32||i>35?'^':'o') :
     ((i-o)%14?(i-o<55?' ':'_'):'\n')
    )
   );
 }
 return " _____I_____ " + S(L+o,L+70+o);
}

```

# Answer
> 1 votes
# PHP, 222 Bytes

```
for($s=" ".str_pad("I",11,_,2)." \n";$i<5;$i++)$s.=str_pad("",13,$i<4?"| ":"|_")."\n";$p=($a=$argv[1])<31||!($a%2)?2:0;$s=substr_replace($s,$a>31?XXXXX:VvVvV,$p+59,5);$s[$p+31]=$s[$p+35]=($a>31?o:"^");$s[$p+47]="^";echo$s;

```

## Output

```
input:29
 _____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|

input:30
 _____I_____
| | | | | | |
| | |^| |^| |
| | | |^| | |
| | |VvVvV| |
|_|_|_|_|_|_|

input:31
 _____I_____
| | | | | | |
| |^| |^| | |
| | |^| | | |
| |VvVvV| | |
|_|_|_|_|_|_|

input:32
 _____I_____
| | | | | | |
| | |o| |o| |
| | | |^| | |
| | |XXXXX| |
|_|_|_|_|_|_|

input:33
 _____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|

input:34
 _____I_____
| | | | | | |
| | |o| |o| |
| | | |^| | |
| | |XXXXX| |
|_|_|_|_|_|_|

input:35
 _____I_____
| | | | | | |
| |o| |o| | |
| | |^| | | |
| |XXXXX| | |
|_|_|_|_|_|_|

```

# Answer
> 0 votes
## Ruby, 168 bytes

```
->i{s=(Zlib.inflate Base64.decode64 "eJxTiAcBTzDJVaOABCG8OCiGycUhyYWVASGYF48EuRTwGhmHZkgckhzMQBKNzIdibEZGgAA2IwFZA1N4").lines;puts i<31?s[0..5]:i<32?s[6..11]:s[12..17]}

```

Probably far from optimal. Requires the `base64` and `zlib` libraries.

Call as a lambda function.

# Answer
> 0 votes
# Python 2, 167 bytes

```
i=input()
b='| |';e='^o'[i>31]+b;print'\n'.join(x[::[1,-1][i>30]]for x in[' _____I_____ ','| '*5+b,b+' |'+e+e,b+' | |^| '+b,b+' |'+['VvVvV','X'*5][i>31]+b,'|_'*6+'|'])

```

# Answer
> -1 votes
## C# 6, 223 215 bytes

`int d=int.Parse(args[0]);var x="| | |\n| |";var s=d<31?" |^| |^| |\n| | | |^"+x+" |VvVvV":(d==31?"^| |^"+x+" |^| "+x+"VvVvV| ":"o| |o"+x+" |^| "+x+"XXXXX| ");Write(" _____I_____\n| | | | "+x+s+"| |\n|_|_|_|_|_|_|");`

Entire program ungolfed:

```
using static System.Console;
namespace Halloween
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int d = int.Parse(args[0]);
            var x = "| | |\n| |";
            var s = d < 31 ? " |^| |^| |\n| | | |^" + x + " |VvVvV"
                           : (d == 31 ? "^| |^" + x + " |^| " + x + "VvVvV| "
                                      : "o| |o" + x + " |^| " + x + "XXXXX| ");
            Write(" _____I_____\n| | | | " + x + s + "| |\n|_|_|_|_|_|_|");
        }
    }
}

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity, integer
---


title: Code Golf Golf Golf

text:
# Question
Title: Code Golf Golf Golf
### Golf Challenge

Given the below ASCII "Green".

```
|          |
|  |>      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |

```

Let `|` Denote a wall
Let `|` Denote half the flag pole
Let `>` Denote the flag on the pole
Let `O` Denote the hole
Let `o` Denote the ball

The dimensions of the "Green" is 10x10. There are ten spaces between the two walls `|`.
There are also ten spaces, empty or not between the top and the bottom of the green.

### Challenge

Input an x and y value or generate two random numbers to "shoot" a golf ball onto the green.
If the x, y generated does not touch the hole or the flag pole/flag output "Try Again!"
If the x, y generated hits the hole output "Hole in One!"
if the x, y generated hits the pole output "Lucky Shot!"
if the x, y generated hits the flag output "Close One!"

After the shot, output the location of the ball on the green with a `o`, replacing any character it hit. Also output the respective saying above.

Examples:

```
//Hole in one example, the O was replaced with a o
Randomed x = 3
Randomed y = 4

"Hole in One!"

|          |
|  |>      |
|  |       |
|  o       |
|          |
|          |
|          |
|          |
|          |
|          |

//Clone example, the top half of the pole was replaced with a o
Randomed x = 3
Randomed y = 2

"Lucky Shot!"

|          |
|  o>      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |

//Lucky Shot example, the > was replaced with a o
Randomed x = 4
Randomed y = 2

"Close One!"

|          |
|  |o      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |

//Try Again example, the <space> was replaced with a o
Randomed x = 5
Randomed y = 1

"Try Again!"

|     o    |
|  |>      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |

```

Have fun and good luck and as this is the shortest code wins!

# Answer
# JavaScript (ES6) ~~210~~ ~~208~~ ~~193~~ 184 bytes

```
f=(a,b)=>((s=[...(`
|          |`).repeat(10)])[17]=s[30]='|',s[18]='>',s[43]=0,s[a+=1+b*13]='o',(a-17&&a-30?a-18?a-43?'Try Again!':'Hole in One!':'Close One!':'Lucky Shot!')+s.join``)

```
* -9 bytes thanx to Hedi

# Demo
> 10 votes

# Answer
# Jelly, 78 bytes

```
ċÐ€®Ḍị“ȷþḄ7Ẋ“þẹƊ⁴ḳL&Ṛ“qĠṂ®““ÞzḊṁġ“»;”!Ṅṛ
⁶ẋ“€¡®µC‘ż“|>|O”©F”o⁸¦Ç
ṭḌ‘Çs⁵j@€⁾||Y

```

Play a **Skill-Game** or a **Crap-Shoot** at **TryItOnline!**

(Crap-shoot cost more bytes).

### How?

```
ṭḌ‘Çs⁵j@€⁾||Y - Main link: x, y (0-based)
ṭ             - tack            -> [y, x]
 Ḍ            - cast to decimal -> 10y+x
  ‘           - increment       -> 10y+x+1
   Ç          - call last link (1) as a monad
    s⁵        - split into chunks of size 10 (rows of green display)
         ⁾||  - literal ['|','|']
      j@€     - join €ach  with reversed @rguments (make the border)
            Y - join with line feeds
              - implicit print

⁶ẋ“€¡®µC‘ż“|>|O”©F”o⁸¦Ç - Link 1, Make green & place the ball: decimal 1-based location
  “€¡®µC‘               - code page indexes -> [12,0,8,9,67]
⁶                       - literal ' '
 ẋ                      - repeat (vectorises)
         ż              - zip with
          “|>|O”        - literal ['|','>','|','O']
                ©       -     and place the flag parts into the register
                 F      - flatten list
                     ¦  - apply to index at
                    ⁸   - input value
                  ”o    - literal 'o'
                      Ç - call the last link (2) as a monad

ċÐ€®Ḍị“ȷþḄ7Ẋ“þẹƊ⁴ḳL&Ṛ“qĠṂ®““ÞzḊṁġ“»;”!Ṅṛ - Link 2, Print message: green with ball
   ®                                     - read register (the flag parts)     | > | O
ċÐ€                                      - count occurrences e.g. HoleInOne: [2,1,2,0]
    Ḍ                                    - cast to decimal                  ->2120
     ị                                   - index into (1-based & modular) 2120 % 6 = 2
      “ȷþḄ7Ẋ“þẹƊ⁴ḳL&Ṛ“qĠṂ®““ÞzḊṁġ“»      - compressed list of (6) strings:
              ...["Lucky Shot","Hole in One","Try Again","","Close One",""]
                                   ;     - concatenate with
                                    ”!   - literal '!'
                                      Ṅ  - print with linefeed
                                       ṛ - yield right argument (the green)

```
> 8 votes

# Answer
# Python 2, ~~290~~ ~~264~~ ~~262~~ ~~252~~ ~~248~~ 245 bytes

It's not pretty and it's not short but I'm tired and its the ~~first~~ only Python answer. Enter shot in x,y format.

**Edit**

Golfed off 26 by redefining the way the list is built. Still no luck with the long if statement though.

-2 by replacing the long if with a dictionary and a shorter if.

-10 with thanks to @Noodle9 - I'd missed that one :)

-4 - thanks again :)

Another 3 off. Thanks.

```
x,y=input();a=[' ']*120;a[15]=a[27]='|';a[16],a[39],b='>','0',x+y*12
a[b],k='o',"Lucky Shot!";l={16:"Close One!",15:k,27:k,39:"Hole in One!"}
print l[b]if b in l else"Try Again!"
for z in range(10):c=z*12;a[c]=a[c+11]='|';print''.join(a[c:c+12])

```

For anyone who is interested in the logic, ungolfed with comments (1316 bytes but still easily fits on a 3.5" disk if anyone remembers them):

```
x,y=input()                                     #Get the input as a tuple
a=[' ']*120                                     #Create a great big list of spaces for the whole green
a[15]=a[27]='|'                                 #Put the flag pole in place
a[16]='>'                                       #Add the flag
a[39]='0'                                       #Add the hole
b=x+y*12                                        #Get the absolute position in the list of the input tuple
a[b]='o'                                        #Place the ball on the green
k="Lucky Shot!"                                 #Set a variable for k because it is long and we're going to use it twice
l={16:"Close One!",15:k,27:k,39:"Hole in One!"} #Create a dictionary of the comments (using k)
print l[b]if b in l else"Try Again!"            #If the absolute index is in the dict then print it otherwise print the default
for z in range(10):                             #Loop through the length of the green
    c=z*12                                      #Set a variable for the start point of each line
    a[c]=a[c+11]='|'                            #Add the left and right walls
    print''.join(a[c:c+12])                     #Print each line in turn. Because this is in a for loop then Python will deal with newlines

```

Definitely the first time for me that a dictionary has been the best data format in a golf challenge.
> 7 votes

# Answer
# C, 236 bytes

```
n,m;char*a[]={"Try Again!","Hole in One!","Lucky Shot!","Close One!"};f(x,y){n=130;m=142-y*13-x;puts(a[(m==87)+2*(m==113|m==100)+3*(m==112)]);while(n--)putchar(m==n?111:n%13?n%13==1|n%13==12|n==113|n==100?124:n==112?62:n==87?79:32:10);}

```

Ungolfed:

```
n,m;
char*a[]={"Try Again!","Hole in One!","Lucky Shot!","Close One!"};
f(x,y){
 n=130;
 m=142-y*13-x;
 puts(a[(m==87) + 2*(m==113|m==100) + 3*(m==112)]);
 while(n--)
  putchar(m==n?111:n%13?n%13==1|n%13==12|n==113|n==100?124:n==112?62:n==87?79:32:10);
}

```
> 5 votes

# Answer
# Scala, 238 bytes

```
(x:Int,y:Int)=>{val r="<          |\n"
('"'+(if(x==2&y==3)"Hole in One!"else
if(x==2&(y==1|y==2))"Lucky Shot!"else
if(x==3&y==1)"Close One!"else
"Try again!")+"'",(r+"|  |>      |\n|  |       |\n|  O       |\n"+r*6)updated(1+x+13*y,'o'))}

```

Using zero-indexing.

This is way too readable :(

Explanation:

```
(x:Int,y:Int)=>{                                      //define an anonymous function
  val r="|          |\n"                                //a shortcut for an empty row
  (                                                     //return a tuple of
    '"'+                                                  //a double quote
    (if(x==2&y==3)"Hole in One!"                          //plus the correct string
    else if(x==2&(y==1|y==2))"Lucky Shot!"
    else if(x==3&y==1)"Close One!"
    else "Try again!"
    )+"'"                                                 //and another quote
  ,                                                     //and
    (r+"|  |>      |\n|  |       |\n|  O       |\n"+r*6) //the field
    updated(1+x+13*y,'o')                                //with the (1+x+13*y)th char replaced with a ball
  )
}

```

I've used the formula `1+x+13*y` to calculate the correct index, since each row is 13 chars long (2 borders, a newline and 10 spaces) plus an offset of one because (0,0) should be the second char.
> 3 votes

# Answer
# Perl, ~~225~~ 209 bytes

```
$_="|".$"x10 ."|
";$_.=sprintf("|  %-8s|
"x3,"|>","|",O).$_ x6;$d="Try Again!";($x,$y)=@ARGV;say$x==3?$y~~[2,3]?"Lucky Shot!":$y==4?"Hole in One!":$d:$x==4&&$y==2?"Close One!":$d;substr($_,$y*13-13+$x,1)=o;say

```

The two literal newlines each save one byte. Pretty standard. Prints the declaration, then the game board.
> 3 votes

# Answer
## Charcoal, 99 bytes

```
ＮαＮβ× ⁵↑¹⁰‖Ｃ←Ｊ⁴¦²←>↓²OＭ⁴↖Ｐ⁺⎇∧⁼α³⁼β⁴Hole in One⎇∧⁼α³⁼¹÷β²Lucky Shot⎇∧⁼α⁴⁼β²Close One¦Try Again¦!Ｊαβo

```

Takes 1-based input, space-separated, on stdin. Most of the code is for printing (one of) the four messages. Try it online!

Note: Charcoal is still a work in progress. This code works as of the current commit. If it stops working in the future (in particular, if the TIO link doesn't work as expected), ping me and I'll try to add a non-competing updated version that works.

### Explanation

```
ＮαＮβ       Read two inputs as numbers into variables α and β

               Construct the green and flag:
× ⁵          Print to canvas 5 spaces
↑¹⁰          Print 10 | characters going up
‖Ｃ←         Reflect and copy leftward
             At this point, borders of green are complete; cursor is above left wall
Ｊ⁴¦²        Jump 4 units right and 2 down
←>           Print the flag, going leftward
↓²           Print the pin (2 | characters), going downward
O            Print the hole
             The last print was rightward by default, which means we're now at (4,4)
Ｍ⁴↖         Move 4 units up and left; cursor is above left wall again

               Add the proper message:
⎇∧⁼α³⁼β⁴    If α is 3 and β is 4 (in the hole):
Hole in One
⎇∧⁼α³⁼¹÷β²  Else if α is 3 and β is 2 or 3 (hit the pin):
Lucky Shot
⎇∧⁼α⁴⁼β²    Else if α is 4 and β is 2 (hit the flag):
Close One
             Else:
¦Try Again
⁺...¦!       Concatenate a ! to the string
Ｐ           Print it without changing the cursor position

               Overwrite the appropriate spot with o:
Ｊαβ         Jump α units right and β units down
o            Print o

```
> 3 votes

# Answer
# Brain-Flak, 1466 ~~1938~~ bytes

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

```

Try it online!

---

Did I win?
> 3 votes

# Answer
# Dyalog APL, 147 (or 127) bytes

Takes (y,x) as argument.

```
{G←10 10⍴''
G[⍳4;3]←' ||O'
G[2;4]←'>'
G[⊃⍵;⊃⌽⍵]←'o'               ⍝ G[y;x]←
⎕←'|',G,'|'                 ⍝ Print G with sides
4 3≡⍵:'Hole in One!'        ⍝ If (y,x) ≡ (4,3)
(⊂⍵)∊2 3∘.,3:'Lucky Shot!'  ⍝ If (y,x) ∊ {(2,3), (2,3)}
2 4≡⍵:'Close One!'
'Try Again!'}               ⍝ Else

```

From version 16.0, we can almost halve the byte-count with the new `@` operator;

`@` puts the left operand into the right-operand positions in the right argument: `NewChars @ Positions ⊢ Data`

```
{⎕←'|','|',⍨' ||O>o'@((2 4)⍵,⍨3,⍨¨⍳4)⊢10 10⍴''
4 3≡⍵:'Hole in One!'
(⊂⍵)∊2 3∘.,3:'Lucky Shot!'
2 4≡⍵:'Close One!'
'Try Again!'}

```

Slightly modified code to make permissible in TryAPL:

Hole in One, Lucky Shot 1, Lucky Shot 2, Close One, Random
> 2 votes

# Answer
# TI-Basic, 183 bytes

```
Input X
Input Y
X+1➡X
ClrHome
For(I,1,10
Output(I,1,"|
Output(I,12,"|
End
Output(2,4,"|>
Output(3,4,"|
Output(4,4,"O
Output(Y,X,"o
13
Output(1,Ans,"TRY AGAIN!
If X=4 and Y=4
Output(1,Ans,"HOLE IN ONE!
If X=5 and Y=2
Output(1,Ans,"CLOSE ONE!
If Y=2 or Y=3 and X=4
Output(1,Ans,"LUCKY SHOT!

```

Thank goodness TI-Basic uses tokens.

The `|` cannot normally be typed, but it is in the character set.

Please let me know if the result of the shot absolutely has to be lowercase.

I will add a screenshot of an example program result later.
> 2 votes

# Answer
# Groovy - 235 bytes

My first attempt - A groovy closure accepting 2 integers from 0 to 9 as the X and Y coordinates for the shot.

```
{j,k->j++;c='';b='|';f='>';h='O';s=' ';v=[2:b,3:b,4:h];(0..9).each{y->l=(b+s*10+'|\n').chars;l[3]=v[y]?:s;l[4]=y==2?f:s;if(k==y){m=[(s):'Try Again!',(b):'Lucky Shot!',(f):'Close One!',(h):'Hole In One!'][""+l[j]];l[j]='o'};c+=l};c+=m}
```
> 2 votes

# Answer
# Turtled, 164 bytes

Once again, showcasing Turtlèd's balance between golfiness and verbosity for the simplest things (like incrementing a number), Turtlèd beats all but the golfing langs.

```
6;11[*'|:'|>;<u]'|rrr'O8:'|u'|>;'|ddd'|l'|uuu<"|>":l'|u'|>11;'|?<:?;( #Try Again!#)(>#Close One!#)(|#Lucky Shot!#)(O#Hole in One!#)'o[|r][ u]dl[|l][ u]u@"-,r["+.r_]

```

### Try it online

Note that it is half zero indexed and half one indexed; x is one indexed, y is zero indexed; 3,3 is a hole in one
> 1 votes

# Answer
# R, ~~230~~ 226 bytes

```
M=matrix("|",10,10);M[2:9,]=" ";M[34]="0";M[4,2:3]="f";M[15]=">";function(x,y){m=switch(M[y,x],">"="Close One","f"="Lucky Shot","0"="Hole In One","Try again");M[y,x]="o";cat(m,"!\n",sep="");cat(gsub("f","|",M),sep="",fill=10)}

```

Thanks to @billywob for -2 bytes, noticing `M[a,b]` is equivalent to `M[c]` in a couple of cases.

Annoyingly, the two `cat` calls (!) can't be con`cat`enated into one, since the `fill` argument messes up the message. Argh!
> 1 votes

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


title: Minify Brainfuck

text:
# Question
Title: Minify Brainfuck
Your challenge is to minify Brainfuck code, according to these rules:

* Remove anything that is not one of `+-><[].,`.
* For any group of consecutive `+` or `-` characters, if the amount of `+`s and `-`s is the same, remove them.
* Do the same as above, but with `>` and `<`.
* Remove sequences of the `+-><` characters if they do nothing. For example, you should remove `+>-<->+<`. (This may be the trickiest and hardest one to implement.) Make sure you don't get any false positives, like `+>-<+>-<`, which should not be removed.

---

Test cases:

Input

```
++++++[->++++++<]>.   prints a $
[-]<                  resets tape
>,[>,]<[.<]           reverses NUL terminated input string
++-->><<              does nothing

```

Output

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

```

Input

```
Should disappear: ++>>+<+++<->-->-<<->-<
Should disappear: +++>-<--->+<
Should stay: +++>-<+>---<

```

Output

```
+++>-<+>---<

```

---

You may accept input and output however you would like - stdin/stdout, a function, etc., but input may not be hardcoded.

This is , so the shortest code in character count will win.

# Answer
> 12 votes
## REBEL - 104

```
_/^_$/$</([^][<>.,+-]|\+-|-\+|<>|><)//((?<X>(<|>))+[+-]+(?!\2)(?<-X><|>)+(?(X)(?!)))([+-]+)/$3$1/.+/$>$&

```

## Usage:

Input: Reads one line from stdin.

Output: Prints one line to stdout.

## Anomalies\*:

* Entering `_` causes another line to be read and used, rather than outputting nothing.
* The second test outputs `++++>----<` instead of `+++>-<+>---<`. But that's OK, right? ;)
* `>-<+` etc. are replaced with `+>-<` etc.

## Spoiler:

> Implementing anomaly #3 makes things quite trivial.

<sub>*** It's not a bug, it's a feature!**</sub>

# Answer
> 47 votes
## Brainfuck, 579 bytes

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

```

With formatting and some comments:

```
,
[
  <<+>> >>+<<
  [
    [<+> >+<-]
    ++++++[>-------<-]
    >-
    [
      not plus
      -
      [
        not comma
        -
        [
          not minus
          -
          [
            not period
            --------------
            [
              not less than
              --
              [
                not greater than
                <+++++[>------<-]>+
                [
                  not open bracket
                  --
                  [
                    not close bracket
                    <<[-]>>-
                  ]
                ]
                <
              ]
              >
              [
                greater than
                >>-<<
                <<<[-]<[<]<<<[<]
                >>>>>>>>[<]
                <-[+>]
                +[->+]
                >>>>+>[<-]
                <[>+<-<]
                >
              ]
              <
            ]
            >
            [
              less than
              <<<[-]-[<]
              >>>> >>>>>>>[<]
              <<<<<<[<]
              <-[+>]
              +[-<+]
              <<<+<[>-<<<]
              >[-<+<]
            ]
          ]
          <
        ]
        >
        [
          minus
          +>[-<]
          <[<<]
          <[-]>>
        ]
      ]
      <
    ]
    +>
    [
      plus
      -[<-]
      <[>+>+<<-<]
      <[-]>+>
    ]
    <<
    [
      comma or period or bracket
      >-
    ]
    >[,>]
    <
  ]
  comma or period or bracket or eof
  <+<
  [
    start and end same cell
    >
  ]
  >
  [
    >>>
    [
      <<<<[-<]<<<
    ]
    >>>+>>>>
    [
      start right of end
      <<<<->>>>
      [>>>[-<]>>>>]
    ]
  ]
  >
  [
    <<<
    [
      <+[-->>]
    ]
    >[-[.[-]]]
    >[<]
    >
    [
      <<++++++[>+++++++<-]>+>>
      [<<.>>-]
      <<++>-[<.>-]
      +++[<+++++>-]
      +<<<<< <+>
      [
        <<
        [
          go left
          >->>>>>.
          [[-]<<<<]
          <<<+>>>
        ]
        >
        [
          toggle left right
          ->->>>>[-]
        ]
      ]
      <
      [
        toggle right left
        ->+[>>>>>]>>[<]
        <<<<<<<<
        [
          [-]<
        ]
        >
        [
          go right
          ++.[-]
          >>>>>>>
        ]
        <
      ]
    ]
    >>
  ]
  <[>>>>>>>]
  +[-<<<<<[-]<<]
  ,
]

```

This uses the same approach as Keith Randall's solution, minifying all contiguous sequences of `+-<>` optimally by simulation. For example, `+++>-<+>---<` becomes `++++>----<` and `>+<+<<+>+<->>>>` becomes `+<+>>+>`.

Try it online. (If a simulated cell's absolute value gets close to 256, there will be overflow issues.)

The overall structure is

```
while not EOF:
  while not EOF and next char not in ",.[]":
    process char
  print minified sequence (followed by the char in ",.[]" if applicable)

```

The tape is divided into 7-cell nodes; at the beginning of the inner loop, the memory layout is

`0 s 0 c 0 a b`

where `s` is a boolean flag for start cell, `c` is the current character, `a` is the negative part of the simulated cell value (plus one), and `b` is the positive part of the simulated cell value.

When the minified sequence is being printed, the memory layout is

`d n e 0 0 a b`

where `d` is a boolean flag for direction, `a` and `b` are as before (but become one/zero when printed), and `n` and `e` are only nonzero for the end node; `n` is related to how many times the node has been seen, and `e` is the value of the char that halted the inner loop (plus one).

Originally I considered keeping track of more information per node: leftmost and rightmost node as boolean flags, and node's position in relation to the start and end nodes. But we can avoid that by looking at neighboring cells when needed, and by doing left and right scans in order to find the start node.

When printing the minified sequence and deciding how to move the simulated pointer, we can take a general approach: start by moving away from the end node (in an arbitrary direction if start and end nodes are the same), turn around at leftmost and rightmost nodes, and stop based on the number of times the end node has been seen: 3 times if the start and end nodes are the same, otherwise 2.

# Answer
> 9 votes
## Python, 404 chars

This code does a perfect optimization of all subsequences of `+-<>`. A bit more than you asked for, but there you go.

```
M=lambda n:'+'*n+'-'*-n
def S(b):
 s=p=0;t=[0];G,L='><'
 for c in b:
  if'+'==c:t[p]+=1
  if'-'==c:t[p]-=1
  if G==c:p+=1;t+=[0]
  if L==c:s+=1;t=[0]+t
 if p<s:k=len(t)-1;t,p,s,G,L=t[::-1],k-p,k-s,L,G
 r=[i for i,n in enumerate(t)if n]+[s,p];a,b=min(r),max(r);return(s-a)*L+''.join(M(n)+G for n in t[a:b])+M(t[b])+(b-p)*L
s=b=''
for c in raw_input():
 if c in'[].,':s+=S(b)+c;b=''
 else:b+=c
print s+S(b)

```

It works by simulating the `+-<>` operations on the tape `t`. `s` is the starting position on the tape and `p` is the current position. After simulation, it figures out the extent `[a,b]` that needs to be operated on and does all the +/- in one optimal pass.

# Answer
> 1 votes
## CoffeeScript - 403 *397*

```
i=prompt().replace /[^\]\[,.+-><]/g,''
x=(c)->
 t={};p=n=0
 for d in c
  t[p]?=0;switch d
   when'+'then n=1;t[p]++;when'-'then n=1;t[p]--;when'<'then p--;when'>'then p++
 (n=0if v!=0)for k,v of t;n
s=e=0;((e++;(i=(i.substr 0,s)+i.substr e;e=s=0)if x (i.substr s,e-s).split "")while(i[e]||0)!in['[',']',0];e=++s)while s<=i.length
r=/(\+-|-\+|<>|><|^[<>]$)/g
i=i.replace r,'' while r.test i
alert i

```

Demo (please forgive the use of bit.ly here, the whole URL would break the markdown)

Uncompressed version (w/ debug code):

```
console.clear()
input = """Should disappear: ++>>+<+++<->-->-<<->-<
Should disappear: +++>-<--->+<
Should stay: +++>-<+>---<"""

input = input.replace /[^\]\[,.+-><]/g, ''
console.log input

execute = (code) ->
  stack = {}
  item = 0
  console.log code
  nop = false
  for char in code
    switch char
      when '+' then nop = true; stack[item]?=0;stack[item]++
      when '-' then nop = true; stack[item]?=0;stack[item]--
      when '<' then item--
      when '>' then item++
  console.debug stack
  (nop = false if v != 0) for k,v of stack
  nop
start = 0
end = 0

while start <= input.length
 while input.charAt(end) not in [ '[', ']', '' ]
  end++
  if execute (input.substring start, end).split("")
    input = (input.substring 0, start) + input.substring end
    end = start = 0
    console.log input
 end = ++start
input = input.replace /(\+-|-\+|<>|><|^(<|>)$)/g, '' while /(\+-|-\+|<>|><)/.test input
console.log 'Result: ' + input

```

---
Tags: code-golf, brainfuck
---