# Question
Title: Write a program to print the sum of the ascii codes of the program
Your task is to write a program to print the sum of the ASCII codes of the characters of the program itself. You are not allowed to open any file (Any input such as command line arguments, standard input or files is prohibited).

The program that prints the lowest number (i.e. has the lowest sum of ASCII codes) wins.

Here is an example (not the shortest) of such a program written in C:

```
#include <stdio.h>
int main(){
printf("4950");/*i*/
return 0;
}

```

(no new line after `}`)

# Answer
> 12 votes
## wc, prints 0

Someone said "cat-like languages", so...

An empty file:

Execute with `wc -c file.wc`. At 0 bytes, I think this is the winner in the 'not really a programming language' category.

Also

## cat, prints 80 (base 13)

```
80

```

No terminating newline, the number 8013 is equivalent to 104 in decimal. You can go shorter with 6017 (102 dec), but I figured "base 13" would be worth more geek points.

EDIT: New `wc` example, this one can be run as a program.

```
#!/usr/bin/wc
ÿÿzw17

```

(As encoded in Latin-1 - the ÿ is a byte with value 255)

Sum of bytes is 2223, output is:

```
  2  2 23 ./w

```

# Answer
> 14 votes
## PHP, m4, and other cat-like languages: 150

```
150

```

Found this solution using a simple Haskell program to brute-force it:

```
f :: String -> Bool
f s = (read s :: Int) == (sum . map fromEnum) s

main = mapM_ print [filter f $ sequence $ replicate n ['0'..'9'] | n <- [1..10]]

```

# Answer
> 12 votes
## Brainf\*ck, 255

```
-.¤

```

This will not print the number 255, but rather the 255th ASCII character.

This might be considered cheating because the BF compiler skips over the `¤`.

# Answer
> 9 votes
## Javascript, prints ~~9432~~ 6902

```
(function a(){b="("+a+")()";c=0;for(i=0;i<b.length;i++){c+=b.charCodeAt(i-0)}alert(c)})()

```

This is the first quine solution so far, unless I am not understanding the Haskell one correctly.

# Answer
> 7 votes
## PowerShell

```
((310))

```

prints 310.

# Answer
> 6 votes
## Perl, 500

```
say     500

```

There are two tabs between `say` and `500`. :)

(Run as a one-liner with `perl -E`, as far as I can tell this is within the rules)

# Answer
> 5 votes
## Ruby, prints 380

```
p (380)

```

No trailing newline after the closing parenthesis.

# Answer
> 5 votes
## PowerShell

```
(230)

```

prints 230, obviously.

# Answer
> 5 votes
## PowerShell

```
-(-320)

```

prints 320.

# Answer
> 5 votes
## J, 150

```
?!6

```

With the caveat that it will be correct only 1/720th of the time.

# Answer
> 4 votes
## Python, prints 781

```
print  781

```

Two spaces.

# Answer
> 4 votes
# Element, 220

This is a language of my own creation, and it is documented on my answer to another question here.

```
220`!

```

Here is a walkthrough of how it works: The `220` pushes that number onto the stack. Then the ``` outputs the top element of the stack. The `!` then performs a logical NOT on the control stack (a separate stack), setting it to 1.

# Answer
> 4 votes
## INTERCAL, 1572

I can't believe no one's done INTERCAL yet!

```
DOREADOUT#1572

DOGIVEUP

```

(Includes terminating newline.) This program prints out MDLXXII.

# Answer
> 2 votes
# PHP, prints 4440

```
<?php
for($x=0;$x<15000;$x++)if($x==4440){printf($x);exit;}

```

# Answer
> 2 votes
## PowerShell, prints 3902

```
&{[char[]]$myinvocation.Line|%{$s+=+$_};$s}

```

Looks into the line currently run and sums the code point values.

# Answer
> 2 votes
## C, 1700

Strange - nobody posted a C solution yet (excluding the example in the question).

```
main(R){puts("1700");}

```

No newline at the end.

# Answer
> 2 votes
## J, 198

```
33*6

```

and

```
6*33

```

Found it by brute force. In J there are no 1 or 2 char solutions, and the only 3-char solution is `150`. Barring any bugs in my search, there are no other 4-char solutions, either.

---

From the #jsoftware IRC channel, we also had `<.%:10!20` at 429 and a self-counting quine `+/a.i.2#(,{:)'+/a.i.2#(,{:)'''` at 1706.

# Answer
> 2 votes
# naz, score ~~777~~ 333

```
3a
3o

```

I think this is allowed.

The newline is normalized to `\r\n` by the naz interpreter at runtime, a sequence which contributes **23** to the overall score.

**Explanation**

```
3a # Add 3 to the register
3o # Output 3 times

```

The previous solution:

```
7a2o1m1o1a

```

# Answer
> 1 votes
## Perl, prints 690

```
die 690 . $/

```

Or, if we can post one-liners (`perl -E`)

```
say(570)

```

Prints 570.

(No trailing newlines)

# Answer
> 1 votes
## JavaScript, ~~1750 900 860~~ 790

`alert(790)`

(Carriage return (CR, `\r` or `\x0D`) after or before the program)

These programs are found by brute-forcing.

Bigger values:

```
alert(860)%0
alert(900)&&6
document.write(1750)

```

# Answer
> 1 votes
# Java -128

I know reading stdin isn't allowed but I wanted to provide an example of how I calculated my score.

My code sums the ASCII count of itself passed on stdin and prints out -128

```
class P{public static void main(String[]z)throws Exception{byte v=0;int b=0;while((b=System.in.read())!=-1){v+=(byte)b;}System.out.println(v);}}

```

No trailing new line

# Answer
> 1 votes
## Ruby, prints 300

```
p   300

```

There is a space and a tab between the `p` and the `300`. No trailing newline.

# Answer
> 1 votes
## Batch files, 500

```
ECHO  500

```

As well, notice the two spaces between "ECHO" (uppercase on purpose) and "500".

# Answer
> 1 votes
# K (~~923 796 795 746~~ 513)

I'm not sure if this falls afoul of the rules or not. It doesn't use stdin, it opens itself as a vector of bytes and sums.

```
+/1:.z.f

```

Usage:

```
q scriptname.k

```

edit 2012.05.08 - no need to hsym the file handle 2012.05.09 - saved 1 point by converting to byte instead of int

2012.05.17 - Can save a load of points by reading file as bytestream rather than text:

# Answer
> 1 votes
# Lenguage, 4 bytes, prints 0

Source code consists of 4 null bytes. Therefore, it should output (0+0+0+0)=0.

# Answer
> 0 votes
### bc 1160

invoked with echo and blanks, the whole String, including 7 blanks, `echo 1160 | bc` has a bytesum of 1160.

```
echo 1160    |  bc

```

150 works for bc too:

```
echo "150" > 150
bc -q 150
150

```

# Answer
> 0 votes
## D, 9752

this one actually calculates it similar to my quine

```
enum c=q{import std.stdio;void main(){int s;foreach(d;"enum c=q{"~c~"};mixin(c);")s+=d;write(s);}};mixin(c);

```

# Answer
> 0 votes
## Whitespace, 369

This 20-character program prints the number 369, which is the sum of the ascii values of its characters (which are Tab,Space,Linefeed characters, here symbolized by T,S,L, respectively):

```
SSSTSTTTSSSTLTLSTLLL

```

(369 = 7\*9 + 8\*32 + 5\*10, there being 7 Tabs, 8 Spaces, and 5 Linefeeds.)

# Answer
> 0 votes
# Haskell, 7518

A small modification of my quine:

```
main=print.sum.map fromEnum$q++show q;q="main=print.sum.map fromEnum$q++show q;q="

```

# Answer
> 0 votes
## Brainf\*ck, 253 (or 252)

Slight improvement on Peter Olson's solution:

```
---.H

```

Provided non-printables are allowed, it can be improved further by adding a `-` and replacing `H` by ASCII code 26.

# Answer
> 0 votes
## Scala, 1090 bytes

```
println (1090)

```

# Answer
> 0 votes
## Python, 5440

Highest score wins, right?

```
import sys
print sum(ord(i)for i in open(sys.argv[0]).read())

```

I just thought I'd post it anyway b/c it's a halfway quine solution.

# Answer
> 0 votes
# Clojure - 8008

There's only a handful of quines so far, and clojure's not represented, so I figured I'd give it a go:

```
(let[s"(let[s%s](apply +(map int(format s(pr-str s)))))"](apply +(map int(format s(pr-str s)))))

```

# Answer
> 0 votes
# 05AB1E, 5 bytes (300)

```
C25LO

```

Try it online!

# Answer
> 0 votes
# , score 198

```
6*33

```

Try it online!

TIO link includes the code used to find this solution, which is the only 1+2 digit solution possible using the "`*`" operator.
Of, course, after finding this, I searched all the other answers for the string "`6*33`", which revealed that AlliedEnvy discovered the same solution in J 6 years ago...

# Answer
> 0 votes
# Stax, score 354

```
|?|+

```

Run and debug it

`|?` returns the program's source. `|+` sums it.

# Answer
> 0 votes
# Zsh, 6 bytes, score 333

```
<<<333

```

`<` = 60, `3` = 51, so it adds up to a nice expression.

---
Tags: code-challenge, self-referential
---


title: Will it float?

text:
# Question
Title: Will it float?
# The challenge

Given a 2d string representing the bottom of a boat as an input, you must determine whether or not the boat will float. This 2D string can be in whatever format is most convenient. (String with newlines, list of string, list of list of chars, etc.) Print a truthy value if it will float, and a falsey value if it will sink.

A boat will tip over if the bottom has an inconsistent density, so every character of must be the same. Also, if a boat has large holes in it, represented by spaces, it will sink, so your boat must have no holes with an area greater than 4. Here is an example:

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

```

This boat is valid because the largest hole in it has an area of 4. This boat:

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

```

is invalid because it has a hole with an area of 7. You can safely assume that the outside of every input will be a solid rectangle with no holes. Here are some more tests:

```
$$$$$$$$
***$$$$$
***$$$$$
***$$$$$
$$$$$$$$
Invalid density. Sink.

%%%%%%%%
%    % %
%%%%%  %
%    % %
%%%%%%%%
None of the holes are larger than 4. Float.

OOOOOOOO
OOOOOOO
OOOOOOOO
OOOOOOOO
OOOOOOOO
The outside border is not solid. Undefined.

&&&&&&&&&&&&&
& & & & & & &
&& & & & & &&
& & & & & & &
&& & & & & &&
& & & & & & &
&&&&&&&&&&&&&
Although I would not be comfortable riding in this boat myself,
none of the holes are larger than 4. It floats.

@@@@@
@   @
@   @
@   @
@@@@@
It sinks.

```

# Rules

* IO can be in any reasonable format.
* Standard loopholes apply.
* Shortest answer in bytes wins.
* The given string will entirely consist of printable ASCII.

# Answer
> 3 votes
# Matlab, 106 bytes

```
s=input('');im=~(s-32);c=bwconncomp(im,4);disp(~nnz(cellfun(@nnz,c.PixelIdxList)>3)&nnz(unique(s(~im)))<2)

```

The input is a matrix of characters, e.g. for the first test case:

```
`['$$$$$$$$';'***$$$$$';'***$$$$$';'***$$$$$';'$$$$$$$$']`

```

Explanation:

```
s=input('');           %read input
im=~(s-32);            %convert input to bw image (space = black)
c=bwconncomp(im,4);    %calculate the connected components (4 connectivity)

disp(
     ~nnz(cellfun(@nnz,c.PixelIdxList)>3) %find out whether we have components that have more at least 4 pixels
     &nnz(unique(s(~im)))<2)              %find out if we have more than 1 non-space character

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 76 bytes

```
{(1=≢∪' '~⍨∊⍵)∧×/5>a/⍨×a←∊g↓⍉↑(g←{⊃,/{×⊃⍵:+/⍵⋄⍵}¨⍵⊂⍨1,2{≠/0=⊃¨⍺⍵}/⍵}¨)' '=⍵}

```

Try it online!

Accepts input as a list of strings.

1 for floating, and 0 for sinking.

## Explanation

```
{(1=≢∪' '~⍨∊⍵)∧×/5>a/⍨×a←∊g↓⍉↑(g←{⊃,/{×⊃⍵:+/⍵⋄⍵}¨⍵⊂⍨1,2{≠/0=⊃¨⍺⍵}/⍵}¨)' '=⍵}
                                                                      ' '=⍵ boolean array for spaces
                              (g←{⊃,/{×⊃⍵:+/⍵⋄⍵}¨⍵⊂⍨1,2{≠/0=⊃¨⍺⍵}/⍵}¨)       apply the following function g to each row:
                                                    1,2{≠/0=⊃¨⍺⍵}/⍵         get the start of each group of zeroes/nonzero values
                                                 ⍵⊂⍨                        cut the list according to that
                                     {×⊃⍵:+/⍵⋄⍵}¨                           sum each nonzero array
                                  ⊃,/                                       join all of that together
                         g↓⍉↑                                               apply g again on the transpose
                  a/⍨×a←∊                                                   flatten and remove zeroes
              ×/5>                                                          are all sums ≤ 4?
             ∧                                                              and
     ' '~⍨∊⍵                                                                the boat with spaces removed
    ∪                                                                       uniquified
 1=≢                                                                        has only 1 element?

```

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


title: The Imperial Ruler

text:
# Question
Title: The Imperial Ruler
Given a ruler length in inches and fractions of an inch, and a granularity in fractions of an inch, output the values of all marks on the ruler, starting from 0, in ascending order.

Input ruler length will be a mixed fraction (integer and proper fraction)

Input granularity will be a proper fraction in the form `1/(2ⁿ)`, where `1 ≤ n ≤ 6`.

Output numbers will all be expressed similarly to the input. For values where the number of inches is a whole number, no fractional part will be expressed. For values where the number of inches is `0 < n < 1`, only the fractional part will be expressed.

If the input granularity is not fine enough to represent the ruler length, then the final number will be the closest representable number below the ruler length.

## Examples

Input `1` `1/2` would output:

```
0
1/2
1

```

Input `2 3/4` `1/8` would output:

```
0
1/8
1/4
3/8
1/2
5/8
3/4
7/8
1
1 1/8
1 1/4
1 3/8
1 1/2
1 5/8
1 3/4
1 7/8
2
2 1/8
2 1/4
2 3/8
2 1/2
2 5/8
2 3/4

```

Input `2 3/4` `1/2` would output:

```
0
1/2
1
1 1/2
2
2 1/2

```

# Answer
> 3 votes
# Pyke, 38 bytes

```
KQz\/cebj*Bh Fj.DRIIid)ij.Hi'f jRf\/Rs

```

Try it online!

Not too bad for a language that has literally no fractional support. Explanation later if at all.

# Answer
> 2 votes
## Mathematica, ~~55~~ 53 bytes

*Thanks to JungHwan Min for saving 2 bytes.*

```
DeleteCases[{a=Floor@#,#-a},0,1,1]&/@Range[0,+##2,#]&

```

Takes three numbers as input, the step width, the integer part of the ruler length, the fractional part of the ruler length.

Output is a list of lists with sublists like `{1}` or `{2, 3/4}`.

# Answer
> 1 votes
# Husk, 21 bytes

```
:"0"mȯwfI§e⌊%1↑≤Σ⁰¡+³

```

Try it online!

Have to prepend a 0 string before, cause filtering out zeroes messes with it.

Does anybody know how to run the Ohm answer?

# Answer
> 0 votes
# Ohm, 17 bytes

```
II¢/II/a/#:$_*,;

```

Explanation:

```
II/¢II/a/#:$_*,;  ■Main wire
II/¢              ■Evaluate fraction and save to register
    II/           ■Evaluate another fraction
       a/         ■Divide first by second evaluating to the required steps
         #:    ;  ■foreach _ in range(0,steps){
           $_*,   ■  print (register * _)
                  ■}

```

# Answer
> 0 votes
## Batch, 213 bytes

```
@echo off
set n=%4
set/an*=%1,n+=%2*%1/%3
for /l %%i in (0,1,%n%)do call:c %%i %1
exit/b
:c
set/ad=%2,i=%1/d,n=%1%%d
if %n%==0 echo %i%&exit/b
set/an/=p=n^&-n,d/=p
if %i% gtr 0 set n=%i% %n%
echo %n%/%d%

```

Takes 4 numbers as input:

1. The number of marks per inch i.e. the reciprocal/denominator of the granularity
2. The numerator of the ruler length
3. The denominator of the ruler length
4. (Optional) The whole number of inches of the ruler length

So for the second example the parameters would be `8 3 4 2`. Note that for lengths that are an exact number of integers you still need to specify a dummy fraction e.g. `4 0 1 2`, or an improper fraction `4 2 1` would also work.

---
Tags: code-golf, sequence, rational-numbers
---


title: Negative Fibonacci Numbers

text:
# Question
Title: Negative Fibonacci Numbers
You probably all know the fibonacci sequence:

```
fibonacci(n)=fibonacci(n-1)+fibonacci(n-2)
fibonacci(0)=0
fibonacci(1)=1

```

Your task is as simple as it could be:

* Given integer `N` compute `fibonacci(n)`

but here is the twist:

* Also do negative `N`

Wait. What?

```
fibonacci(1)=fibonacci(0)+fibonacci(-1)

```

so

```
fibonacci(-1)=1

```

and

```
fibonacci(-2)=fibonacci(0)-fibonacci(1)=-1

```

and so on...

* This is a so shortest programm in bytes win.
* You may submit a function or a full programm
* N is in \[-100,100\]

Testcase(s) in CSV:

```
-9;-8;-7;-6;-5;-4;-3;-2;-1;0;1;2;3;4;5;6;7;8
34;-21;13;-8;5;-3;2;-1;1;0;1;1;2;3;5;8;13;21

```

Hint:

> n\<0 and n&1==0:
>
> ```
> fibonacci(n)=fibonacci(abs(n))*-1
> ```

# Answer
# Mathematica, 9 bytes

```
Fibonacci

```

Yes, this built-in function supports negative numbers.
> 23 votes

# Answer
# Octave, 20 bytes

```
 @(n)([1,1;1,0]^n)(2)

```

Try it online!

### Explanation

This makes use of the fact that the fibonacci sequence `f(n)` can be written as (this should be a matrix vector notation):

Recursively:

```
[f(n+1)]  = [1  1] * [f(n)  ]
[f(n)  ]    [1  0]   [f(n-1)]

```

Explicitly:

```
[f(n+1)]  = [1  1] ^n * [1]
[f(n)  ]    [1  0]      [0]

```

This means that the top right entry of this matrix to the power of `n` is the value `f(n)` we're looking for. Obviously we can also invert this matrix as it has full rank, and the relationship still describes the same recurrence relation. That means it also works for negative inputs.
> 18 votes

# Answer
# Maxima, 3 bytes

```
 fib

```

supports positive and negative numbers.

Try it (paste) on CESGA - Maxima on line
> 13 votes

# Answer
## Python, 43 bytes

```
g=5**.5/2+.5
lambda n:(g**n-(1-g)**n)/5**.5

```

A direct formula with the golden ratio `g`. With `f` the above function:

```
for n in range(-10,11):print f(n)

-55.0
34.0
-21.0
13.0
-8.0
5.0
-3.0
2.0
-1.0
1.0
0.0
1.0
1.0
2.0
3.0
5.0
8.0
13.0
21.0
34.0
55.0

```

Same length alt, only aliasing the square root of 5:

```
a=5**.5
lambda n:((a+1)**n-(1-a)**n)/a/2**n

```

I didn't see a way to make a recursive function that could compete with these. A mildly-golfed attempt for 57 bytes:

```
f=lambda n:n<0and(-1)**n*f(-n)or n>1and f(n-1)+f(n-2)or n

```

For comparison, an iterative method (60 bytes in Python 2):

```
n=input()
a,b=0,1;exec"a,b=b,a+b;"*n+"a,b=b-a,a;"*-n
print a

```

Or, for 58 bytes:

```
n=input()
a,b=0,1;exec"a,b=b,a+cmp(n,0)*b;"*abs(n)
print a

```
> 12 votes

# Answer
## JavaScript (ES6), 42 bytes

```
f=n=>n<2?n<0?f(n+2)-f(n+1):n:f(n-2)+f(n-1)

```

### Test

```
f=n=>n<2?n<0?f(n+2)-f(n+1):n:f(n-2)+f(n-1)

for(i = -9; i < 9; i++) {
  console.log(i, f(i))
}
```
> 10 votes

# Answer
# JavaScript (ES7) 37 bytes

Uses Binet's Formula.

```
n=>((1+(a=5**.5))**n-(1-a)**n)/a/2**n

```

This outputs the `n`th Fibonacci number +- `0.0000000000000005`.
> 6 votes

# Answer
# MATL, ~~11~~ 9 bytes

~~I'm happy about the `[3,2]`, which surely could be golfed, if anyone knows a way please let me know=) (It would also work with `[1,3]`.)~~ Thanks @LuisMendo for -2 bytes=)

```
IHhBiY^2)

```

This is using the same approach as the Octave annswer. But to generate the matrix

```
[1,1]
[1,0]

```

we just conver the number `3` and `2` from decimal to binary (i.e. `11` and `10`).

Try it online!
> 5 votes

# Answer
# Jolf, 2 bytes

```
mL

```

Try it here!

The fibonacci builtin, implemented using the `phi` formula.
> 4 votes

# Answer
# Haskell, 51 bytes

```
s=0:scanl(+)1s;f z|even z,z<0= -f(-z);f z=s!!abs z

```
> 2 votes

# Answer
## Lithp, 88 bytes

```
#N::((if(< N 2)((if(< N 0)((-(f(+ N 2))(f(+ N 1))))((+ N))))((+(f(- N 2))(f(- N 1))))))

```

My look at all those parentheses.

Try it online!

Not very small really. There's currently a parsing bug that requires one to use `(get N)` or `(+ N)` instead of simply `N`. I chose the smaller one. However I don't think there's anything that can be done further to golf this.
> 1 votes

# Answer
# PowerShell, 112 Bytes

```
function f($n){$o=('-','+')[$n-lt0];&(({$a,$b=(2,1|%{f("$n$o$_"|iex)});"$a- $o$b"|iex},{$n*$n})[$n-in(-1..1)])}

```

**Demo Call:**

```
-9..9 | %{"{0,2}`t=> {1,3}" -f $_,(f($_))}

```

**Output of Demo:**

```
-9  =>  34
-8  => -21
-7  =>  13
-6  =>  -8
-5  =>   5
-4  =>  -3
-3  =>   2
-2  =>  -1
-1  =>   1
 0  =>   0
 1  =>   1
 2  =>   1
 3  =>   2
 4  =>   3
 5  =>   5
 6  =>   8
 7  =>  13
 8  =>  21
 9  =>  34

```
> 1 votes

# Answer
# Jelly, 2 bytes

```
ÆḞ

```

Try it online!

Boring builtin answer, Jelly’s Fibonacci builtin handles negative inputs just fine
> 0 votes

---
Tags: code-golf, number, sequence, fibonacci
---


title: Equality up to Swapping

text:
# Question
Title: Equality up to Swapping
## inputs / outputs

your program/function/routine/... will be a predicate on two tuple sequences; call it relation . for the purpose of simplicity we use natural numbers:

* the input will be two list of pairs of numbers from ℕ (including 0); call them `Xs` and `Ys`
* the output will be a "truthy" value

## specification

checks the sequences for equality up to permuting elements where the first elements `u` and `u'` don't match.

in other words  compares lists with `(u,v)`s in it for equality. but it doesn't completely care about the order of elements `(u,v)`s. elements can be permuted by swapping; swaps of `(u,v)` and `(u',v')` are only allowed if `u ≠ u'`.

**formally:** write `Xs ≡ Ys` iff  holds for `Xs` and `Ys` as inputs (the predicate is an equivalence relation hence symmetric):

* `[] ≡ []`
* if `rest ≡ rest` then `[(u,v),*rest] ≡ [(u,v),*rest]` (for any `u`, `v`)
* if `u ≠ u'` and `[(u,v),(u',v'),*rest] ≡ Ys` then `[(u',v'),(u,v),*rest] Ys`

## examples

```
[] [] → 1
[] [(0,1)] → 0
[(0,1)] [(0,1)] → 1
[(0,1)] [(1,0)] → 0
[(1,0)] [(1,0)] → 1
[(1,2),(1,3)] [(1,2),(1,3)] → 1
[(1,2),(1,3)] [(1,3),(1,2)] → 0
[(1,2),(1,3)] [(1,2),(1,3),(0,0)] → 0
[(0,1),(1,2),(2,3)] [(2,3),(1,2),(0,1)] → 1
[(1,1),(1,2),(2,3)] [(2,3),(1,2),(0,1)] → 0
[(1,2),(0,2),(2,3)] [(2,3),(1,2),(0,1)] → 0
[(1,2),(2,3),(0,2)] [(2,3),(1,2),(0,1)] → 0
[(1,1),(1,2),(1,3)] [(1,1),(1,2),(1,3)] → 1
[(3,1),(1,2),(1,3)] [(1,2),(1,3),(3,1)] → 1
[(3,1),(1,2),(1,3)] [(1,3),(1,2),(3,1)] → 0
[(2,1),(3,1),(1,1),(4,1)] [(3,1),(4,1),(1,1)] → 0
[(2,1),(4,1),(3,1),(1,1)] [(3,1),(1,1),(2,1),(4,1)] → 1
[(2,1),(3,1),(1,1),(4,1)] [(3,1),(2,1),(4,1),(1,1)] → 1

```

(keep in mind the relation is symmetric)

# Answer
> 5 votes
# Husk, 4 bytes

```
¤=Ö←

```

Try it online! (header runs function on all test cases)

```
¤       # combin: applies one function to two values and combines the results
 =      # combining function: are they equal?
  Ö←    # function to apply: sort on first element
        # values (implicit): inputs

```

# Answer
> 4 votes
# JavaScript (ES6), 47 bytes

Assumes that `.sort()` is stable, which is now guaranteed by the specification (today's version!).

```
a=>b=>(g=a=>a.sort(([a],[b])=>a-b))(a)+''==g(b)

```

Try it online!

# Answer
> 3 votes
# Haskell, 42 bytes

```
import Data.List
q=sortOn fst
a%b=q a==q b

```

Try it online!

Based on Arnauld's JS solution. Despite Haskell needing a lengthy import to access sorting, it's well worth the bytes. Note that sortOn, which sorts a list by a custom predicate, is stable. In fact, `sortOn fst` is used for the example in the documentation.

---

# Haskell, 50 bytes

```
a%b|let q l=[t|u<-a++b,t<-l,fst t==fst u]=q a==q b

```

Try it online!

**51 bytes**

```
k?l=[x|(i,x)<-l,i==k]
a%b=and[k?a==k?b|(k,_)<-a++b]

```

Try it online!

Uses this characterization: For each number `k`, the pairs whose first element equals `k` within each list come in the same order."

The helper function `?` in `k?l` takes a list of pairs `l` and selects for the second element `x` in each pair `(k,x)` with first element equal to `k`. The main function `%` then checks that this is the same on both input lists for each `k` present.

Note that we avoid using sorting, which Haskell doesn't have built-in without a lengthy import.

**51 bytes**

```
k?l=[t|t<-l,fst t==k]
a%b=and[k?a==k?b|(k,_)<-a++b]

```

Try it online!

**51 bytes**

```
(?)k=filter$(==k).fst
a%b=and[k?a==k?b|(k,_)<-a++b]

```

Try it online!

**51 bytes**

```
l?m=[x|(k,_)<-m,(i,x)<-l,i==k]
a%b|s<-a++b=a?s==b?s

```

Try it online!

# Answer
> 2 votes
# Ruby 2.7, 41 bytes

```
->a,b{a.sort_by{_1[0]}==b.sort_by{_1[0]}}

```

No TIO link, as TIO uses an older version of Ruby.

---

# Ruby, 45 bytes

```
->a,b{a.sort_by(&:first)==b.sort_by(&:first)}

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), 13 bytes

```
{~/x@'<'*''x}

```

Try it online!

Takes input as a single argument of two lists of lists.

* `x@'<'*''x` sort each input by the first item of each-each input
* `~/` do the two sorted lists match?

# Answer
> 1 votes
# Charcoal, 23 bytes

```
⬤⁺θη⁼Φθ⁼§λ⁰§ι⁰Φη⁼§λ⁰§ι⁰

```

Try it online! Link is to verbose version of code. Output is a Charcoal boolean, i.e. `-` for equivalent, nothing if not. Explanation:

```
  θ                     First list
 ⁺                      Concatenated with
   η                    Second list
⬤                       All pairs must satisfy
      θ                 First list
     Φ                  Filtered where
        §λ⁰             First element of inner pair
       ⁼                Equals
           §ι⁰          First element of outer pair
    ⁼                   Equals
               η        Second list
              Φ         Filtered where
                 §λ⁰    First element of inner pair
                ⁼       Equals
                    §ι⁰ First element of outer pair
                        Implicitly print

```

# Answer
> 1 votes
# Retina 0.8.2, 21 bytes

```
%O#`\d+,\d+
^(.+)¶\1$

```

Try it online! Assumes lists on separate lines but link includes header that splits the test cases for ease of use. Explanation:

```
%O#`\d+,\d+

```

Sort each list stably by the first element of each pair.

```
^(.+)¶\1$

```

Compare the two lists.

# Answer
> 1 votes
# Jelly, 4 bytes

```
ṖÞ€E

```

A monadic Link accepting a list of the two lists which yields `1` (truthy) or `0` (falsey).

**Try it online!** Or see the test-suite.

### How?

```
ṖÞ€E - Link: [a,b]
  €  - for each list, [t_1, t_2, ...], in [a,b]
 Þ   -   sort by:
Ṗ    -     pop (t_n with its tail removed)
   E - all equal?

```

---
Tags: code-golf, array, decision-problem
---


# Question
Title: How many points does my license plate give?
(This is my first code-golf question)

When I was a child, my dad and I invented a game where the license plate we see on cars can give certain points based on some rather simple rules:

X amount of the same letter or number give X-1 points, examples:

```
22 = 1 point
aa = 1 point
5555 = 3 points

```

The numbers must be next to eachother, so `3353` only gives 1 point, as the 5 breaks the sequence of 3's.

A sequence of X numbers in ascending or descending order, at a minimum of 3, give X points, examples:

```
123 = 3 points
9753 = 4 points
147 = 3 points

```

The point system only works for 1-digit-numbers, so `1919` doesn't give points, and `14710` only give 3, (147).

Sequences can be combined to make more points, examples:

```
1135 = 4 points (1 point for 11 and 3 points for 135)
34543 = 6 points (3 points for 345 and 3 points for 543)

```

You are however not allowed to chop a larger sequence into 2 smaller sequences for extra points: `1234 = 123, 234 (6 points)` is not allowed.

Your task is, given a sequence, to determine the number of points the license plate gives.

In Denmark, the license plates are structured like this: CC II III, where C is character and I is integer, and thus my example inputs will reflect this structure. If you wish, you may make the sequence fit your own structure, or, if you feel really adventurous, let the program analyze the structure of the license plate and thus have it work on any type of license plate around the world. Explicitly state the structure you decide to use in your answer though.

You may take the input in any way you please, either a string or an array seem to make most sense to me.

Test input | output:

```
AA 11 111 | 5
AB 15 436 | 3
OJ 82 645 | 0
UI 65 456 | 6
HH 45 670 | 5
YH 00 244 | 5
AJ 00 754 | 1

```

Due to the nature of choosing your own structure, or even covering all structures, I dont necessarily see how a winner can be explicitly determined. I suppose the winner will be the shortest bytes on the structure one has decided. (And don't take an input like C I C I C, just to make it easy for yourself)

EDIT:

Due to comments asking, I have a few extra pieces of information to share: A sequence of ascending or descending numbers refers to an arithmetic sequence, so X +/- a * 0, X +/- a * 1, ... X +/- a * *n* etc. So 3-5-7 for example is 3 + 2 * 0, 3 + 2 * 1, 3 + 2 * 2. The sequence does not, however, need to start from 0 nor end in 0.

MORE EDIT:

You may give the input in any way you please, you dont need to input spaces, dashes or any other thing that makes a license plate more readable. If you can save bytes by only accepting capital letters or something like that, you may do that aswell. The only requirement is that your program can take a string/array/anything containing both characters and numbers, and output the correct amount of points according to the rules stated.

# Answer
> 7 votes
# 05AB1E, ~~25~~ ~~22~~ ~~20~~ 18 bytes

Accepts a string of lower-case alphabetic chars and numbers with no spaces.

```
Ç¥0Kγ€gXK>OIγ€g<OO

```

Try it online! or as a Test Suite

# Answer
> 7 votes
# Husk, ~~20~~ ~~16~~ 15 bytes

-1 byte thanks to @Zgarb

Takes input without spaces and in lower case.

```
ṁ??¬o→LεL←gẊ¤-c

```

Try it online!

### Explanation

```
           Ẋ      Map over all adjacent pairs
            ¤-c   get the difference of their codepoints
          g       Split into groups of equal elements
ṁ                 Map then sum
 ?       ←          If the head of the list is truthy (not 0)
  ?    ε              If the length of the list is 1
   ¬                    return 0
                       Else
    o→L                 return the length + 1
                     Else
        L             return the length

```

# Answer
> 6 votes
# Python 3, ~~193~~ 85 bytes

-3 bytes thanks to Lynn

Takes input as a byte-string with lowercase letters as: `b'aa11111'`.

```
def f(s):
 d=l=L=p=0
 for c in s:C=0!=d==c-l;p+=(c==l)+C*L;L=3>>C;d=c-l;l=c
 return p

```

Try it online!

# Answer
> 2 votes
# Java 8, 195 bytes

```
a->{int r=a[0]==a[1]?1:0,i=3,j,p=a[2],x,y,z;for(;i<7;p=a[i++])for(r+=(x=a[i])==p?1:0,j=-4;++j<4;r+=j==0?0:i<6&&p+j==x&x+j==(y=a[i+1])?++i<6&&y+j==(z=a[i+1])?++i<6&&z+j==a[i+1]?5:4:3:0);return r;}

```

Can definitely be golfed some more by using another technique to check for sequences.

**Explanation:**

Try it here.

```
a->{                      // Method with character-array parameter and integer return-type
  int r=                  //  Result-integer
        a[0]==a[1]?       //   If the two letters are equal:
         1                //    Start this result-integer at 1
        :                 //   Else:
         0,               //    Start the result-integer at 0 instead
      i=3,j,              //  Index-integers
      p=a[2],x,y,z;       //  Temp integers
   for(;i<7;              //  Loop (1) from index 3 to 7 (exclusive)
       p=a[i++])          //    And after every iteration: Set `p` and raise `i` by 1
     for(r+=(x=a[i])==p?  //   If the current digit (now `x`) equals the previous `p`:
             1            //    Raise the result-integer by 1
            :             //   Else:
             0,           //    Keep the result-integer the same
         j=-4;++j<4;      //   Inner loop (2) from -3 to 3 (inclusive)
       r+=j==0?           //    If `j` is 0:
           0              //     Skip it, so keep the result-integer the same
          :i<6            //    Else-if `i` is not 6,
           &&p+j==x       //    and the previous digit `p` + `j` equals the current digit,
           &x+j==(y=a[i+1])?
                          //    and the current digit `x` + `j` equals the next digit `y`:
            ++            //     Raise index `i` by 1 first,
              i<6         //     and check if `i` is not 6 again,
              &&y+j==(z=a[i+1])?
                          //     and if the new current digit `y` + `j` equals the next digit `z`:
               ++         //      Raise index `i` by 1 first again,
                 i<6      //      and check if `i` is not 6 again,
                 &&z+j==a[i+1]?
                          //      and if the new current digit `z` + `j` equals the next digit:
                  5       //       Raise the result-integer by 5
                 :        //      Else:
                  4       //       Raise it by 4 instead
              :           //     Else:
               3          //      Raise it by 3 instead
           :              //    Else:
            0             //     Keep it the same
     );                   //   End of inner loop (2)
                          //  End of loop (1) (implicit / single-line body)
  return r;               //  Return the result-integer
}                         // End of method

```

# Answer
> 2 votes
# , ~~153~~, ~~145~~, 143 bytes

```
function(x){p=0;s=sum;if(x[1]==x[2])p=1;a=diff(strtoi(x[3:7]));p=p+s(a==0);l=sort(table(a[a!=0]),T);(p=p+s(l[(l[((s(l)>0)&(l[1]>1))]+1)>2]+1))}

```

Anonymous function that takes a character vector and returns an integer.
Expected input `z(c("A", "A", "1", "1", "1", "1", "1"))`

Try it online!

Ungolfed version

```
function(x){
  pnt <- 0; s <- sum
  if(x[1] == x[2]) pnt <- 1
  a <- diff(strtoi(x[3:7]))
  pnt <- pnt + s(a == 0)
  l <- sort(table(a[a!=0]), T)
  (pnt <- pnt + s(l[(l[((s(l) > 0) & (l[1] > 1))] + 1) > 2] + 1))
}

```

# Answer
> 2 votes
# Perl 5 `-pF`, ~~116~~ 89 bytes

```
$a.=($_=(ord$F[++$t])-ord)?chr$_+77:++$;for@F[0..@F-2];$_=$a=~s/(\S)\1+/$;+=length$&/ge+$

```

Try it online!

# Answer
> 1 votes
# Pyth,  ~~51~~  50 bytes (staggering)

```
+/|R0.+QZslM.MlZ+kfTsmm?&!-K.+sMkhK.AKkY.:>Q2d}3 5

```

**Verify all test cases** or **Try it here.**

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

```
f(p,r,d,D,s,l)char*p;{for(r=D=0;d=p[1]-*p,*++p;D=d){s=d&&d==D;r+=!d+s*l;l=3-2*s;}return r;}

```

Try it online!

Idea stolen from Felipe Nardi Batista's Python answer.

# Answer
> 1 votes
# Pyth, ~~48~~ 42 bytes

Direct port from my python answer. Takes input as a byte-string with lowercase letters as: b'aa11111'.

This is my first time coding in Pyth, so any tips are welcome :D

```
KJ=b0VQ=d&KqK-NJ=+b+qNJ*dZ=Z-3yd=K-NJ=JN;b

```

Try it here

# Answer
> 1 votes
# JavaScript, ~~216~~ ~~192~~ ~~186~~ ~~202~~ 201 bytes

```
function f(s){var a=s.split(" "),c=a[1],a=a[0],r,h=b=i=p=0;for(i=0;i<4;i++){if(i<2&(r=a[i+1]-a[i]==a[i+2]-a[i+1])){p++;b=2}if(i>0){if(a[i]==a[i-1]){p++;h++}if(i<3&c[i]==c[i-1])p++}}return h==4?p+b:p-b}

```

### Unminified

```
function f(s){
    var a=s.split(" "),c=a[1],a=a[0],r,h=b=i=p=0;
    for(i=0;i<4;i++){
        if(i<2&(r=a[i+1]-a[i]==a[i+2]-a[i+1])){
            p++;
            b=2
        }
        if(i>0){
            if(a[i]==a[i-1]){
                p++;
                h++;
            }
            if(i<3&c[i]==c[i-1])
                p++;
        }
    }

    return h==4?p+b:p-b
}

```

Edit history:

* Narrowed down the code to only work with `0000 XXX` format. (-24 bytes)
* Edits as suggested by @Titus. (-6 bytes)
* fixed a bug where four identical numbers gave a score of 7 instead of 3. (+16 bytes)
* Removed last semi-colon. (-1 byte)
* Fixed a typo in the code. (no byte change)

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


# Question
Title: Convert all the newlines in a file from \r\n to \n
Inspired by what I'm doing at work right now.

Your program should take one parameter, the path to the file

It should convert all the windows style newlines (\r\n) to unix style (\n) and write the result back to the file

# Answer
> 0 votes
# APL (Dyalog Unicode), ~~22~~ bytes

Anonymous tacit prefix function.

```
10@3∘⎕NGET⎕NPUT{⍵1}

```

Try it online!

`⎕NGET` get content,encoding,line-ending from argument file

`10@3∘` replace the third element (line ending) with 10, meaning \n

`⎕NPUT` put that into…

`{⍵1}` the file name followed by an overwrite flag

---
Tags: code-golf, file-system
---


title: Explosions on a chessboard

text:
# Question
Title: Explosions on a chessboard
Atomic chess is a (very fun) variant of chess in which every capture causes an "explosion," destroying the captured piece, the piece doing the capturing, and all non-pawns in a 1-square radius. The goal of this challenge is not to play an entire game of atomic chess, but simply to simulate what happens when a certain move is made.

Disclaimer: Explosion sound effects not included.

## Input

Board position will be given in Forsyth-Edwards Notation (commonly known as FEN), but with only the first field. For example, an input of:

```
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR

```

represents the starting position:

This must be taken as a string or your language's equivalent. It is guaranteed to be valid; for example, you don't have to care if there are ten kings, or if there is no king at all.

You will also be given the move that you are to simulate, which is represented as two square names: the square on which the piece to be moved is, and the square it is moving to. For example, moving the king's pawn two spaces forwards on the above picture would be represented as:

```
e2e4

```

This must also be taken as a string. The move will always be valid, and you do not need to support castling. You do need to support *en passant*, which will be explained in further detail in the next section.

## Output

The output of your program should be in the same partial-FEN notation as the input, with the specified move made (and any pieces exploded if necessary).

The exact rules for explosions are—when a piece is captured:

* Remove the piece being captured (this will always be the piece on the second square named in the input, except for when the capture is an *en passant*).
* Remove the piece that is doing the capturing (this will always be the piece on the first square named in the input).
* Remove every piece that is:

+ located on one of the 8 squares surrounding the one where the capture took place (for *en passant*, this is the square that the capturing pawn would be on, if it didn't explode).
    + not a pawn.

Quick overview of *en passant* rules, for those who are unfamiliar: if a pawn moves two spaces forwards from its starting rank, and there is a pawn that could have captured it if it only moved one square forward, it may capture it anyway, but only on the subsequent move. This capture is said to be done "*in passing*" (or in French: "*en passant*").

## Test cases

In the pictures, the green arrows represet the move about to be made, and the green circles represents pieces that are exploded.

Input: `rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`, `g1f3`
Output: `rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R`

---

Input: `3kBb1r/pp5p/3p4/4pn2/P7/1P2P1pP/2rP1P2/R1B3RK`, `f2g3`
Output: `3kBb1r/pp5p/3p4/4pn2/P7/1P2P2P/2rP4/R1B3RK`
*(stolen from http://en.lichess.org/ocoSfS5I/white#36)*

---

Input: `rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R`, `f3b7`
Output: `3qk1nr/2p5/p2pp1pp/5p2/1bN5/2P1P2N/PP1P1PPP/R1B1KB1R`
*(stolen from http://en.lichess.org/NCUnA6LV/white#14)*

---

Input: `rnbqk2r/pp2p2p/2p3pb/3pP3/5P2/2N5/PPPP2P1/R1BQKB1R`, `e5d6`
Output: `rnbqk2r/pp2p2p/2p3pb/8/5P2/2N5/PPPP2P1/R1BQKB1R`
*(stolen from http://en.lichess.org/AvgU4Skq/white#16; this wasn't the actual move, but I couldn't be bothered to find an atomic game that actually had en passant :P)*

---

Input: `5r2/2k5/p1B5/1pP1p3/1P4P1/3P4/P7/1K3R1q`, `c6h1`
Output: `5r2/2k5/p7/1pP1p3/1P4P1/3P4/P7/1K3R2`
*(stolen from http://en.lichess.org/l77efXEb/white#58)*

## Scoring

This is , so the shortest code in bytes wins.

# Answer
# JavaScript (*ES6*) 305 ~~310 321~~

As a function with 2 real parameters (and a lot more with default values, used as a quick and dirty way to define locals)

Test running the snippet below (being EcmaScript 6, Firefox only)

```
F=(g,m,b=[...g.replace(/\d/g,c=>'0'.repeat(c))],P=p=>p=='p'|p=='P',n=parseInt(m,32),
  s=n>>5&31,u=n>>15,x=b[y=u+62-(n>>10&31)*9])=>(
  b[b[y]=0,z=s+62-(n&31)*9]<1&!(s!=u&P(x))?b[z]=x:
  [-1,1,8,9,10,-8,-9,-10].map(i=>b[i+=z]>'/'&&!P(b[i])?b[i]=0:0,b[b[z]<1?z>y?z-9:z+9:z]=0),
  b.join('').replace(/0+/g,x=>x.length)
)

//TEST
out=x=>O.innerHTML+=x+'\n'

test=[
 ['rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR', 'g1f3'
  ,'rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R']
,['3kBb1r/pp5p/3p4/4pn2/P7/1P2P1pP/2rP1P2/R1B3RK', 'f2g3'
  ,'3kBb1r/pp5p/3p4/4pn2/P7/1P2P2P/2rP4/R1B3RK']
,['rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R', 'f3b7'
  ,'3qk1nr/2p5/p2pp1pp/5p2/1bN5/2P1P2N/PP1P1PPP/R1B1KB1R']
,['rnbqk2r/pp2p2p/2p3pb/3pP3/5P2/2N5/PPPP2P1/R1BQKB1R', 'e5d6'
  ,'rnbqk2r/pp2p2p/2p3pb/8/5P2/2N5/PPPP2P1/R1BQKB1R']
,['5r2/2k5/p1B5/1pP1p3/1P4P1/3P4/P7/1K3R1q', 'c6h1'
  ,'5r2/2k5/p7/1pP1p3/1P4P1/3P4/P7/1K3R2']
]

test.forEach(t=>(
  r=F(t[0],t[1]),
  out('Test '+(r==t[2]?'Ok':'Fail!')+'  '+t[0]+' move '+t[1]
     +'\nResult   '+r+'\nExpected '+t[2]+'\n')))
```

```
<pre id=O></pre>
```

**Ungolfed**

```
B=(b,m)=>{
  P=p=>p=='p'|p=='P'
  m=parseInt(m,32)
  r=m&31 // arrival row
  s=(m/32&31)-10 // arrival column
  z=s+(8-r)*9 // arrival position
  t=m/32/32&31 // start row
  u=(m/32/32/32&31)-10 // start column
  y=u+(8-t)*9 // start position
  b=[...b.replace(/\d/g,c=>'0'.repeat(c))] // board to array, empty squares as 0
  x=b[y] // moving piece
  b[y]=0
  C=s!=u&P(x) // pawn capture
  if (b[z]<1 && !C)
  {  // no capture
    b[z]=x
  }
  else
  {
    // capture and boom!
    if (b[z]<1) // arrival empty: en passant
      b[z>y?z-9:z+9]=0;
    else
      b[z]=0;
    // zero to nearest 8 squares
    [-1,1,8,9,10,-8,-9,-10].forEach(i=>b[i+=z]>'/'&&!P(b[i])?b[i]=0:0)
  }
  return b.join('').replace(/0+/g,x=>x.length)
}

```
> 5 votes

# Answer
# APL (Dyalog Extended), 240 bytes

```
e←' '@(p/⍨~(x←∊∘'Pp')(b←↑⊃¨,/¨{⍵∊⎕D:' '/⍨⍎⍵⋄⍵}¨¨'/'(≠⊆⊢)⎕)[p←p/⍨{∧/⍵∊⍳8}¨p←(⊃⌽c←{(9-⍎⊃⌽⍵),⎕A⍳⊃⍵}¨↓2 2⍴1⎕C⎕)∘+¨,∘.,⍨2-⍳3])
1↓⊃,/{'/',⊃,/{' '∊⍵:⍕≢⍵⋄⍵}¨⍵⊂⍨1,2≠/⍵}¨↓{(x⊃n)∧(≠/⊃¨⌽¨c)∧' '=⊃⌽n←b[c]:e' '@((⊃c)+0,1↓⊃-⍨/c)⊢b⋄' '∊n:(⌽n)@c⊢b⋄e' '@c⊢b}0

```

Try it online!

A full program which takes the FEN first, and the move second.

## Explanation

**First Line: Explode. Function**

```
e←' '@(p/⍨~(x←∊∘'Pp')(b←↑⊃¨,/¨{⍵∊⎕D:' '/⍨⍎⍵⋄⍵}¨¨'/'(≠⊆⊢)⎕)[p←p/⍨{∧/⍵∊⍳8}¨p←(⊃⌽c←{(9-⍎⊃⌽⍵),⎕A⍳⊃⍵}¨↓2 2⍴1⎕C⎕)∘+¨,∘.,⍨2-⍳3])

```

`1⎕C⎕` capitalize the first input

`↓2 2⍴` cut into halves

`{(9-⍎⊃⌽⍵),⎕A⍳⊃⍵}¨` apply the following to each square name:  `,⎕A⍳⊃⍵` get position of first char in the alphabet(column) `(9-⍎⊃⌽⍵)`  get 9-int(second char) (row number)

`c←` store that in c

`⊃⌽` take the last element

`∘+¨` and add that to:

`,∘.,⍨2-⍳3` the cartesian product of (-1,0,1), getting the von neumann neighborhood

`p←` assign the explosion indices to p

`p←p/⍨{∧/⍵∊⍳8}¨` remove the ones outside the board, and reassign to p

`(...)[...]` and index into the following:

`'/'(≠⊆⊢)⎕` split the second input on slashes

`⊃¨,/¨{⍵∊⎕D:' '/⍨⍎⍵⋄⍵}¨¨` convert each digit to the appropriate amount of spaces

`b←↑` and convert it to a matrix, storing in b. This is the chess board.

`x←∊∘'Pp'` store function to check for pawns in x

`p/⍨~(x←∊∘'Pp')` now, remove the points which map to pawns

`' '@` and insert a space at those indices in the right argument.

**Second line: capture calculator**

```
1↓⊃,/{'/',⊃,/{' '∊⍵:⍕≢⍵⋄⍵}¨⍵⊂⍨1,2≠/⍵}¨↓{(x⊃n)∧(≠/⊃¨⌽¨c)∧' '=⊃⌽n←b[c]:e' '@((⊃c)+0,1↓⊃-⍨/c)⊢b⋄' '∊n:(⌽n)@c⊢b⋄e' '@c⊢b}0

```

`n←b[c]` assign the starting and ending characters to n

`' '=⊃⌽n←b[c]` If ending square is empty,

`(≠/⊃¨⌽¨c)∧` start column and end column are not equal,

`(x⊃n)∧` and capturing piece is a pawn(en passant):

`0,1↓⊃-⍨/c` get the direction of capture

`(⊃c)+` add that to the start index

`' '@((⊃c)+0,1↓⊃-⍨/c)⊢b` insert a space at that point

`e` and **explode.**

`' '∊n` else, if ending point is a space(no capture):

`(⌽n)@c⊢b⋄` switch the places of the space and the piece

`' '@c⊢b` Otherwise, insert a space at the start and end index(normal capture)

`e` and **explode.**

`¨↓` then, take each row,

`⍵⊂⍨1,2≠/⍵` group it into equal runs

`{' '∊⍵:⍕≢⍵⋄⍵}¨` replace runs of spaces with their length.

`'/',⊃,/` join everything together and prepend a /

`1↓⊃,/` join the rows together and drop the first /.
> 3 votes

# Answer
# Java, (~~946~~ ~~777~~ 776 chars)

*1 char thanks to @edc65*

Note: Chars counted without test cases put in.

**Code**

```
class E{public static void main(String[]a){String i=a[0];char[]n=a[1].toCharArray();int j,k,z,w,y,u=56-n[3];char q,p,e ='e';char[][]b=new char[8][8];String[]r=i.split("/");for(j=0;j<8;j++){z=0;for(k=0;k<r[j].length();k++){p=r[j].charAt(k);if(Character.isDigit(p)){for(int l=k+z;l<k+z+p-48;l++)b[j][l]=e;z+=p-49;}else b[j][k+z]=p;}}z=n[0]-97;w=56-n[1];y=n[2]-97;p=b[w][z];q=b[u][y];b[w][z]=e;if(q!=e||((p|32)=='p'&&(w-u<0?u-w:w-u)==1&&(z-y<0?y-z:z-y)==1)){if(q!=e)b[u][y]=e;else b[w][y]=e;for(j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){for(k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++)if((b[k][j]|32)!='p')b[k][j]=e;}}else b[u][y]=p;i="";for(j=0;j<8;j++){z=0;for(k=0;k<8;k++){if(b[j][k]==e)z++;else {if(z>0){i+=z;z=0;}i+=b[j][k];}}if(z>0)i+=z;i+=j!=7?"/":"";}System.out.print(i);}}

```

I'm not sure if this solution is optimal, but I'm working on golfing it more, any suggestions are welcome. I can comment all the code too if anyone would like, but I think it's mostly self explanatory, except for the confusing variable enumeration.

**Explanation**

* Unpack the board string into a char matrix
* Calculate the effect of the move
* Repack the board into a string

**Expanded**

```
class ExplosionChess{
    public static void main(String[]a){
        String i=a[0];
        //"rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R";
        //"f3b7";
        char[]n=a[1].toCharArray();
        int j,k,z,w,y,u=56-n[3];
        char q,p,e ='e';
        char[][]b=new char[8][8];
        String[]r=i.split("/");
        for(j=0;j<8;j++){
            z=0;
            for(k=0;k<r[j].length();k++){
                p=r[j].charAt(k);
                if(Character.isDigit(p)){
                    for(int l=k+z;l<k+z+p-48;l++)
                        b[j][l]=e;
                    z+=p-49;
                }else
                    b[j][k+z]=p;
            }
        }
        z=n[0]-97;
        w=56-n[1];
        y=n[2]-97;
        p=b[w][z];
        q=b[u][y];
        b[w][z]=e;
        if(q!=e||((p|32)=='p'&&(w-u<0?u-w:w-u)==1&&(z-y<0?y-z:z-y)==1)){
            if(q!=e)
                b[u][y]=e;
            else
                b[w][y]=e;
            for(j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){
                for(k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++)
                    if((b[k][j]|32)!='p')
                        b[k][j]=e;
            }
        }else
            b[u][y]=p;
        i="";
        for(j=0;j<8;j++){
            z=0;
            for(k=0;k<8;k++){
                if(b[j][k]==e)
                    z++;
                else {
                    if(z>0){
                        i+=z;
                        z=0;
                    }
                    i+=b[j][k];
                }
            }
            if(z>0)
                i+=z;
            i+=j!=7?"/":"";
        }
        System.out.print(i);
    }
}

```

**Old**

```
class E{public static void main(String[]a){String m,i="rnbqk1nr/1pp5/p2pp1pp/5p2/1bN5/2P1PQ1N/PP1P1PPP/R1B1KB1R";m="f3b7";char[]n=m.toCharArray();int z,w,y,u=56-n[3];z=n[0]-97;w=56-n[1];y=n[2]-97;char e='e';char[][]b=new char[8][8];String[]r=i.split("/");for(int j=0;j<8;j++){int o=0;for(int k=0;k<r[j].length();k++){char q=r[j].charAt(k);if(Character.isDigit(q)){for(int l=k+o;l<k+o+q-48;l++){b[j][l]=e;}o+=q-49;}else b[j][k+o]=q;}}char q,p=b[w][z];q=b[u][y];b[w][z]=e;if(q==e){if((p|32)=='p'&&(w-u<0?u-w:w-u)==1&&(z-y<0?y-z:z-y)==1){b[w][y]=e;for(int j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){for(int k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++){if((b[k][j]|32)!='p')b[k][j]=e;}}}else{b[u][y]=p;}}else{b[u][y]=e;for(int j=y-(y==0?0:1);j<y+(y==8?0:y==7?1:2);j++){for(int k=u-(u==0?0:1);k<u+(u==8?0:u==7?1:2);k++){if((b[k][j]|32)!='p')b[k][j]=e;}}}i="";for(int j=0;j<8;j++){int x=0;for(int k=0;k<8;k++){if(b[j][k]==e)x++;else{if(x>0){i+=x;x=0;}i+=b[j][k];}}if(x>0)i+=x;i+=j!=7?"/":"";}System.out.println(i);}}

```
> 2 votes

---
Tags: code-golf, chess
---


# Question
Title: increment a binary number without arithmetic manipulations
**Input:** binary string

**Output:** binary string that represents the binary input + 1

**Example:** Given `10111` as an input, output `11000`

**Limitations:** Can't use arithmetic operators or functions (like `+ - * /`)

**Criterion:** code-golf, the shortest code wins the big imaginary award.

# Answer
> 2 votes
# GNU sed \<4.3, ~~49 46 44 34~~ 30 bytes

```
s/.*/0&M/ # prepend 0 and append mark
: # label
s/0M/1/ # 0 incremented is 1
s/1M/M0/ # 1 incremented is 0 and the one to the left is incremented
t # if anything just changed, repeat until it doesn't (the M has disappeared)

```

(comments and all whitespace other that newlines are just for explanation)

This takes any amount of newline-separated binary numbers and increments each, it might give a number with leading 0s.

try it online

# Answer
> 2 votes
# Perl 5, 38 bytes

```
s/0$/1/||s/0?(1+)$/1 .(0 x length$1)/e

```

Try it online!

Basically: If(last digit is zero){ change it to 1} else {change the last consecutive 1's (with possibly a 0 ahead of them) with a 1 and a count of zeros that is the same number as the number of 1's matched at the end of the line.

Example input lines: 00000 00001 00111 1000 1011 111 1

Example output lines: 00001 00010 01000 1001 1100 1000 10

# Perl 5, 37 bytes

Or one less byte with this if it's ok to not preserve leading 0's (i.e. `0001``10`)

```
printf"%b\n",length 1 .(1x oct"0b$_")

```

Try it online!

---
Tags: code-golf, string, arithmetic, binary
---


title: Kill The Dragon!

text:
# Question
Title: Kill The Dragon!
John, a knight wants to kill a dragon to escape the castle! The dragon has `A` heads and `B` tails.

He knows, that:

* if you cut off one tail, two new tails grow
* if you cut off two tails, one new head grows
* if you cut off one head, one new tail grows
* if you cut off two heads, nothing grows

To defeat the dragon, John needs to cut off all his heads and all his tails. Help the knight to do this by making no more than 1000 strikes.

**Input**

The input contains two integers A and B (1 ≤ A, B ≤ 100).

**Output**

Print the sequence of strikes in the order in which they should be performed by encoding them with the following combinations of letters: `T` (one tail), `TT` (two tails), `H` (one head), `HH` (two heads) in the most optimal order.

**Example**

```
3 1

T
TT
HH
HH

```

The winning condition is the least number of bytes!

UPDATE: Bounty on offer for answers with Python

# Answer
# JavaScript (ES6),  ~~136~~  134 bytes

Takes input as `(heads)(tails)`. Naive brute force search.

```
h=>F=(t,x=0)=>(g=(h,t,p=[],i=-6)=>h|t?h<0|t<0||p[x]?0:['HH','H','T','TT'].some(m=>g(h+i+4,i++%5%4-~t,[...p,m]))&&P:P=p)(h,t)||F(t,x+1)

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~122~~ ~~121~~ 117 bytes

```
def f(a,b):x=a+b/2;b+=1;return b%2*x%2and['H']+a%2*['TT']+f(a-~a%2,b-a%2*2)or~b%2*['HT'[x%2]]+b/2*['TT']+-~x/2*['HH']

```

Try it online!
> 5 votes

# Answer
# Python 2, 121 bytes

Outputs to stderr, tries all possible sequences until the first one succeeds.

```
r=[([],)+input()]
for s,h,t in r:h==t==0>exit(s);r+=[(s+['HT'[i/9]*(2-i%2)],h+i/4-2,t+i%4-2)for i in 11,12,7,2 if h>-1<t]

```

Try it online!

I don't think the `if h>-1<t` part is necessary, without it it would be 111 bytes.
> 4 votes

# Answer
# Jelly, 71 bytes

```
⁴HḞ
“TT¶”ẋ¢
³ḂḤ⁴+
“H¶TT¶“H¶H¶TT¶“T¶TT¶“”¢ị
Ø+ŻUŻ3£ị+1£+³H
“HH¶”ẋ¢
2£4£¢

```

Try it online!

I'm quite new to Jelly, so this is not optimal, but here's my explanation:

```
                         (1st link)
⁴                        starting number of tails
 H                       halved
  Ḟ                      and floored

                         (2nd link)
“TT¶”                    take the string "TT\n"
     ẋ¢                  and repeat it (last link) amount of times

                         (3rd link)
³                        starting number of heads
 Ḃ                       mod 2
  Ḥ                      doubled
    +                    plus
   ⁴                     starting number of tails

                         (4th link)
“H¶TT¶“H¶H¶TT¶“T¶TT¶“”   array of actions
                      ¢  based on the last link
                       ị get the (n % len(array))th element

                         (5th link)
Ø+                       [1, -1]
  Ż                      prepend 0 ([0, 1, -1])
   U                     reverse the array ([-1, 1, 0])
    Ż                    prepend 0 ([0, -1, 1, 0])
       ị                 index
     3£                  of the 3rd link
        +                plus
         1£              1st link
             +           plus
           ³H            half the number of heads

                         (6th link)
“HH¶”                    take the string "HH\n"
     ẋ¢                  repeat it (last link) amount of times

                         (Main link)
2£                       2nd link
  4£                     4th link
    ¢                    last link

```
> 4 votes

# Answer
## Batch, 201 bytes

```
@set/aa=%1,b=%2,c=(b+a+a)%%4
@if %1%c%==12 echo TT&set/ab-=a=c=2
@if %c%==3 echo T&set/ab+=1,c=0
@set/ab+=c,a+=b/2-c,c+=c
@for %%v in (%c%.H %b%.TT %a%.HH)do @for /l %%i in (2,2,%%~nv)do @echo%%~xv

```

Works by directly calculating the number of `H`, `TT` and `HH` strikes required. This handles all cases except where \\$2a+b\equiv3\pmod4\\$ (which requires an initial `T`) and the case \\$a=1,b=4k\\$ (which requires an initial `TT`). Edit: Fixed second special case for \\$k\>1\\$.
> 4 votes

# Answer
# Java 8, ~~194~~ ~~167~~ ~~164~~ ~~163~~ ~~140~~ 135 bytes

```
(h,t)->{for(;t>-h;)System.out.println(t+h%2<1&&h>(h-=2)?"HH":h<1&t%4<3|t%4==h%2*2&&h<++h&t>(t-=2)?"TT":t++%4!=3-h%2*2&&h>--h?"H":"T");}

```

-51 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

I first tried all possible cases by hand:

```
Heads     Tails        Steps

1 (odd)   5 (%4==1)    1,5 → T(1,6) TT(2,4) TT(3,2) TT(4,0) HH(2,0) HH(0,0)
1 (odd)   6 (%4==2)    1,6 → see above after first step

2 (even)  6 (%4==2)    2,6 → H(1,7) H(0,8) TT(1,6) TT(2,4) TT(3,2) TT(4,0) HH(2,0) HH(0,0)
1 (odd)   7 (%4==3)    1,7 → see above after first step

3 (odd)   8 (%4==0)    3,8 → H(2,9) H(1,10) TT(2,8) TT(3,6) TT(4,4) TT(5,2) TT(6,0) HH(4,0) HH(2,0) HH(0,0)
2 (even)  9 (%4==1)    2,9 → see above after first step

2 (even)  7 (%4==3)    2,7 → T(2,8) TT(3,6) TT(4,4) TT(5,2) TT(6,0) HH(4,0) HH(2,0) HH(0,0)
2 (even)  8 (%4==0)    2,8 → see above after first step

0 (zero)  6 (%4==2)    0,6 → TT(1,4) H(0,5) TT(1,3) H(0,4) TT(1,2) TT(2,0) HH(0,0)
0 (zero)  5 (%4==1)    0,5 → see above after second step
0 (zero)  4 (%4==0)    0,4 → see above after fourth step

0 (zero)  7 (%4==3)    0,7 → T(0,8) TT(1,6) TT(2,4) TT(3,2) TT(4,0) HH(2,0) HH(0,0)

5 (odd)   0 (zero)     5,0 → H(4,1) H(3,2) TT(4,0) HH(2,0) HH(0,)
4 (even)  0 (zero)     4,0 → see above after third step

```

After that I knew the first moves for every possibility. Which I displayed here in table form:

```
      | 0   %4==0    %4==1    %4==2    %4==3  < Tails
------|-------------------------------------
0     | -   TT       TT       TT       T
%2==0 | HH  TT       H        H        T
%2==1 | H   H        T        TT       H
  ^
Heads

```

As for my code:

```
(h,t)->{                // Method with two integer parameters and String return-type
  for(;t>-h;)           //  Loop until both the amount of heads and tails are 0:
    System.out.println( //   Print with trailing newline:
      t+h%2<1&&         //    If there are 0 tails and an even amount of heads:
        h>(h-=2)?       //     Decrease the amount of heads by 2
        "HH"            //     And print "HH"
      :h<1&t%4<3        //    Else if there are 0 heads and tails modulo 4 is 0, 1, or 2
       |t%4==h%2*2&&    //    Or there is an even amount of heads and tails modulo 4 is 0
                        //    Or there is an odd amount of heads and tails modulo 4 is 2:
        h<++h&          //     Increase the amount of heads by 1
        t>(t-=2)?       //     Decrease the amount of tails by 2
        "TT"            //     And print "TT"
      :t++%4!=3-h%2*2&& //    Else-if there are an odd amount of heads and tails modulo-4 is NOT 1
                        //    Or there are an even amount of heads and tails modulo-4 is NOT 3:
                        //    (and increase `t` by 1 with `t++` right after this check)
        h>--h?          //     Decrease the amount of heads by 1
        "H"             //     And print "H"
      :                 //    Else:
        "T");}          //     Print "T"

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~104~~ ~~91~~ 77 bytes

-14 bytes thanks to @att

```
Table@@@Join[{H,b=1-#~Mod~2},{T,q=Mod[2-#2-b,4]},{TT,n=(#2+q)/2},HH|(#+n)/2]&

```

Try it online!

A 74 byte version, but can't be run in TIO, as it fakes Put. Put is the only valid operator with a higher precedence than Set, so it can be used in place of List in each pair, save a byte over each.

```
Table@@@Join[H>>b=1-#~Mod~2,T>>q=Mod[2-#2-b,4],TT>>n=(#2+q)/2,HH|(#+n)/2]&

```
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~91~~ 79 bytes

*Saved 1 byte thanks to @ovs*

```
{⍺=-⍵:⍬⋄⍵>1:'TT ',(⍺+1)∇⍵-2⋄3=⍺+⍵:'H ',(⍺-1)∇⍵+1⋄1=⍺⌈⍵:'T ',⍺∇⍵+1⋄'HH ',⍵∇⍨⍺-2}

```

Try it online!

Here is my "research." The x-axis is heads, y-axis is tails. Each cell contains the minimum number of moves to get to (0, 0), and the optimal move(s) you can make from there.

There are multiple ways you can divide it up, but I am going to hold `t>=2` to be one section (TT); (2, 1) and (3, 0) to be another (H); (1, 0), (0, 1), and (1, 1) to be another (T), and the rest to be HH.

The first case is if the dragon has no heads or tails (`h==-t`), in which case we return the empty set ().

As you can see, the optimal move if the dragon has 2 or more tails is a double tail-chop, and that is our second case. We prepend `'TT '` to the result of calling the function again with one more head and two less tails.  refers to the current function,  is heads, and  is tails.

The third case is the single head chop. The only two times when the only option available is `H` is at (3,0) and (2,1). Our condition here is that `h+t` is 3 (this condition is also met with (1,2) and (0,3), but those were covered in the second case).

The third case is the single tail chop. Only one square requires it - (1, 1), so we check if the maximum of `h` and `t` is 1.

The last case doesn't need any condition checking, so we can go ahead and decapitate the dragon twice.
> 3 votes

# Answer
# 05AB1E, ~~75~~ 71 bytes

```
[UVXY+_#XÈY_*i„HHYXÍëY4%©X_i3‹ëXÈi_ë2Q}}i„TTYÍX>ë®XÈi3Q}i'TY>Xë'HY>X<]»

```

Port of my Java answer. Can definitely be golfed, though (probably by using a different approach all-together more suitable to 05AB1E..)

Try it online or verify some more test cases.

**Explanation:**

```
[                  # Start an infinite loop:
 U                 #  Pop and save the top of the stack (or the first (implicit) input
                   #  in the first iteration) in variable `X` (the heads)
 V                 #  Pop and save the top of the stack (or the second (implicit) input
                   #  in the first iteration) in variable `Y` (the tails)
 XY+_              #  If the amount of heads and tails are both 0:
     #             #   Stop the infinite loop
 XÈ   i            #  If there is an even amount of heads
   Y_*             #  and there are 0 tails:
       „HH         #   Push "HH" to the stack
       Y           #   Leave `Y` the same
       XÍ          #   Decrease `X` by 2
 ë                 #  Else:
  Y4%              #   Push tails modulo-4 to the stack
     ©             #   (and add it to the register without popping as well)
      X_i          #   If there are 0 heads:
         3‹        #    Check if tails modulo-4 is 0, 1, or 2
      ëXÈi         #   Else-if there are an even amount of heads (but not 0)
          _        #    Check if tails modulo-4 is 0
      ë            #   Else (there are an odd amount of heads)
       2Q          #    Check if tails modulo-4 is 2
           }}i     #   And if it is truthy:
              „TT  #    Push "TT" to the stack
              YÍ   #    Decrease `Y` by 2
              X>   #    Increase `X` by 1
 ë                 #   Else:
  ®                #    Push tails modulo-4 to the stack again (from the register)
   XÈi             #    If there are an even amount of heads:
      3Q           #     Check if tails modulo-4 is 3
        }i         #    If this is truthy or tails modulo-4 is 1:
          'T      '#     Push "T" to the stack
          Y>       #     Increase `Y` by 1
          X        #     Leave `X` the same
 ë                 #    Else:
  'H              '#     Push "H" to the stack
  Y>               #     Increase `Y` by 1
  X<               #     Decrease `X` by 1
]                  # After all if-else statements and the loop:
 »                 # Join everything on the stack by newlines
                   # (which is output implicitly as result)

```
> 1 votes

# Answer
# Scala, ~~154~~ 147 bytes

```
a=>b=>{var(h,t,s)=(a,b,"")
while(-t<h)s+=(if(t>1){h+=1;t-=2
"TT "}else if(3==h+t){h-=1;t+=1
"H "}else if(2>h.max(t)){t+=1
"T "}else{h-=2
"HH "})
s}

```

Try it online!

Uses a completely different approach, but it's *still* longer than Java. :(

See my APL answer for an explanation.

### Previous solution, 182 bytes

```
h=>t=>{var m=Map(0->0->"")
while(!m.keySet(h->t)){for{g->s->p<-m
i->u->q<-Map(g+2->s->"HH",(g+1,s-1)->"H",(g,s-1)->"T",(g-1,s+2)->"TT")--m.keySet
if-1<i*u}m+=i->u->s"$q $p"}
m(h->t)}

```

Try it online!

Uses the pathfinding approach Lynn suggested in the comments.
> 1 votes

# Answer
# Python 3, 107 bytes

```
def f(a,b):return'TT '+f(a+1,b-2)if b>2else'HH '+f(a-2,b)if a>2else'H '+f(1,b+1)if a>1else'T TT HH'[2*b-2:]

```

Try it online!

The only way to reduce the tails is TT. You can safely do this as long as b \> 2.

You can also safely reduce heads by HH as long as a \> 2. I do this after reducing the tails, so it does not mix with TT operations.

When no more than 2 heads and tails are left, there are two cases:

1. a = 2: Cut off a head (H) then call recursively (with a = 1 now).
2. a = 1: Manually coded using a constant string.
> 1 votes

# Answer
# Java (JDK), 110 bytes

```
String f(int a,int b){return b>2?"TT "+f(a+1,b-2):a>2?"HH "+f(a-2,b):a>1?"H "+f(1,b+1):b>1?"TT HH":"T TT HH";}

```

Try it online!
> 1 votes

# Answer
# Perl 5, 102 bytes

```
sub f($a,$b){$b>2?"TT ".f($a+1,$b-2):$a>2?"HH ".f($a-2,$b):$a>1?"H ".f(1,$b+1):$b>1?"TT HH":"T TT HH"}

```

Try it online!

6 Chars less due to hint by Dom Hastings.
> 1 votes

---
Tags: code-golf
---


title: (Almost) Solve Fermat's Last Theorem

text:
# Question
Title: (Almost) Solve Fermat's Last Theorem
It's a well-known fact that Fermat's Last Theorem is true. More specifically, that for any integer \\$n \gt 2\\$, there are no three integers \\$a, b, c\\$ such that

$$a^n + b^n = c^n$$

However, there are a number of near misses. For example,

$$6^3 + 8^3 = 9^3 - 1$$

We'll call a triple of integers \\$(a, b, c)\\$ a "Fermat near-miss" if they satisfy

$$a^n + b^n = c^n \pm 1$$

for some integer \\$n \> 2\\$. Note that this includes negative values for \\$a, b, c\\$, so \\$(-1, 0, 0)\\$ is an example of such a triple for any \\$n\\$.

---

Your task is to take an integer \\$n \> 2\\$ as input, in any convenient method. You may then choose which of the following to do:

* Take a positive integer \\$m\\$ and output the \\$m\\$-th Fermat near-miss for that specific \\$n\\$
* Take a positive integer \\$m\\$ and output the first \\$m\\$ Fermat near-misses for that specific \\$n\\$
    + For either of these two, you may choose any ordering to define the "\\$m\\$th" or "first \\$m\\$" terms, so long as the ordering eventually includes all possible triples. For example, the test case generator program below orders them lexographically.
* Output all Fermat near-misses for that specific \\$n\\$
    + The output may be in any order, so long as it can be shown that all such triples will eventually be included. The output does not have to be unique, so repeated triples are allowed.
    + You may output in any format that allows for infinite output, such as an infinite list or just infinite output. You may choose the delimiters both in each triple and between each triple, so long as they are distinct and non-digital.

This is so the shortest code in bytes wins

---

This program was helpfully provided by Razetime which outputs all solutions with \\$|a|, |b|, |c| \le 50\\$ for a given input \\$n\\$\*.

This is a question asked over on MathOverflow about the existence of non-trivial solutions to

$$a^n + b^n = c^n \pm 1$$

Unfortunately, it appears (although is not proven, so you may not rely on this fact) that no non-trivial solutions exist for \\$n \ge 4\\$, so for most \\$n\\$, your output should be the same.

\*Currently, this also returns exact matches, which your program shouldn’t do.

# Answer
> 5 votes
# , ~~119~~ ~~110~~ ~~108~~ ~~105~~ 100 bytes

*Edit: -2 bytes thanks to Giuseppe*

```
n=scan();repeat for(b in -(F=-F+!(F>0)):F)for(i in (d=-(c=F^n+b^n):c)[abs(d^n-c)==1])cat(F,b,i,'\n')

```

Try it online!

Prints the infinite list of near-misses, without duplicates (this includes duplicates by re-ordering `a` and `b`, so the triples `(a,b,c)` and `(b,a,c)` are considered duplicates: add an extra `,b,F,i,'\n'` (11 bytes) to print the list *with* duplicates).
Wastes a few bytes avoiding taking nth-roots, to prevent floating-point errors.

**How?**

```
function(n){
                            # note: F (false), which represents variable a, is initialized to zero;
repeat{                     # repeat for ever:
 for(b in -F:F){            # try all possible values of b from -a to a,
  c=F^n+b^n                 # calculate c as a^n+b^n,
  c=(-c:c)                  # now find value in the range -c to c
  [(-c:c)^n%in%(c+c(1,-1))] # that gives either c+1 or c-1 when raised to the n-th power
                            # replace c with this value (if there is one),
  for(i in c)               # now, if there were any:
   print(c(F,b,i))}         # print out the a,b,c combination
 F=-F+!(F>0)}}              # update F to the next value of variable a, in the sequence:
                            # 0, 1, -1, 2, -2, 3, -3 ... and so on

```

# Answer
> 4 votes
# Stax, 20 bytes

```
ÜTCÑ ¢@∙╡·Gò╝╠Δh÷╠╧m

```

Run and debug it

This uses the fact that results need not be unique.

As with most of caird's challenges, you get brownie points for finding/outgolfing my 16 byte Husk solution :P

## Explanation

```
Wi:r3:${{x#mNs|+:-2<f|uP
W                        iterate forever
 i                       push current iteration index
  :r                     symmetric range (-n..n)
    3:$                  cartesian power of 3
       {            f    filter each triple by the following:
        {x#m             map each number to the power of input
            Ns           push the last element separately
              |+         sum the first two
                :-       absolute difference
                  1=     equals 1?
                     |u  stringify the result
                       P print with newline

```

# Answer
> 3 votes
# JavaScript (ES7), 124 bytes

Expects `(n)(m)` and returns the \\$m\\$-th solution (1-indexed).

```
n=>(a=b=c=1,g=m=>(t=[A,B,C]=[a=a<c+2?a+1:b<c+2?++b/b:b=++c/c,b,c].map(v=>(v>>1)*(v&1||-1)),A**n+B**n-C**n)**2-1||--m?g(m):t)

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~15~~ 13 bytes

```
∞εD(Ÿ3ãʒIm`+α

```

Looks for \\$\left\vert a^n+b^n−c^n\right\vert = 1\\$ (near-misses).
Inspired by *@Razetime*'s Stax answer. The program outputs an infinite list of lists of triplets in the order \\$\[c,b,a\]\\$ (including duplicated triplets) with only \\$n\\$ as input.

Try it online.

**Explanation:**

```
∞             # Push an infinite list of positive integers: [1,2,3,...]
 ε            # Map each integer y to:
  D(          #  Duplicate it, and negate the copy: -y
    Ÿ         #  Pop both, and push a list in that range: [y,...,-y]
     3ã       #  Create triplets of this list with the cartesian power
       ʒ      #  Filter this list of [c,b,a]-triplets by:
        Im    #   Take each value to the power of the input n: [c^n,b^n,a^n]
          `   #   Pop the list, and push the three values separated to the stack
           +  #   Add the top two together: b^n+a^n
            α #   Take the absolute difference: |c^n-a^n+b^n|
              #   (NOTE: only 1 is truthy in 05AB1E)
              # (after which the infinite list of lists of triplets is output implicitly)

```

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


title: What song is playing?

text:
# Question
Title: What song is playing?
Inspired by this xkcd

You work for Shazam and they have a project for you. Some customers are complaining about their app taking up too much space on their phone, so they want you to code a lite version of the app. Unfortunately, your existing code can only understand the word "na", and you have to ship soon. That's okay, we'll do the best with what we've got.

# The Challenge

You must write a full program that takes a user input, or takes a command line argument, and print the title and artist of the song. Since we are trying to fix customers complaining about program size, your code must be as short as possible. The input will be a string consisting entirely of na's, with a single space between them. Lowercase/uppercase is arbitrary. This is considered a valid input: `Na Na nA na NA` This is an invalid input: `nah nah NA naNa banana` You must determine what song is playing and print it out in exactly this format:

```
Song: <trackname>
Artist: <artist>

```

If the input is *exactly* 8 na's, this matches two separate songs, so you must print both:

```
Song: Batman Theme
Artist: Neal Hefti

```

and

```
Song: Na Na Hey Hey Kiss Him Goodbye
Artist: Steam

```

If the input is *exactly* 10 na's, you must print:

```
Song: Katamari Damacy
Artist: Yuu Miyake

```

If the input is *exactly* 11 na's, you must print:

```
Song: Hey Jude
Artist: The Beatles

```

If the input is 12 or more na's, you must print

```
Song: Land Of 1000 Dances
Artist: Wilson Pickett

```

Lastly, if the input is invalid, there are less than 8 na's, or any of the words are not "na", your program fails to understand the music. So logically, there is only one other song that it could possibly be. You must print:

```
Song: Africa
Artist: Toto

```

As usual, standard loopholes apply, and the shortest answer in bytes wins.

# Answer
> 7 votes
# Retina, 242

Try it online!

```
iG`^na( na)*$
iM`na
m`^8$
>Batman Theme,Neal Hefti$n>Na Na Hey Hey Kiss Him Goodbye,Steam
m`^10$
>Katamari Damacy,Yuu Miyake
m`^11$
>Hey Jude,The Beatles
[0-9].+
>Land Of 1000 Dances,Wilson Pickett
m`^[0-9]
>Africa,Toto
>
Song:
,
$nArtist:

```

# How it works:

IgnoreCase flag + Grep mode flag + Regex `^na( na)*$`. If the input is valid, print it as is. If not, print nothing.

```
iG`^na( na)*$

```

IgnoreCase flag + Match mode flag + Regex `na`. Count the "na"s and print the number.

```
iM`na

```

If the string is exactly "8", replace by the second line.

```
m`^8$
>Batman Theme,Neal Hefti$n>Na Na Hey Hey Kiss Him Goodbye,Steam

```

If the string is exactly "10", replace by the second line.

```
m`^10$
>Katamari Damacy,Yuu Miyake

```

If the string is exactly "11", replace by the second line.

```
m`^11$
>Hey Jude,The Beatles

```

If the string matches `[0-9].+`, replace by the second line. This is neither true for single digit numbers, `10` and `11` as they already have been repaced nor any of the above replacement strings.

```
[0-9].+
>Land Of 1000 Dances,Wilson Pickett

```

If none of the above matched, the string still starts with a number. Default to Toto, Africa.

```
m`^[0-9]
>Africa,Toto

```

Replace the placeholders `>` and `,` by `Song:` and `Artist:`.

```
>
Song:
,
$nArtist:

```

# Answer
> 5 votes
# JavaScript (ES6), 276 bytes

```
alert(`Song: `+([,`Batman Theme,Neal Hefti
Song: Na Na Hey Hey Kiss Him Goodbye,Steam`,,`Katamari Damacy,Yuu Miyake`,`Hey Jude,The Beatles`,`Land Of 1000 Dances,Wilson Pickett`][+prompt(i=0).replace(/na( |$)/gi,_=>++i)&&(i>11?4:i-7)]||`Africa,Toto`).replace(/,/g,`
Artist: `))

```

## Explanation

Input can optionally contain one trailing space.

```
alert(                 // output the result
  `Song: `+([          // insert the "Song:" label
      ,                // set the first element to undefined in case input is empty

      // Songs
      `Batman Theme,Neal Hefti
Song: Na Na Hey Hey Kiss Him Goodbye,Steam`,
      ,
      `Katamari Damacy,Yuu Miyake`,
      `Hey Jude,The Beatles`,
      `Land Of 1000 Dances,Wilson Pickett`

    ][
      +                // if the input string was made up only of "na"s, the replace would
                       //     return a string containing only digits, making this return a
                       //     number (true), but if not, this would return NaN (false)
        prompt(        // get the input string
          i=0          // i = number of "na"s in input string
        ).replace(     // replace each "na" with a number
          /na( |$)/gi, // find each "na"
          _=>++i       // keep count of the "na"s and replace with a (non-zero) number
        )
      &&(i>11?4:i-7)   // select the song based on the number of "na"s
    ]
      ||`Africa,Toto`  // default to Africa
  ).replace(/,/g,`
Artist: `)             // insert the "Artist:" label
)

```

## Test

```
var prompt = () => input.value;
var alert = (text) => result.textContent = text;
var solution = () => {

alert(`Song: `+([,`Batman Theme,Neal Hefti
Song: Na Na Hey Hey Kiss Him Goodbye,Steam`,,`Katamari Damacy,Yuu Miyake`,`Hey Jude,The Beatles`,`Land Of 1000 Dances,Wilson Pickett`][+prompt(i=0).replace(/na( |$)/gi,_=>++i)&&(i>11?4:i-7)]||`Africa,Toto`).replace(/,/g,`
Artist: `))

}
```

```
<input type="text" id="input" value="na na Na na NA na na nA" />
<button onclick="solution()">Go</button>
<pre id="result"></pre>
```

# Answer
> 4 votes
# PowerShell, 278 bytes

* Can handle any amount of whitespace
* No regex whatsoever!
* Implicit typecasting FTW!

```
@{8='Batman Theme/Neal Hefti','Na Na Hey Hey Kiss Him Goodbye/Steam'
10='Katamari Damacy/Yuu Miyake'
11='Hey Jude/The Beatles'
12='Land Of 1000 Dances/Wilson Pickett'}[[math]::Min($args.Count*!($args|?{$_-ne'na'}),12)]|%{'Song: {0}
Artist: {1}'-f($_+'Africa/Toto'*!$_-split'/')}

```

# Ungolfed

```
@{8='Batman Theme/Neal Hefti','Na Na Hey Hey Kiss Him Goodbye/Steam' # array
10='Katamari Damacy/Yuu Miyake'
11='Hey Jude/The Beatles'
12='Land Of 1000 Dances/Wilson Pickett'} # Hashtable of songs
[   # Get value by key from hashtable
    # If key is invalid, silently return null value

    [math]::Min( # Clamp max value to 12
        $args.Count* # Multiply count of argumens
                     # true/false will be cast to 1/0
            ! # Negate result of expression
              # Will cast empty array to 'false'
              # and non-empty array to 'true'
            (
                # Return non-empty array if input arguments
                # contain anything other than 'na'
                $args | Where-Object {$_ -ne 'na'}
            ),
        12
    )
] | ForEach-Object { # Send value from hashtable down the pipeline,
                     # This allows to process arrays in hasthable values
    'Song: {0}
    Artist: {1}' -f ( # Format string
        $_+ # Add to current pipeline variable
            'Africa/Toto'*!$_ # If pipeline variable is empty,
                              # then add default song to it
                              # Example: 'Test'*1 = 'Test'
                              #          'Test'*0 = null
        -split '/' # Split string to array for Format operator
    )
}

```

# Usage

```
PS > .\WhatSong.ps1 na na na na na na na na
Song: Batman Theme
Artist: Neal Hefti
Song: Na Na Hey Hey Kiss Him Goodbye
Artist: Steam

PS > .\WhatSong.ps1 Na na na na na na na na na Na
Song: Katamari Damacy
Artist: Yuu Miyake

PS > .\WhatSong.ps1 Na na na na na na na na na BanaNa
Song: Africa
Artist: Toto

```

# Answer
> 1 votes
# Python ~~453~~ ~~440~~ ~~406~~ 380 bytes

**EDIT:** Thanks to Cyoce for reducing 13 bytes!

**EDIT:** Thanks again to Cyoce!

**EDIT:** Thanks to RainerP. for helping me imrpove the algorithm on certain invalid cases.

This is a rough draft of a Python program. I believe it can be definitely golfed, maybe to 300-400 bytes. But will work on that soon.

```
f=0
S='Song:'
A='\nArtist:'
l="Batman Theme,Neal Hefti,Na Na Hey Kiss Him Goodbye,Steam,Katamari Damacy,Yuu Miyake,Hey Jude,Beatles,Land of the 1000 Dances,Wilson Pickett,Africa,Toto".split(',')
s=raw_input().lower()+" "
n=s.count("na ")
n*=n*3==len(s)
if n>11:f=8
if n==10:f=4
if n==11:f=6
if n<8or n==9:f=10
if f:print S+l[f]+A+l[f+1]
else:print S+l[0]+A+l[1]+"\n"+S+l[2]+A+l[3]

```

Try here!

# Answer
> 1 votes
# sh + coreutils, 290

Albeit longer than my other submission, this one is straightforward and pretty much ungolfed, so i included it anyway.

```
grep -Ei "^na( na)*$"|wc -w|awk '{s="Song: ";a="\nArtist: ";p=s"Africa"a"Toto"}$1==8{p=s"Batman Theme"a"Neal Hefti\n"s"Na Na Hey Hey Kiss Him Goodbye"a"Steam"}$1>9{p=s"Katamari Damacy"a"Yuu Miyake"}$1>10{p=s"Hey Jude"a"The Beatles"}$1>11{p=s"Land Of 1000 Dances"a"Wilson Pickett"}{print p}'

```

# How it works:

If the input is valid, print it as is. If not, print nothing.

```
grep -Ei "^na( na)*$"

```

Count the words.

```
wc -w

```

Simple look up table, `Song:` and `Artist:` are kept in variables.

```
awk '
    {s="Song: ";a="\nArtist: ";p=s"Africa"a"Toto"}
    $1==8{p=s"Batman Theme"a"Neal Hefti\n"s"Na Na Hey Hey Kiss Him Goodbye"a"Steam"}
    $1>9{p=s"Katamari Damacy"a"Yuu Miyake"}
    $1>10{p=s"Hey Jude"a"The Beatles"}
    $1>11{p=s"Land Of 1000 Dances"a"Wilson Pickett"}
    {print p}
'

```

# Answer
> 1 votes
# Julia, 325 bytes

Probably could be golfed further.

```
p(s,a)=println("Song: $s\nArtist: $a");ismatch(r"^(na )*na$",ARGS[1])&&(c=length(split(ARGS[1],"na"))-1)==8?(p("Batman Theme","Neal Hefti"),p("Na Na Hey Hey Kiss Him Goodbye","Steam")):c==10?p("Katamari Damacy","Yuu Miyake"):c==11?p("Hey Jude","The Beatles"):c>=12?p("Land Of 1000 Dances","Wilson Pickett"):p("Africa","Toto")

```

# Answer
> 1 votes
# C (gcc), ~~403~~ ~~395~~ ~~370~~ ~~365~~ ~~364~~ 362 bytes

-8 -5 -1 = -14 bytes thanks to ceilingcat

Pretty much as straight-forward as can be.

```
f(char*s){int*a[]={"Neal Hefti","Steam","Yuu Miyake","The Beatles","Wilson Pickett","Toto","Batman Theme","Na Na Hey Hey Kiss Him Goodbye","Katamari Damacy","Hey Jude","Land Of 1000 Dances","Africa"},i,l=0,j=1;for(;*s;s+=3-!s[2])i=(*s|32)^'n'|(s[1]|32)^97|s[2]>32,l++;for(i=i?5:l^8?l^10?l^11?l>11?4:5:3:2:j++;j--;)printf("Song: %s\nArtist: %s\n",a[6+i--],a[i]);}

```

Try it online!

# Answer
> 1 votes
# Rust, ~~501~~ 477 bytes

```
fn main(){let(mut i,mut n)=(String::new(),0);let(s,a);std::io::stdin().read_line(&mut i);i=i.trim().to_lowercase();let o=i.split(" ");for w in o{if w!="na"{n=0;break}else{n+=1}}match n{8=>{println!("Song: Batman Theme\nArtist: Neal Hefti");s="Na Na Hey Hey Kiss Him Goodbye";a="Steam"}10=>{s="Katamari Damacy";a="Yuu Miyake"}11=>{s="Hey Jude";a="The Beatles"}_=>{if n>=12{s="Land Of 1000 Dances";a="Wilson Pickett"}else{s="Africa";a="Toto"}}}print!("Song: {}\nArtist: {}",s,a)}

```

Ungolfed

```
fn main() {
    let (mut input_string, mut na_counter) = (String::new(), 0);
    let (song_name, artist_name);

    std::io::stdin().read_line(&mut input_string);
    input_string = input_string.trim().to_lowercase();
    let output = input_string.split(" ");

    for word in output {
        if word != "na" {
            na_counter = 0;
            break;
        } else {
            na_counter += 1;
        }
    }

    match na_counter {
        8 => {
            println!("Song: Batman Theme\nArtist: Neal Hefti");
            song_name = "Na Na Hey Hey Kiss Him Goodbye";
            artist_name = "Steam";
        }
        10 => {
            song_name = "Katamari Damacy";
            artist_name = "Yuu Miyake";
        }
        11 => {
            song_name = "Hey Jude";
            artist_name = "The Beatles";
        }
        _ => {
            if na_counter >= 12 {
                song_name = "Land Of 1000 Dances";
                artist_name = "Wilson Pickett";
            } else {
                song_name = "Africa";
                artist_name = "Toto";
            }
        }
    }

    print!("Song: {}\nArtist: {}", song_name, artist_name);
}

```

Edit: removed an unnecessary to\_string and type annotations

# Answer
> 1 votes
# Perl 5, ~~312~~ 292 bytes

```
$_=lc<>;$n="(na ?)";/^(na ){7}na$|(na ){9,}na/ or$_="%Africa&Toto";s/$n{12,}/%Land Of 1000 Dances&Wilson Pickett/;s/$n{11}/%Hey Jude&The Beatles/;s/$n{10}/%Katamari Damacy&Yuu Miyake/;s/$n{8}/%Batman Theme&Neal Hefti\n%Na Na Hey Hey Kiss Him Goodbye&Steam/;s/&/\nArtist: /g;s/%/Song: /g;print

```

Try it online!

Ungolfed:

```
$_ = lc <STDIN>;
$_ =~ /^(na ){7}na$|(na ){9,}na/ or $_ = "%Africa&Toto";
$_ =~ s/(na ?){12,}/%Land Of 1000 Dances&Wilson Pickett/;
$_ =~ s/(na ?){11}/%Hey Jude&The Beatles/;
$_ =~ s/(na ?){10}/%Katamari Damacy&Yuu Miyake/;
$_ =~ s/(na ?){8}/%Batman Theme&Neal Hefti\n%Na Na Hey Hey Kiss Him Goodbye&Steam/;
$_ =~ s/&/\nArtist: /g;
$_ =~ s/%/Song: /g;
print $_

```

# Answer
> 1 votes
# Perl 5 `-pa`, 248 bytes

```
$_=/^(na ?)+$/&&(@F==8?",Batman Theme;Neal Hefti,Na Na Hey Hey Kiss Him Goodbye;Steam":@F==10?"Katamari Damacy;Yuu Miyake":@F==11?",Hey Jude;The Beatles":@F>11?",Land Of 1000 Dances;Wilson Pickett":0)||",Africa;Toto";s/;/
Artist: /gm;s/,/
Song: /gm

```

Try it online!

# Answer
> 1 votes
# UNIX Shell, 394 bytes

```
uudecode -p<<<'begin-base64 0 -
/Td6WFoAAATm1rRGAgAhARwAAAAQz1jM4AE9AIRdACmbycaLOYv90Azj3HBohRZGa6a5FikeJU+8JbGlB4f9wmi2aQ+mn81aypMRM4nEKPxW439Z2C4WfGeyrREjk427H1GrCRUMHdth+9lVBDiPfCaD8WpStyS0MtJenHKB+tou8rD9INq0yw9IPXuQe7zLM3p14ZDFO8UoJp66scd4bKQAAACSwUb7ERvesgABoAG+AgAARAEAGbHEZ/sCAAAAAARZWg==
===='|unxz|sed -n $#s/,/\\n/gp|grep .||echo $'Song: Land Of 1000 Dances\nArtist: Wilson Pickett'

```

Test:

```
; sh $THE_FILE na na na na na na na
Song: Batman Theme
Artist: Neil Hefti

Song: Na Na Hey Kiss Him Goodbye
Artist: Steam

```

Probably could be optimized, but I just liked this idea TBH :)

# Answer
> 0 votes
# Java 8, 353 bytes

```
s->{int n=s.split(" ").length,b=s.matches("(na ?)+")?1:0;s="Africa";return"Song: "+(b>0?n<8?s:n<9?"Batman Theme\nArtist: Neal Hefti\nSong: Na Na Hey Hey Kiss Him Goodbye":n>11?"Land of 1000 Dances":n>10?"Hey Jude":n>9?"Katamari Damacy":"":s)+"\nArtist: "+(b>0?n<8?"Toto":n<9?"Steam":n>11?"Wilson Pickett":n>10?"The Beatles":n>9?"Yuu Miyake":"":"Toto");}

```

**Explanation:**

Try it online.

```
s->{                             // Method with String as both parameter and return-type
  int n=s.split(" ").length,     //  The amount of words when split by spaces
      b=s.matches("(na ?)+")?1:0;//  Whether the input matches the regex "^(na ?)+$"
  s="Africa";                    //  Set the input we no longer need to "Africa"
  return"Song: "                 //  Return "Song: "
    +(b>0?                       //   +If the input matched the regex:
       n<8?                      //     If there are less than 8 "na"'s:
        s                        //      Append "Africa"
       :n<9?                     //     Else-if there are exactly 8 "na"'s:
        "Batman Theme\nArtist: Neal Hefti\nSong: Na Na Hey Hey Kiss Him Goodbye"
                                 //      Append the String above
       :n>11?                    //     Else-if there are 12 or more "na"'s:
        "Land of 1000 Dances"    //      Append "Land of 1000 Dances"
       :n>10?                    //     Else-if there are exactly 11 "na"'s:
        "Hey Jude"               //      Append "Hey Jude"
       :n>9?                     //     Else-if there are exactly 10 "na"'s:
        "Katamari Damacy"        //      Append "Katamari Damacy"
       :                         //     Else (there are exactly 9 "na"'s):
        ""                       //      Append nothing
      :                          //    Else:
       s)                        //     Append "Africa"
    +"\nArtist: "                //   +Append a new-line and "Artist: "
    +(b>0?                       //   +If the input matched the regex:
       n<8?                      //     If there are less than 8 "na"'s:
        "Toto"                   //      Append "Toto"
       :n<9?                     //     Else-if there are exactly 8 "na"'s:
        "Steam"                  //      Append "Steam"
       :n>11?                    //     Else-if there are 12 or more "na"'s:
        "Wilson Pickett"         //      Append "Wilson Pickett"
       :n>10?                    //     Else-if there are exactly 11 "na"'s:
        "The Beatles"            //      Append "The Beatles"
       :n>9?                     //     Else-if there are exactly 10 "na"'s:
        "Yuu Miyake"             //      Append "Yuu Miyake"
       :                         //     Else (there are exactly 9 "na"'s):
        ""                       //      Append nothing
      :                          //    Else:
       "Toto");}                 //     Append "Toto"

```

# Answer
> 0 votes
# 05AB1E, 148 bytes

```
l#„naQW*O5Ý8+@OI5£“‹…0Toto
ßƒ›Ì0Neal Hefti0ÿ¤·¤··—„š‚¿bye0ÁÜ

KatamariÊÖacy0Yuu Miyake
¤· Jude0€€ÊÄ
ˆÑ€‚ 2–›s0¦‹šèett“¶¡0δ¡2₄:¬2ǝ„ŽŸŒá#ÞrèðδÛø„: ý»™

```

Try it online or verify some more test cases.

**Explanation:**

```
l            # Convert the (implicit) input-string to lowercase
 #           # Split it on spaces (if there are any)
  „naQ       # Check for each word if it's equal to "na" (1 if truthy; 0 if falsey)
      W      # Push its minimum, without popping the list itself
       *     # Multiply that to all integers
             # (if any word wasn't "na", the entire list now only contains 0s)
        O    # Sum this list to get the amount of "na"s
5Ý           # Push the list [0,1,2,3,4,5]
  8+         # Add 8 to each: [8,9,10,11,12,13]
    @        # Check for each if the sum is larger than or equal to this value
             # (1 if sum>=n, 0 if sum<n)
     O       # Sum to get the amount of truthy values
I            # Push the input-string
 5£          # Pop and only leave its first 5characters (if it's a valid string,
             # this will be "na na" - with variable casing)
   “‹…0Toto
    ßƒ›Ì0Neal Hefti0ÿ¤·¤··—„š‚¿bye0ÁÜ

    KatamariÊÖacy0Yuu Miyake
    ¤· Jude0€€ÊÄ
    ˆÑ€‚ 2–›s0¦‹šèett“
             # Push dictionary string "africa0 Toto\nbatman theme0Neal Hefti0ÿ hey hey kiss him goodbye0 steam\n\nKatamari damarcy0Yuu Miyake\nhey Jude0 the beatles\nland of 2 dances0 wilson pickett",
             # where the `ÿ` is automatically replaced with the 5-char string
¶¡           # Split this string on newlines
  0δ¡        # And then split each inner string on 0s
             #  [["africa"," Toto"],
             #   ["batman theme","Neal Hefti","na na hey hey kiss him goodbye"," steam"],
             #   [],
             #   ["Katamari damarcy","Yuu Miyake"],
             #   ["hey Jude"," the beatles"],
             #   ["land of 2 dances"," wilson pickett"]]
     2₄:     # Replace the 2 with 1000
        ¬    # Get the first pair (without popping): ["africa"," Toto"]
         2ǝ  # Insert it at (0-based) index 2, replacing the empty list
„ŽŸŒá        # Push dictionary string "song artist"
     #       # Split it on spaces: ["song","artist"]
      Þ      # Cycle this list infinitely: ["song","artist","song","artist",...]
r            # Reverse the values on the stack
 è           # Modulair 0-based index the sum of truthy values into the list of lists of
             # artist(s)/song(s), so 6 will wrap back to the first item
   δ         # Map over each string inside each inner list:
  ð Û        #  And trim all leading spaces
     ø       # Create pairs with the infinitely cycled list, where it will only create
             # as many pairs as the smallest list (so either 2 or 4 in this case)
      „: ý   # Join each inner pair with ": " delimiter
          »  # Then join everything by newlines
           ™ # And finally titlecase each word in the string
             # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“‹…0Toto ßƒ›Ì0Neal Hefti0ÿ¤·¤··—„š‚¿bye0ÁÜ\n\nKatamariÊÖacy0Yuu Miyake\n¤· Jude0€€ÊÄ\nˆÑ€‚ 2–›s0¦‹šèett“` is `"africa0 Toto\nbatman theme0Neal Hefti0ÿ hey hey kiss him goodbye0 steam\n\nKatamari damarcy0Yuu Miyake\nhey Jude0 the beatles\nland of 2 dances0 wilson pickett"` and `„ŽŸŒá` is `"song artist"`.

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