title: Average Two Letters

text:
# Question
Title: Average Two Letters
# Introduction

Every letter in the English alphabet can be represented as an ASCII code. For example, `a` is `97`, and `S` is `83`. As we all know, the formula for averaging two numbers \\$x\\$ and \\$y\\$ is \\$\frac{x+y}{2}\\$. I'm pretty sure you can see where this is going. Your challenge is to average two letters.

# Challenge

Your program must take two letters as input, and output the average of the ASCII values in it. If the average is a decimal, you should truncate it.

* Input will always be two ASCII letters. You can assume they will always be valid, but the case may vary. Basically, both letters will be in the range `97-122` or `65-90`. The second letter will always have a greater ASCII value than the first. If your language has no method of input, you may take input from command line arguments or from a variable.
* You must output the ASCII character signified by the average of the two numbers. As stated above, it should always be truncated to `0` decimal places. If your language has no method of output, you may store it in a variable. Exit codes and return values are considered valid output methods.

# Example I/O

* `Input: A, C`
`Output: B`
* `Input: a, z`
`Output: m`
* `Input: d, j`
`Output: g`
* `Input: B, e`
`Output: S`
* `Input: Z, a`
`Output: ]`

# Rules

This is , so shortest answer in bytes wins!

# Answer
> 9 votes
# C# (Visual C# Interactive Compiler), 20 bytes

```
a=>b=>(char)(a+b>>1)

```

Try it online!

# Answer
> 8 votes
# x86-16 machine code, IBM PC DOS, ~~13~~ ~~12~~ 10 bytes

Binary (xxd):

```
00000000: a182 0002 c4d0 e8cd 29c3            ..........

```

Listing:

```
A1 0082     MOV  AX, [0082H]    ; load two chars into AH and AL from command line
02 C4       ADD  AL, AH         ; AL = AL + AH
D0 E8       SHR  AL, 1          ; AL = AL / 2
CD 29       INT  29H            ; write to console
C3          RET                 ; return to DOS

```

Standalone PC DOS executable. Input is via command line, output to console.

Example:

# Answer
> 7 votes
# Jelly, 4 bytes

```
OSHỌ

```

Try it online!

# Explanation

```
OSHỌ  Main Link: takes (a, b)
O     (ord(a), ord(b))
 S    sum; ord(a) + ord(b)
  H   halve; (ord(a) + ord(b)) / 2
   Ọ  chr

```

# Answer
> 7 votes
# Poetic, 163 bytes

```
software inside a computer
a robot+a man+a keypad+a plan=a PC
still,P.C.this,P.C.that?i await a day i crush a PC
resist P.C,Google,or an Apple
i do Linux,i suppose

```

Try it online!

Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.

(I actually use PC myself. )

# Answer
> 6 votes
# , 17 bytes

```
(+/<.@%#)&.(3&u:)

```

Try it online!

* `(+/<.@%#)` truncated average...
* `&.` "Under", which applies a transform, then the verb it modifies -- truncated avg in this case -- then the inverse transform....
* `3&u:` convert to ascii byte integer.

That is, it converts each letter to its ascii number, gets the truncated average of those, and applies the inverse of "convert to ascii number", which takes an ascii number and returns a letter.

# Answer
> 6 votes
# , ~~56~~ 37 bytes

```
intToUtf8(mean(utf8ToInt(scan(,""))))

```

Try it online!

**Description**

* `intToUtf8()` converts the average into its ASCII character.
* `mean()` takes the average which is automatically truncated.
* `utf8ToInt()` converts the inputs into two ASCII numbers.
* `scan()` allows inputs.

# Answer
> 6 votes
# Ruby, 22 bytes

```
->a,b{""<<(a+b).sum/2}

```

Try it online!

# Answer
> 5 votes
# Keg `-ir` `-oc`, ~~5~~ 2 bytes (SBCS)

Works in all 3 test cases.

Try it online!

# Explanation

<pre><code>-ir will *not* try to evaluate the input
+   Add them
 ½  Halve the value
-oc Output all as a character, if possible

Implicit print. The output is print nice by default.
```
</code></pre>

# Answer
> 5 votes
# K (oK), 8 bytes

**Solution:**

```
`c$.5*+/

```

Try it online!

**Explanation:**

Sum, multiply by 0.5 and convert to ASCII.

```
`c$.5*+/ / the solution
      +/ / sum (add-over)
   .5*   / multiply by 0.5
`c$      / convert to ASCII

```

# Answer
> 5 votes
# Bash, 56 bytes

```
printf \\x$(printf %x $[`printf "(%d+%d)/2" \'$1 \'$2`])

```

Try it online!

# Answer
> 5 votes
# Shakespeare Programming Language, 144 bytes

Try it online!

(Whitespace added for readability)

```
/.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]
Ajax:Open mind.
Puck:Open mind.
You is the quotient betweenthe sum ofyou I a big cat.
Speak thy.

```

Simple enough, just finds the average. ASCII characters and numbers are identical in SPL, so this language was ideal for the task.

# Answer
> 4 votes
# dzaima/APL, 11 bytes

```
(+/÷≢)⍢⎕UCS

```

Try it online! dzaima/APLs `⎕UCS` \- convert to/from char currently ignores the fractional part of the given number, so no floor is necessary.

# Answer
> 4 votes
# Befunge-98 (PyFunge), 7 bytes

```
~~+2/,@

```

Try it online!

# Answer
> 4 votes
# Python 2, 31 bytes

```
lambda*A:chr(sum(map(ord,A))/2)

```

Try it online!

# Answer
> 4 votes
# Lua, ~~42~~ 41 bytes

```
a=...print(a.char(a:byte()+a:byte(2)>>1))

```

Try it online!

Removed 1 byte using ouflak's method of taking input as a single command line argument.

Takes input as a single command line argument of two characters. Uses the convenient operator precedence of `>>`.

Note that this is actually a full standalone Lua 5.3 program, because command line arguments are accessible as a top-level vararg.

# Answer
> 4 votes
# jq, 23 characters

```
[explode|add/2]|implode

```

Sample run:

```
bash-5.0$ jq -Rr '[explode|add/2]|implode' <<< 'AC'
B

```

Try it online!

# Answer
> 4 votes
# Excel, 28 bytes

```
=CHAR((CODE(A1)+CODE(B1))/2)

```

# Answer
> 4 votes
# Julia 1.0, 26 bytes

```
a\b=Char(sum(Int[a,b])÷2)

```

TIO was timing out for me, so only tested at REPL.

Try it online!

# Answer
> 4 votes
# Preproc, 1187 bytes

```
#define A
#define B,
#define C,,
#define D,C
#define E,D
#define F,E
#define G,F
#define H,G
#define I,H
#define J,I
#define K,J
#define L,K
#define M,L
#define N,M
#define O,N
#define P,O
#define Q,P
#define R,Q
#define S,R
#define T,S
#define U,T
#define V,U
#define W,V
#define X,W
#define Y,X
#define Z,Y
#define a Z H
#define b,a
#define c,b
#define d,c
#define e,d
#define f,e
#define g,f
#define h,g
#define i,h
#define j,i
#define k,j
#define l,k
#define m,l
#define n,m
#define o,n
#define p,o
#define q,p
#define r,q
#define s,r
#define t,s
#define u,t
#define v,u
#define w,v
#define x,w
#define y,x
#define z,y
#define _(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,cb,cc,cd,ce,cf,cg,ch,ci,cj,ck,cl,cm,cn,co,cp,cq,cr,cs,ct,cu,cv,cw,cx,cy,cz,da,db,dc,dd,de,df,dg,dh,di,dj,dk,dl,dm,dn,do,dp,dq,dr,ds,dt,du,dv,dw,dx,dy,dz,ea,eb,ec,ed,ee,ef,eg,eh,ei,ej,$,...)#$
#define $($a,$b)_($a $b z,y,y,x,x,w,w,v,v,u,u,t,t,s,s,r,r,q,q,p,p,o,o,n,n,m,m,l,l,k,k,j,j,i,i,h,h,g,g,f,f,e,e,d,d,c,c,b,b,a,a,`,`,_,_,^,^,],],\\,\\,[,[,Z,Z,Y,Y,X,X,W,W,V,V,U,U,T,T,S,S,R,R,Q,Q,P,P,O,O,N,N,M,M,L,L,K,K,J,J,I,I,H,H,G,G,F,F,E,E,D,D,C,C,B,B,A,A)

```

Try it online!

Defines a macro `$` which can be called (as shown in the footer of the TIO link above)

This challenge is barely possible in preproc (pure macro) -- if the input can be non-alphanumeric characters too, it would not be possible.

I don't see any simple way to shorten this code -- it might be possible to make the part to take the (n)th element shorter, but that would come at the cost of making the initial macro definitions significantly longer.

# Answer
> 3 votes
# Python 2, ~~33~~ 32 bytes

<sup><sup>-1B from Embodiment of Ignorance using bit ops. </sup></sup>

Exactly as specified. For a Python 3 answer change the `/` into `//`.

```
lambda a,b:chr(ord(a)+ord(b)>>1)

```

Try it online!

# Answer
> 3 votes
# Lua, ~~63~~ 60 bytes

```
s=io.read()print(s.char(math.floor((s:byte()+s:byte(2))/2)))

```

Takes the two letters with no delimeters, i.e. `AB`, `j$`, `|1`, etc....

Try it online!

*Saved 3 bytes thanks to PhillipRoman*

# Answer
> 3 votes
# Zsh, ~~33~~ 31 characters

```
a=({$1..$2} 0)
echo ${a[$#a/2]}

```

This one does no character code conversion.

Sample run:

```
manatwork ~ % set -- A C

manatwork ~ % a=({$1..$2} 0);echo ${a[$#a/2]}
B

```

Try it online!

# Answer
> 3 votes
# K4, ~~9~~ 8 bytes

**Solution:**

```
10h$_avg

```

**Examples:**

```
q)k)10h$_avg"AC"
"B"
q)k)10h$_avg"az"
"m"
q)k)10h$_avg"dj"
"g"

```

**Explanation:**

~~Unfortunately the space is needed.~~ Turns out the space isn't necessary!

```
10h$_avg / the solution
     avg / calculate mean
    _    / floor
10h$     / cast to char

```

**Bonus:**

* `10h$-256+avg` for a 12 byte Q version (more/less hacky than `10h$(_)avg` for 10)

# Answer
> 3 votes
# MarioLANG, 63 bytes

```
,
)
,
>[!(>[!
"=#="=#
  - ( >
) ( + -
!+< ) [
#=" !-<)
    #=".

```

Try it online!

Super golfable, I'm sure - not really able to think in MarioLANG yet. Calculates \\$\lfloor\frac{x+y}{2}\rfloor\\$.

# Answer
> 3 votes
# Forth (gforth), 15 bytes

```
: f + 2/ emit ;

```

Try it online!

### Code Explanation

```
: f      \ start a new word definition
  +      \ add top two stack arguments
  2/     \ divide top stack value by 2
  emit   \ output char of resulting ascii value
;        \ end word definition

```

# Answer
> 3 votes
# Hexagony, ~~14~~ 13 bytes

```
|*;:2@+/',{,|

```

Try it online!

Linear control flow: `,{,'+{*2':;@`

I decide to plug it in the Hexagony brute forcer program, and it can't find a 12-byte program. At least for that specific linear code.

Other possible linear control flows:

```
,{,'+'2=':;@
,{,'+'2{=:;@
,},"+{*2':;@
,},"+'2=':;@
,},"+'2{=:;@
,{,'+{+2':;@

```

(none of them results in a 12-byte solution (there are only some non-halting 12-byte solutions); nevertheless, the brute force program has room for improvement.)

# Answer
> 3 votes
# Perl 5, ~~31~~ 30 bytes

```
$x+=ord for@ARGV;print chr$x>>1

```

Try it online!

Shortened to 30 bytes thanks to comment by Dadsdy

# Answer
> 2 votes
# Red, 18 bytes

```
func[a][average a]

```

Try it online!

Takes the input as a list of two letters.

If this is not acceptable:

# Red, 20 bytes

```
func[a b][a + b / 2]

```

Try it online!

# Answer
> 2 votes
# MATL, 3 bytes

```
Ymc

```

Try it online!

### Explanation

```
Ym   % Implicit input: string of two letters. Implicitly convert to ASCII, and take mean
c    % Implicitly round down, and convert to char
     % Implicit display

```

# Answer
> 2 votes
# Runic Enchantments, 7 bytes

```
ii+2,k@

```

Try it online!

Input is space sepatrated. Use invalid inputs at your own peril.

# Answer
> 2 votes
# PowerShell, 32 bytes

```
$args|%{$s+=+$_}
[char]($s-shr1)

```

Try it online!

# Answer
> 2 votes
# Pari/GP, 57 bytes

```
fun(x,y)=Strchr(floor((Vecsmall(x)[1]+Vecsmall(y)[1])/2))

```

Try it online!

**Description**

* `Vecsmall(x)[1]` gives the ASCII number of `x`.
* `Vecsmall(y)[1]` gives the ASCII number of `y`.
* `/2` gives the average.
* `floor()` truncates the average.
* `Strchr()` converts the average to its ASCII character.

# Answer
> 2 votes
# Ceylon (named function) ~~74 68 65 64~~ 60

Contrary to e.g. Java, in Ceylon you can't directly add characters (The compiler complains with `Left operand must be of summable type: Character is not a subtype of Summable`). Instead, we first need to convert it to an integer, and afterwards back to character. This gives 74 bytes:

```
Character c(Character x,Character y)=>((x.integer+y.integer)/2).character;

```

We can write this shorter by using the `.hash` attribute instead of the `.integer` attribute, which for characters turns out to have the same implementation (returning the Unicode value of a character). This is 68 bytes:

```
Character d(Character x,Character y)=>((x.hash+y.hash)/2).character;

```

A more ceylonic way of doing this is to use the fact that Character is a Enumerable type, and implements the `.neighbour` and `.offset` methods. The average has an offset from the smaller which is half as large as the offset of the larger to the smaller. This even turns out slightly smaller, with 65 bytes.

```
Character a(Character x,Character y)=>x.neighbour(y.offset(x)/2);

```

Unfortunately most of this is the declaration of the types. We can reduce this slightly by having the method take a sequence (tuple/pair) of two characters instead of both individually – this removes one parameter, but adds `[...]` several times, coming to 64 bytes:

```
Character b(Character[2]c)=>c[0].neighbour(c[1].offset(c[0])/2);

```

An alternative way of making the type declaration shorter is an alias declaration. This only is worthwile from 3 usages of `Character`, which we have here, reaching 60 bytes:

```
alias C=>Character;C e(C x,C y)=>x.neighbour(y.offset(x)/2);

```

(The `.hash` version with alias comes to 63 bytes.)

Try all the examples online

# Answer
> 2 votes
# PHP (7.4), 34 bytes

```
fn($a,$b)=>chr(ord($a)+ord($b)>>1)

```

Try it online!

# Answer
> 2 votes
# Wren, 67 bytes

There should be a Wren answer for every Lua answer.

```
Fn.new{|a|String.fromCodePoint((a.bytes.reduce{|a,i|a+i}/2).floor)}

```

Try it online!

# Answer
> 2 votes
# Javascript, 59 53 Bytes

`i=>String.fromCharCode(Buffer.from(i).reduce((t,v)=>t+v)/2)`

`i=>String.fromCharCode((b=Buffer.from(i))[0]+b[1]>>1)`

```
> f('ae')
'c'
> f('ab')
'a'
> f('ac')
'b'
> f('ad')
'b'
> f('ae')
'c'
> f('aZ')
']'
> f('Be')
'S'

```

Bonus (Sorry if off topic, I'm not sure if this is allowed and couldn't find anything with a quick check. Please advise if this is actually a viable answer or not), here is the first answer written as NodeJS REPL input (making use of tabs to complete partial names):

`i=>St .f h (Bu .f (i).reduce((t,v)=>t+v)/2)` (43 bytes)

Note tabs might be malformed by page formatting. Note pasting anything after the tab will suppress completion on some terminals.

# Answer
> 2 votes
# Whitespace, 45 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_char_from_STDIN][T  T   T   _Retrieve][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_char_from_STDIN][T  T   T   _Retrieve][T    S S S _Add][S S S T S N
_Push_2][T  S T S _Integer_divide][T    N
S S _Print_as_character]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation:**

Character inputs in Whitespace are always stored as unicode integers, so we don't have to do an explicit conversion manually. The program has the following pseudo-code:

```
int a = STDIN as character
int b = STDIN as character
int c = (a+b) integer-divided by 2
Print c as character to STDOUT

```

I also use the first input as a heap-address for the second input, since it's guaranteed to be non-negative. This saves a byte by using `SNS` (duplicate) twice instead of `SSSN` \+ `SNS` (push 0 and duplicate).

# Answer
> 2 votes
# brainfuck, 46 bytes

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

```

Try it online!

```
,>,                             Takes input into cells 0 and 1
[-<+>]                          Sums the two values, storing the result in cell 0
++<                             Sets cell 1 to 2, and returns to cell 0
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]  Divides cell 0 by cell 1
>>>.                            Moves to and outputs cell 3, where the quotient is stored

```

# Answer
> 2 votes
# (e)Lisp, 50 bytes

```
(insert (/ (+ (aref (read) 0) (aref (read) 0)) 2))

```

# Answer
> 2 votes
# CJam, 10 bytes

```
rcirci+2/c

```

Try it online!

# Answer
> 2 votes
# T-SQL, 64 bytes

```
declare @ char='Z',@2 char='a'print char((ascii(@)+ascii(@2))/2)

```

assuming `@` and `@2` the input.

37 bytes if only put:

```
print char((ascii('B')+ascii('C'))/2)

```

# Answer
> 2 votes
# T-SQL, 32 bytes

```
SELECT CHAR(AVG(ASCII(c)))FROM i

```

Input is taken via a pre-existing table \\$i\\$ with `CHAR(1)` column \\$c\\$, per our IO standards.

The two input characters are entered as separate rows. (Note that because SQL is set-based, this will calculate the average of an arbitrary number of inputs.)

# Answer
> 2 votes
# C (gcc), 22 bytes

Saved 0 bytes, but got a giggle, thanks to @ceilingcat!

```
(*c)()=L"\xd137048d쏸";

```

Try it online!

# Answer
> 2 votes
# PHP 7.3, ~~52~~ 51 bytes

-1 byte thanks to manatwork

```
$x=function($a,$b){echo chr((ord($a)+ord($b))/2);};

```

Try it online!

# Answer
> 2 votes
# shortC, ~~12~~ 8 bytes

```
APG+G>>1

```

Try it online!

Please advise on golfing skeeels.

# Answer
> 2 votes
# 1+, ~~25~~ 23 bytes

```
,,+11##1+"\"/^"+1+<1+#;

```

Try it online!

# Answer
> 2 votes
# Husk, 3 bytes

```
c½Σ

```

Try it online!

Input as a two character string.

# Answer
> 2 votes
# Zsh, 27 bytes

Not as original as @manatwork's solution, but shorter. Try it online!

```
<<<${(#)$(((##$1+##$2)/2))}

```

Alternative for 30 bytes: `printf \\$[[##8](##$1+##$2)/2]`

# Answer
> 2 votes
# Julia 1.0, <sup>~~24~~ ~~21~~</sup> 14 bytes

```
a\b=a+(b-a)÷2

```

Try it online!

# Answer
> 2 votes
# Vyxal, 3 bytes

```
CṁC

```

Try it Online!

### Explanation

```
CṁC
     (implicit input)
C    Convert to character code list
 ṁ   Get average
  C  Convert back to letter

```

# Answer
> 2 votes
# Piet (ASCII-Piet), 12 bytes

```
jN LnN FjCjJ

```

ASCII-Piet is a compact encoding for the image-based esolang Piet that encodes each pixel (or codel) of Piet code as a single ASCII character. This ASCII-Piet code translates into the following program:

Or enlarged to codel size 25:

Edit: fixed the enlarged version, and golfed two bytes off by rotating the program.

Simply takes two characters from input (Piet can only represent chars on the stack by codepoints), sums them, divides by two, and outputs the result char.

# Answer
> 2 votes
**ABAP**

```
    SELECTION-SCREEN BEGIN OF BLOCK b0.
    PARAMETERS: p_first  TYPE c LOWER CASE OBLIGATORY,
                p_second TYPE c LOWER CASE OBLIGATORY.
    SELECTION-SCREEN END OF BLOCK b0.

    START-OF-SELECTION.

    WRITE / cl_abap_conv_in_ce=>uccpi( uccp =
         (
            ( cl_abap_conv_out_ce=>uccpi( char = p_first )
              + cl_abap_conv_out_ce=>uccpi( char = p_second ) ) / 2 )
          ).

```

# Answer
> 2 votes
# \>\<\> (Fish), 5 bytes

```
+2,o;

```

Try it

# Answer
> 2 votes
# Thunno 2 `B`, 2 bytes

```
mC

```

Attempt This Online!

```
mC  # implicit input, B flag converts string to byte array
m   # mean
 C  # convert to letter

```

# Answer
> 2 votes
# Vyxal 2.4.1 `K`, 2 bytes

```
ṁC

```

Try it Online!

# Answer
> 2 votes
# Trilangle, 8 bytes

```
ii2+d@'o

```

Try it in the online interpreter!

Takes the two letters on stdin with no separator. Very straightforward, `putchar((getchar() + getchar()) / 2)`.

# Answer
> 2 votes
# Java (JDK), 20 <sup>~~21~~</sup> bytes

> -1 byte after seeing in other languages that `[...]>>1` is a shorter way to do `([...])/2` because it has less operator priority!

A 2-parameters problem is the only moment where the double lambda can shine!

```
a->b->(char)(a+b>>1)

```

Try it online!

# Answer
> 2 votes
## C, 17 bytes

```
f(a,b){a=a+b>>1;}

```

At first I thought

```
f(a,b){a=(a+b)/2;}

```

was the best but then I remembered Cs operation precedent and realized it would be shorter to shift right by 1.

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
ÇÅAç

```

Try it online! or verify all test cases

**Explanation**

```
Ç    | Get ASCII values of both inputs
 ÅA  | Take the mean
   ç | Convert to ASCII char

```

# Answer
> 1 votes
# Perl 5 `-p`, 22 bytes

```
$_=chr+(ord(<>)+ord)/2

```

Try it online!

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

```
f(a,b){a=a+b>>1;}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 7 bytes

```
℅⊘ΣＥＳ℅ι

```

Try it online! Link is to verbose version of code. Takes input as a string of two letters. Explanation:

```
    Ｓ   Input string
   Ｅ    Map over characters
      ι Current character
     ℅  Take the ordinal
  Σ     Take the sum
 ⊘      Halved
℅       Convert to character
        Implicitly print

```

# Answer
> 1 votes
# Ruby, 27 bytes

```
->x,y{(x.ord+y.ord>>1).chr}

```

Try it online!

# Answer
> 1 votes
# Python 3, 34 bytes

```
lambda a,b:chr((ord(a)+ord(b))//2)

```

Try it online!

# Answer
> 1 votes
# Labyrinth, 8 bytes

```
,,+_2/.@

```

**Try it online!**

### How?

```
, read a character from STDIN and push its ordinal
, read a character from STDIN and push its ordinal
+ pop y, pop x, push x+y
_ push a zero
2 pop x, push 10*x+2
/ pop y, pop x, push x/y (integer division, rounded towards negative infinity)
. pop x, print byte at (x%256)
@ exit program

```

# Answer
> 1 votes
# Japt, ~~8~~ 6 bytes

```
xc z d

```

Try it

# Answer
> 1 votes
# Pyth, 6 5 bytes

```
C.OmC

```

Try it online!

As a bonus, works with more than two letters

Edit: -1 thanks to @randomdude999, wasnt aware that the lambda function implicitly adds the lambda variable

## How it Works

```
C.OmC
   mC - Map (char to int) to the implicit input
 .O    - Take the average
C      - Int to char

```

# Answer
> 1 votes
# Haskell, 32 bytes

```
toEnum.(`div`2).sum.map fromEnum

```

Try it online!

# Answer
> 1 votes
# JavaScript - ~~62~~ 60 bytes

I'm certain there's a better way than this:

```
(a,b,c=x=>x.charCodeAt())=>String.fromCharCode(c(a)+c(b)>>1)

```

Would love some feedback!

Example:

```
f=(a,b,c=x=>x.charCodeAt())=>String.fromCharCode(c(a)+c(b)>>1)
f('a','c') // 'b'

```

# Answer
> 1 votes
# Gol\>\<\>, 6 bytes

```
ii+2,H

```

Try it online!

**Explanation**

```
ii     Push 2 input chars as int to stack
  +    Add them
   2,  Float divide by 2
     H Output as char and halt (Seems to truncate)

```

# Answer
> 1 votes
# Triangular, ~~10~~ 9 bytes

```
t+~2.`>_@

```

Try it online!

**Ungolfed:**

```
   t
  + ~
 2 . `
> _ @

----------------------

t~`           - Read 2 characters from input; change direction to SE after
+2>_          - Add the two top values of the stack, then divide by 2
@             - Print as a character

```

---

**Previous Version (10 bytes):**

```
~.~..+@_2<

```

# Answer
> 1 votes
# Stax, 4 bytes

```
:V@]

```

Run and debug it

# Answer
> 1 votes
## GolfScript, 10 bytes

```
{+}*2/]''+

```

## Explanation

```
{+}*       # Fold the input string with sums
    2/     # Divide this number by 2
      ]''+ # Put stack into array & convert to string

# Implicit print

```

Try it online!

# Answer
> 1 votes
# , 6 bytes

Has some trailing garbage, but can't be avoided because all functions have return values.

```
ō/+čč2

```

## Explanation

```
  +čč  Sum two inputs' charcodes
 /   2 Halve the number
ō      Output as a character

```

# Answer
> 1 votes
# Ahead, 7 bytes

```
ii+2/o@

```

Try it online!

# Answer
> 1 votes
# Burlesque, 9 bytes

```
)**avavL[

```

Try it online!

If I'm allowed to report the ceiling, can save 2 chars `)**foL[` `fo` is defined as `avpd` which calculates the average and then ceilings it.

```
)** # Map ord(a)
av  # Calculate average
av  # Floor the resulting double
L[  # Int to Char

```

# Answer
> 1 votes
# Haskell, 48 bytes

```
f=fromEnum;g a b=toEnum(div((f a)+(f b))2)::Char

```

Try it online

# Answer
> 1 votes
# Erlang (escript), 26 bytes

Sums the input, divide by 2, and then convert to character.

```
f(X)->[lists:sum(X)div 2].

```

Try it online!

# Answer
> 1 votes
# MAWP, 5 bytes

```
|M2P;

```

Input must be given without any separator.

Try it!

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
ÇO;ç

```

Try it online!

```
ÇO;ç  # full program
  ;   # divide...
 O    # sum of...
Ç     # charcodes of...
      # implicit input...
  ;   # by 2
   ç  # convert to charcodes, rounding down
      # implicit output

```

# Answer
> 1 votes
# Raku, 18 characters

```
{($^a..^$^b)[*/2]}

```

Sample run:

```
> {($^a..^$^b)[*/2]}('A', 'C')
B

```

Try it online!

# Answer
> 1 votes
# Python ~~53~~ 46 bytes

thanks to @manatwork recommended not to store inputs in variables.

```
print(chr(int((ord(input())+ord(input()))/2)))

```

# Answer
> 1 votes
# Java, 45 chars

```
char c(char a,char b){return(char)((a+b)/2);}

```

Try it online!

# Answer
> 1 votes
# Pyth, 5 bytes

```
C.OCM

```

Try it online!

# Answer
> 1 votes
# Factor, 8 bytes

```
[ + 2/ ]

```

Try it online!

Or if we're allowed to take input in a list, then

# Factor, 4 bytes

```
mean

```

# Answer
> 1 votes
# C++ - 34 Bytes

```
int f(int a,int b){return(a+b)/2;}

```

**Ungolfed**

```
int f(int a, int b)
{
    return (a + b) / 2;
}

```

**Explanation**

A function that returns the average of two integers, in this case it can be used with ASCII characters.

# Answer
> 1 votes
# Knight, 14 bytes

```
O A/+A P A P 2

```

Try it online!

# Answer
> 1 votes
# Scala, 32 bytes

Golfed version. Try it online!

```
z=>(z.map(_.toInt).sum/2).toChar

```

# Answer
> 0 votes
# C (gcc), 49 bytes

```
int a,b;scanf("%c,%c",&a,&b);printf("%c",a+b>>1);

```

Try it online!

Got the idea of bit-shift operators from this answer

# Answer
> 0 votes
**Swift**, 134 bytes

```
var s=readLine(),a=readLine();print(Character(UnicodeScalar((s?.compactMap{$0.asciiValue}[0])!+(a?.compactMap{$0.asciiValue}[0])!/2)))

```

# Answer
> 0 votes
# Ruby, 45 bytes

```
a,b=gets.split;puts"#{((a.ord+b.ord)/2).chr}"

```

Attempt This Online!

# Answer
> 0 votes
# J-uby, 22 bytes

```
:*&:ord|+:+|~:/&2|:chr

```

Attempt This Online!

## Explanation

```
:* & :ord | +:+ | ~:/ & 2 | :chr

:* & :ord |                       # Map with .ord, then
            +:+ |                 # sum, then
                  ~:/ & 2 |       # integer divide by two, then
                            :chr  # convert to character

```

# Answer
> 0 votes
# Uiua, 18 bytes

```
⍜∩utf(⌊÷2+)

```

Try It

Explanation

```
⍜∩utf(⌊÷2+)
⍜∩utf # convert both chars to ints,
      # apply the operation in parentheses, and undo the char to int conversion
     (⌊÷2+) # calculate a floored avg
         + # sum both elements
       ÷2 # divide by two
      ⌊ # floor the result

```

---
Tags: code-golf, string, math, arithmetic, statistics
---


title: Charlie, Oscar, Delta, Echo

text:
# Question
Title: Charlie, Oscar, Delta, Echo
A big part of radio communication is the NATO Phonetic Alphabet, which encodes letters as words to make them easier to understand over comms. Your job, if you wish to accept it, is to print them one by one.

You must print this exact string to stdout:

```
A: Alfa
B: Bravo
C: Charlie
D: Delta
E: Echo
F: Foxtrot
G: Golf
H: Hotel
I: India
J: Juliet
K: Kilo
L: Lima
M: Mike
N: November
O: Oscar
P: Papa
Q: Quebec
R: Romeo
S: Sierra
T: Tango
U: Uniform
V: Victor
W: Whiskey
X: Xray
Y: Yankee
Z: Zulu

```

# Rules:

* Your program takes no input
* Standard loopholes are **Disallowed**.
* If there are any builtins in your language that turn letters to their NATO equivelants, you may not use them (I'm looking at you Mathematica).
* You may have trailing spaces and **one** trailing newline.

# Answer
# Python 2, ~~189~~ 186 bytes

```
i=65
for w in"lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split():print'%c: %c'%(i,i)+w;i+=1

```

**Try it online!**

---

Previous: (this was cool, but I realised the simpler version could be made shorter by a byte)

```
w=''
i=65
for c in"lfAravOharliEeltAchOoxtroTolFoteLndiAulieTilOimAikEovembeRscaRapAuebeComeOierrAangOniforMictoRhiskeYraYankeEulU":
 w+=c.lower()
 if'_'>c:print'%c: %c'%(i,i)+w;w='';i+=1

```
> 18 votes

# Answer
# Jelly, 76 bytes

```
“ṭṡl°ẠkWßġȮRẎ+wḋñȥạġ¢ƊḌ¬kạẠ¦WṡỊƒK⁹ç}⁶hm}Kñ£ɦ/lṇẊɠƓ}pƤ°⁸Ụ.g⁹Ġh9ṁ{f»ḲØAżj€⁾: Y

```

**Try it online!**

### How?

Pretty much just dictionary values and compression. The code between  and `»` is just a compressed value that will form the string `"Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu"` by looking up all the words (with single space prefixes, except for `"Alfa"`) in Jelly's dictionary (except for `" Xray"` which is not in the dictionary, so the direct string value `" X"` and the dictionary entry `"ray"` are used instead).

The rest of the code does the rest:

```
“...»ḲØAżj€⁾: Y - Main link: no arguments
“...»           - the string described above (really a list of characters)
     Ḳ          - split at spaces
      ØA        - alphabet yield - ['A','B','C', ...,'X','Y','Z']
        ż       - zip - makes a list of lists [['A'],['A','l','f','a']],[['B'],['B','r','a','v','o']], ...]
         j€     - join each with
           ⁾:   - the string ": "
              Y - join with line feeds
                - implicit print

```
> 12 votes

# Answer
## Retina, 156 bytes

Byte count assumes ISO 8859-1 encoding.

```

AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu
[A-Z]
¶$&: $&
G`.

```

Try it online!
> 11 votes

# Answer
# 05AB1E, ~~102~~ 98 bytes

Saved 4 bytes thanks to *Erik the Outgolfer*

```
”AlfaÐ†vo¼¯¤œ®È¨›trotŠˆƒ‹Š™ÈŸt Kilo´àma—……ÍÐ—Žêpa¼°«Äoµ†Çâgo¸šÉµ Whiskey Xrayµ‹nkeeâ¸lu”#vy¬„: «ì,

```

Try it online!

**Explanation**

Uses dictionary compression for the words in 05AB1E's dictionary.
Uses partial dictionary compression whenever possible for other words.
Plain-text words where neither is possible.

```
#          # split on spaces
 v         # for each word
  y        # push the word
   ¬       # get the first letter of the word
    „:     # push the string ": "
       «   # append this to the letter
        ì  # prepend the result to the word
         , # print with newline

```
> 11 votes

# Answer
# Java 7, ~~242~~ ~~225~~ ~~222~~ 217 bytes

```
void d(){char c=65;for(String s:"lpha ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split(" "))System.out.println(c+": "+c+++s);}

```

**Explanation:**

```
void d(){                          // Method
  char c = 65;                     //  Starting character 'A'
  for(String s : "lpha ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu"
      .split(" "))                 //  Loop over the word-parts
    System.out.println(            //   Print line with:
      c                            //    The current character
      + ": "                       //    + ": "
      + c++ + s                    //    + the current character + word-part (and raise the character afterwards)
    );                             //   End of print line
                                   //  End of loop (implicit / single-line body)
}                                  // End of method

```

**Test code:**

Try it here.

```
class M{
  static void d(){char c=65;for(String s:"lpha ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split(" "))System.out.println(c+": "+c+++s);}

  public static void main(String[] a){
    d();
  }
}

```
> 6 votes

# Answer
# Ruby, 169 characters

(Heavily based on Jonathan Allan's Python 2 solution. If you like the idea, please upvote the original answer.)

```
i=?@
"LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUlietIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu".scan(/.[a-z]+/){|w|puts i.succ!+": "+i+w.downcase}

```

Sample run:

```
bash-4.3$ ruby -e 'i=?@;"LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUlietIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu".scan(/.[a-z]+/){|w|puts i.succ!+": "+i+w.downcase}' | head
A: Alfa
B: Bravo
C: Charlie
D: Delta
E: Echo
F: Foxtrot
G: Golf
H: Hotel
I: India
J: Juliet

```
> 6 votes

# Answer
## PHP, ~~202~~ ~~227~~ ~~196~~ 187 bytes

Thanks to Dewi Morgan for saving 9 bytes

```
echo preg_replace('/([A-Z])[a-z]+/',"$1: $0\n",AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu);

```

https://repl.it/GMkH/1

---

**Older versions**

Thanks to manatwork and insertusernamehere for saving 31 bytes!

```
foreach(preg_split('/\B(?=[A-Z])/',AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu)as$k)echo"$k[0]: $k\n";

```

https://eval.in/749541

Thanks to insertusernamehere for noticing the output was wrong with the previous version.

```
$a=preg_split('/(?=[A-Z])/',AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu,-1,PREG_SPLIT_NO_EMPTY);foreach($a as $k)echo "$k[0]: $k\n";

```

https://repl.it/GKS8/3

```
$a=preg_split('/(?=[A-Z])/',AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu);foreach($a as $k)echo"$k[0]: $k\n";

```

https://repl.it/GKS8/2
> 5 votes

# Answer
# Octave, ~~215~~ ~~210~~ 209 bytes

~~Saved 5 bytes thanks to Luis Mendo.~~ I saved 4 bytes thanks to Luis Mendo, but changing the approach help me save one more

```
fprintf('%s: %s%s\n',[k=num2cell(65:90);k;regexp('lfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu','[A-Z]','split')]{:})

```

Try it online!

~~If I got rid of the spaces, I'd save 25 bytes, but then~~ I'd have to use a regex. The regex itself would cost quite a few bytes, and it would also remove the capital letter of all words, leaving me with the words `lfa, ravo` etc. I would therefore have to concatenate the new strings with the leading characters. All this costs bytes.

**Old explanation:**

```
fprintf('%s: %s\n',      % Print a string with the format "str: str\n"
num2cell(65:90)          % Create a cell array with the numbers 65 - 90, one in each cell
strsplit('Alfa ...       % Split the string on the default delimiter: space
[num2cell();strsplit()]  % Concatenate cell arrays, leaving us with
                         % {'A',    'B'
                         %  'Alfa', 'Bravo'}
[...]{:}                 % Convert the cell array to a comma-delimited vector
                         % 'A', 'Alfa', 'B', 'Bravo' ...

```
> 5 votes

# Answer
# Brachylog, 178 bytes

```
"Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu"ṇ₁{hw": "w?ẉ}ᵐ

```

Try it online!

### Explanation

```
"…"ṇ₁               Split the string on spaces
     {         }ᵐ   Map on each word:
      hw              Write the first letter
        ": "w         Write ": "
             ?ẉ       Write the word followed by a new line

```
> 4 votes

# Answer
# C (MinGW, Clang), 218 bytes

*Thanks to @gastropner!*

```
i;f(){char s[]="lfa:ravo:harlie:elta:cho:oxtrot:olf:otel:ndia:uliet:ilo:ima:ike:ovember:scar:apa:uebec:omeo:ierra:ango:niform:ictor:hiskey:ray:ankee:ulu";for(i=64;++i<91;)printf("%c: %c%s\n",i,i,strtok(i^65?0:s,":"));}

```

Try it online!

# C, ~~259~~ 236 bytes

```
i;f(){char*s="lfa\0ravo\0harlie\0elta\0cho\0oxtrot\0olf\0otel\0ndia\0uliet\0ilo\0ima\0ike\0ovember\0scar\0apa\0uebec\0omeo\0ierra\0ango\0niform\0ictor\0hiskey\0ray\0ankee\0ulu";for(i=64;++i<91;s+=strlen(s)+1)printf("%c: %c%s\n",i,i,s);}

```

Try it online!
> 4 votes

# Answer
# PHP, ~~188~~ ~~186~~ ~~180~~ 174 bytes

no trailing spaces, one leading newline

```
<?=preg_filter("#[A-Z]#","
$0: $0",AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu);

```

simply replaces all uppercase letters in the compressed string with
`<newline><letter><colon><space><letter>`
> 4 votes

# Answer
# Python 2, ~~186~~ 182 bytes

```
print''.join('\n%s: '%c*('['>c)+c for c in'AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu')

```

Try it online!
> 4 votes

# Answer
# Gema, 168 characters

```
\A=@subst{?<J>=\?: \$0\\n;AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu}@end

```

Sample run:

```
bash-4.3$ gema '\A=@subst{?<J>=\?: \$0\\n;AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu}@end' | head
A: Alfa
B: Bravo
C: Charlie
D: Delta
E: Echo
F: Foxtrot
G: Golf
H: Hotel
I: India
J: Juliet

```
> 3 votes

# Answer
# Bash, ~~224~~ ~~205~~ ~~188~~ 180 bytes

Thanks to Digital Trauma for removing 17 bytes, and manatwork for 8 bytes.

```
set {A..Z}
for i in lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu;{ echo $1: $1$i;shift;}

```

Try it online!
> 3 votes

# Answer
# x86 Assembly, 512 bytes

Compiled with NASM and tested with QEMU. To boot you need to put a 2 byte boot signature at the end of the bootsector (510 bytes into the file) so I lost 317 bytes filling the compiled code with zeros. This is my first golf so I have to apologize for any gigantic errors.

```
[org 7c00h]     ;So NASM can change the labels into memory locations correctly.

cld             ;Tells lodsb to look forward in memory

mov bh, 65      ;Moves the ASCII value of A into the BH register
mov si, NATO    ;Moves the first byte of NATO into the si register
call print      ;Call the 'print' subroutine

jmp $            ;Loops forever

print:
    mov ah, 0eh ;Moves the hex value 0E into the AH register. Tells interrupt 10h that we want subfucntion 0E
    lodsb       ;Load a byte of SI into AL and increments a register (DL i think) that tells it the offset to look at

    cmp al, 3   ;Compares the AL register that now has a byte from our string to ASCII value 3 (Enf Of Text)
    je R        ;If AL == 3 then jump to R

    cmp al, 0   ;Comapre AL to ASCII 0 (NULL)
    je newWord  ;If AL == 0 hump to newWord
    int 10h     ;Execute interrupt 10h Subfunction 0Eh (stored in AH register) which prints character value in AL
    jmp print   ;Jump to print

newWord:
    mov al, 10  ;Move ASCII 10 (New Line) into AL
    int 10h     ;Print character

    mov al, 13  ;Move ASCII 13 (Carriage Return) into AL
    int 10h     ;Print character

    mov al, bh  ;Move BH (which has our starting letter) into AL
    int 10h     ;Print Character

    mov al, 58  ;Move ASCII 58 (:) into AL
    int 10h     ;Print Character

    mov al, 32  ;Move ASCII 32 (Space) into AL
    int 10h     ;Print Character

    mov al, bh  ;Move BH into AL
    int 10h     ;Print Character

    inc bh      ;Increments BH by one (BH++)
    jmp print   ;Jump to print

R:
    ret         ;Returns from a subroutine

;Below defines bytes (db) of our string to print. I used 0 as word seperators and 3 to end the string.
NATO: db 0,"lfa",0,"ravo",0,"harlie",0,"elta",0,"cho",0,"oxtrot",0,"olf",0,"otel",0,"ndia",0,"uliet",0,"ilo",0,"ima",0,"ike",0,"ovember",0,"scar",0,"apa",0,"uebec",0,"omeo",0,"ierra",0,"ango",0,"niform",0,"ictor",0,"hiskey",0,"ray",0,"ankee",0,"ulu",3

times 0200h - 2 - ($ - $$) db 0 ;Zerofill the file with upto 510 bytes (This is where all my bytes are)
dw 0AA55H   ;Write the bootsignature

```

## Output

This is what the above code outputs. As you can see *A: Alfa* is missing and that is because the prompt is 25 lines tall...

To prove I printed *A: Alfa* I replaced `0,"ulu"` with `32,"Z: Zulu"` so that Zulu is one on the same line as Yankee.

I would appreciate it if someone told me if I would be able to subtract the 317 bytes of zerofill from my code so it would be 195 bytes. Also if this is even valid because the output won't fit on the screen.
> 3 votes

# Answer
# JavaScript ES6, 216 187 184 180 174 bytes

```
"AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu".replace(/[A-Z]/g,`
$&: $&`).trim()

```

Saved a byte thanks to Neil. Saved 5 bytes thanks to ETHproductions.

```
console.log("AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu".replace(/[A-Z]/g,`
$&: $&`).trim());
```

# Japt, 127 bytes

```
`AlfaBŸvoC•r¦eDeltaE®oFoxÉ•GolfHÇUI˜iaJªietKiloL‹aMikeNovem¼rOs¯rPapaQue¼cRo´oSi€ŸTÂ
UnifŽmVÅ¡rW–skeyXŸyY„keeZªu`r"%A""
$&: $&

```

Try it online!

Saved 2 bytes thanks to obarakon.
> 2 votes

# Answer
# Python 2, 198 bytes

```
for x in'Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu'.split():print x[0]+': '+x

```

Try it online!

Not exciting or clever. Just loops through the list and prints the first letter then ': ' then the whole word.
> 2 votes

# Answer
## Lua, ~~278~~ 260 bytes

Thanks again to Manatwork for saving 18 bytes!

```
function f(w)print(w.sub(w,0,1)..": "..w)end
f"Alfa"f"Bravo"f"Charlie"f"Delta"f"Echo"f"Foxtrot"f"Golf"f"Hotel"f"India"f"Juliet"f"Kilo"f"Lima"f"Mike"f"November"f"Oscar"f"Papa"f"Quebec"f"Romeo"f"Sierra"f"Tango"f"Uniform"f"Victor"f"Whiskey"f"Xray"f"Yankee"f"Zulu"

```

Try it online

---

**Older versions**

```
a={"Alfa","Bravo","Charlie","Delta","Echo","Foxtrot","Golf","Hotel","India","Juliet","Kilo","Lima","Mike","November","Oscar","Papa","Quebec","Romeo","Sierra","Tango","Uniform","Victor","Whiskey","Xray","Yankee","Zulu"}
for i=1,26 do print(a[i].sub(a[i],0,1) .. ": " .. a[i]) end

```

https://repl.it/GK8J

First time doing Lua, do probably can golf more, but thought I'd add it as an answer anyways.
> 2 votes

# Answer
# PowerShell, ~~187~~ 185 bytes

```
0..25|%{($a=[char]($_+65))+": $a"+(-split'lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu')[$_]}

```

Try it online!

Loops from `0` to `25`, each iteration forming `$a` of the corresponding capital `char`. Then string-concatenated with `: $a` (i.e., the colon-space-letter). Then that string is string-concatenated with an string that's formed by indexing into an array created by `-split`ting the phonetic string on spaces. Each of those 26 strings is left on the pipeline, and an implicit `Write-Output` happens at program completion, inserting a newline between elements.

*Saved two bytes thanks to @Matt.*
> 2 votes

# Answer
# PHP, 184 bytes 179 bytes 178

```
<?=preg_filter('/(.)[a-z]+/',"$1: $0
",AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu);

```

saved a single byte by using preg\_filter instead of preg\_replace.

---

*Original answer* 184 bytes 179 bytes

```
for($c=A;$s=[lfa,ravo,harlie,elta,cho,oxtrot,olf,otel,ndia,uliet,ilo,ima,ike,ovember,scar,apa,uebec,omeo,ierra,ango,niform,ictor,hiskey,ray,ankee,ulu][+$i++];$c++)echo"$c: $c$s
";

```

uses the fact that its sorted to generate the first char on the fly.

5 bytes saved by @Titus.
> 2 votes

# Answer
## GNU sed, 165 bytes

This script is based on the Retina answer by Martin Ender.

```
s/$/AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu/
s/[A-Z]/\n&: &/g
s/.//

```

**Try it online!**

**Explanation:**

```
s/$/AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu/
   # generate the alphabet words in concatenated form
s/[A-Z]/\n&: &/g
   # prepend '\nUL: ' before each upper-case letter (UL), getting the needed format
s/.//
   # delete the leading newline, plus implicit printing at the end

```
> 2 votes

# Answer
# SOGL, 91 bytes

```
╗D↕«∙φā¡75↔TI.½!γΜΧ…¡%<F┼0h╔κy|▓@TņV≈%⁹cr_σy░mgļΕžΕ⅝ »τ{M╔|«▼↔»aΓ²⁹┘′⅓G…└g↔bFΞ‽‘θ{KUtƧ: ooo

```

Explanation:

```
...‘θ{KUtƧ: ooo  that gibberish is a compressed string
...‘             push the compressed string of the words
    θ            split on spaces
     {           for each
      K          pop the 1st letter off & push it
       U         uppercase it
        t        output in newline a copy of the letter
         Ƨ: o    append ": "
             o   append the alphabet letter
              o  append the rest of the word

```
> 2 votes

# Answer
# Bash, 184 bytes

```
printf '%c: %s
' {Alfa,Bravo,Charlie,Delta,Echo,Foxtrot,Golf,Hotel,India,Juliet,Kilo,Lima,Mike,November,Oscar,Papa,Quebec,Romeo,Sierra,Tango,Uniform,Victor,Whiskey,Xray,Yankee,Zulu}{,}

```

Try it online!
> 2 votes

# Answer
# Lua, 177 bytes

```
print(("AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu"):gsub('%u',"\n%1: %1"):sub(2))

```

Try it online!

**Without trailing newline, 180 bytes:**

```
io.write(("AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu"):gsub('%u',"\n%1: %1"):sub(2))

```

**Explanation**

```
str = "AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu"
str = str:gsub('%u',"\n%1: %1") -- returns "\nA: Alfa...". %u matches uppercase letters, %1 returns matched letter in this case.
str = str:sub(2) -- remove added newline in the beginning
print(str) -- native print command

```

It uses Lua's string.gsub substitution function to pattern match the uppercase letters. The letters are then replaced with the requested format (plus the letters themselves). Newlines are also added on the same pass.

The sub-function at the end just trims out newline from the beginning and also works nicely to hide the second return value of gsub, which would have been the amount of replacements.
> 2 votes

# Answer
# PHP, ~~175~~ ~~171~~ ~~164~~ 162 bytes

Note: no longer requires compressed file, uses IBM-850 encoding.

```
for($l=A;$c=LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUlietIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu[$i++];)echo$c<a?"
$l: ".$l++:"",$c|~▀;

```

Run like this:

```
php -nr 'for($l=A;$c=LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUlietIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu[$i++];)echo$c<a?"
$l: ".$l++:"",$c|~▀;';echo

```

# Explanation

Prints every character individually (lowercased by OR with a space). If an uppercase character is encountered, it first prints a string of the form "\nA: A".

# Tweaks

* Saved 4 bytes by using another compression strategy
* Saved 7 bytes by using a different delimiter (to combine assignment of `$l` with explode param), and not preventing a leading newline
* Saved 2 bytes with a new method
> 2 votes

# Answer
# C, ~~216~~ ~~215~~ 212 bytes

```
i=64,l;f(){for(char*s="lfAravOharliEeltAchOoxtroTolFoteLndiAulieTilOimAikEovembeRscaRapAuebeComeOierrAangOniforMictoRhiskeYraYankeEulU";++i<91;printf("%c: %c%.*s%c\n",i,i,l,s,s[l]+32),s+=l+1)for(l=0;s[++l]>90;);}

```

Try it online!

A detailed, human readable, well commented and perfectly valid (no compiler warnings) version of the program can be found below:

```
#include <stdio.h>

int main() {
    // Uppercase characters designate the last character of a word
    char*s="lfAravOharliEeltAchOoxtroTolFoteLndiAulieTilOimAikEovembeRscaRapAuebeComeOierrAangOniforMictoRhiskeYraYankeEulU";

    int i = 64; // Consecutive character
    int l; // Word length

    // Loop `i` from A to Z; Shift `s` with word length
    // `s` always points to the beginning of a word
    for( ; ++i < 91; s += l + 1 ) {
        // Increment `l` until you reach the next capital letter
        for( l = 0; s[++l] > 90 ;);
        // Print the current character, the word without it's last letter
        // and the last letter lowercased
        printf( "%c: %c%.*s%c\n", i, i, l, s, s[l]+32 );
    }
}

```
> 2 votes

# Answer
# C#, 257 242 bytes

*Thanks to Kevin Cruijssen for saving 15 bytes!*

```
class P{static void Main(){var c='A';foreach(var t in "lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".Split())System.Console.WriteLine(c+": "+c+++t);}}

```

Full program which prints the required text, with one trailing newline.

Ungolfed:

```
class P
{
    static void Main()
    {
        var c='A';
        foreach(var t in "lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".Split())
            System.Console.WriteLine(c+": "+c+++t);
    }
}

```
> 1 votes

# Answer
# Japt, ~~216~~ 214 bytes

```
`A: Alfa
B: Bvo
C: Cr¦e
D: Delta
E: E®o
F: FoxÉ
G: Golf
H: HÇU
I: Iia
J: Jªiet
K: Kilo
L: La
M: Mike
N: Novem¼r
O: Os¯r
P: Papa
Q: Que¼c
R: Ro´o
S: Si
T: TÂ
U: Unifm
V: VÅ¡r
W: Wskey
X: Xy
Y: Ykee
Z: Zªu

```

Explaination: There is most likely a much better way to do it, but since i'm new I don't know it. I basically compressed the string with Oc" and put that string to be decompressed using Od"

If someone wants to help me save bytes by using something different from line breaks, I'd be happy to learn!

edit: Saved 2 bytes using \` instead of Od"
> 1 votes

# Answer
## Pyke, 89 bytes

```
.d⻵㡺ᐒଆຳ뼙΋ÒΗ䊊繎ㅨڨǔᯍⰬᐓ❤ᄵ㤉ተ᤬䆰髨⨈性dc Fl5DhRJ":

```
> 1 votes

# Answer
# Qbasic, 383 bytes

Not impressive, but for what it's worth:

```
dim a(1to 26)as string
a(1)="lfa
a(2)="ravo
a(3)="harlie
a(4)="elta
a(5)="cho
a(6)="oxtrot
a(7)="olf
a(8)="otel
a(9)="ndia
a(10)="uliet
a(11)="ilo
a(12)="ima
a(13)="ike
a(14)="ovember
a(15)="scar
a(16)="apa
a(17)="uebec
a(18)="omeo
a(19)="ierra
a(20)="ango
a(21)="niform
a(22)="ictor
a(23)="hiskey
a(24)="ray
a(25)="ankee
a(26)="ulu
for i=1to 26
?chr$(i+64);": ";chr$(i+64);a(i)
next

```
> 1 votes

# Answer
# ///, 220 bytes

```
/;/: /A;Alfa
B;Bravo
C;Charlie
D;Delta
E;Echo
F;Foxtrot
G;Golf
H;Hotel
I;India
J;Juliet
K;Kilo
L;Lima
M;Mike
N;November
O;Oscar
P;Papa
Q;Quebec
R;Romeo
S;Sierra
T;Tango
U;Uniform
V;Victor
W;Whiskey
X;Xray
Y;Yankee
Z;Zulu

```

Try it online!

-20 bytes thanks to @ETHproductions.
> 1 votes

# Answer
# Bubblegum, 182 bytes

```
00000000: 05c1 4792 e330 1004 c07b bda2 de51 3779  ..G..0...{...Q7y
00000010: efbd 6e10 b7b5 4210 644f 8026 46bf 9fcc  ..n...B.dO.&F...
00000020: 8138 48ef 80a1 38cc a177 8cc4 d127 e414  .8H...8..w...'..
00000030: 0d63 716c a90d 9888 93e2 e398 8a53 ff6d  .cql.........S.m
00000040: b3b7 9889 334f 6fcc c5b9 b796 b010 17f5  ....3Oo.........
00000050: bf18 b014 975d 8ad6 6225 ae62 72ac c575  .....]..b%.br..u
00000060: ac02 36e2 2696 86ad b8f5 deaa 9765 ecc4  ..6.&........e..
00000070: 5d53 848c bdb8 0f3f 0107 f1d0 d9cb 0a1c  ]S.....?........
00000080: c5a3 57e6 3889 a768 3907 9cc5 73a8 ff3b  ..W.8..h9...s..;
00000090: 2ee2 a58e 6fcf 15ae e235 16ad 67dc c4db  ....o....5..g...
000000a0: 2736 a57d 7117 ef39 7cf1 101f a12e cdf0  '6.}q..9|.......
000000b0: 149f 5dea fe00                           ..]...

```

Just Zopfli'd the target string for 100 000 iterations.
> 1 votes

# Answer
# Japt, 131 bytes

130 bytes +1 for the `-R` flag.

```
;B¬®+": "+`AlfaBŸvoC•r¦eDeltaE®oFoxÉ•GolfHÇUI˜iaJªietKiloL‹aMikeNovem¼rOs¯rPapaQue¼cRo´oSi€ŸTÂ
UnifŽmVÅ¡rW–skeyXŸyY„keeZªu`fZ+"%a+

```

Try it online!

### Explanation

```
;B¬®+": "+`{compressed string}`fZ+"%a+
;B                                     // Alphabet shortcut (ABC...XYZ)
  ¬                                    // Splits the Alphabet, by char, into new lines
   ®                                   // Shortcut for mZ{Z, which maps each item Z to the following:
    +": "+                             //   (Implicit) Z + ": " +
                               fZ+"%a+ //   matches of Z followed by lowercase letters, in
          `{compressed string}`        //   the compressed string "Alfa...Zulu". Backticks are used to decompress the string

```

The `-R`flag is used to seperate each item by newlines.

Japt uses the shoco library for string compression.
> 1 votes

# Answer
# Chipmunk BASIC, 191 characters

(Inspired by anonymous2's QBasic solution. Was just too impatient to see a `data` based variant, so tried it myself.)

```
data lfa,ravo,harlie,elta,cho,oxtrot,olf,otel,ndia,uliet,ilo,ima,ike,ovember,scar,apa,uebec,omeo,ierra,ango,niform,ictor,hiskey,ray,ankee,ulu
for i=65to 90
read w$
?chr$(i)": "chr$(i)w$
next

```

Sample run:

```
Chipmunk BASIC v3.5.8b9
>load "nato.bas"
>run
A: Alfa
B: Bravo
C: Charlie
D: Delta
E: Echo
F: Foxtrot
G: Golf
H: Hotel
I: India
J: Juliet
K: Kilo
L: Lima
M: Mike
N: November
O: Oscar
P: Papa
Q: Quebec
R: Romeo
S: Sierra
T: Tango
U: Uniform
V: Victor
W: Whiskey
X: Xray
Y: Yankee
Z: Zulu

```
> 1 votes

# Answer
# Common Lisp, 219 bytes

```
(dolist(c'(alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango uniform victor whiskey xray yankee zulu))(format t"~C: ~:(~A~)~%"(char(string c)0)c))

```

Ungolfed

```
(dolist (c '(alfa bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa quebec romeo sierra tango uniform victor whiskey xray yankee zulu))
  (format t "~C: ~:(~A~)~%" (char (string c) 0) c))

```

Explaination:

`dolist` is effectively the CL equivalent of python's for _ in _ loop.

The words themselves are stored as lisp symbols, which are upcased after parsing by default.

`format` actually handles printing out to screen. The heavily lifting is in the format control string: "~C: ~:(~A~)~%".

~C takes a char and just prints it, ~A does the same with an arbitrary lisp object. ~:( and ~) are 'case control' directives, which upcase the first letter of any word printed between them.

`(char (string c) 0)` Gets the string for the symbol c and pulls the first char out of it.
> 1 votes

# Answer
# Groovy, 191 bytes

Really nothing fancy, but it's Friday and I wanted to go golfing for the first time.

```
char c=65;"lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split().any{println("${c}: ${c++}"+it)}

```

Try it online!
> 1 votes

# Answer
# 8086 machine code, 187 bytes

```
00000000  be 4c 01 31 c9 53 89 e5  68 0a 24 8a 8f 32 01 29  |.L.1.S..h.$..2.)|
00000010  cc 89 e7 f3 a4 83 c3 41  b7 20 86 fb 53 b3 3a 86  |.......A. ..S.:.|
00000020  fb 53 89 e2 b4 09 cd 21  89 ec 5b 43 83 fb 1a 75  |.S.....!..[C...u|
00000030  d4 c3 03 04 06 04 03 06  03 04 04 05 03 03 03 07  |................|
00000040  04 03 05 04 05 04 06 05  06 03 05 03 6c 66 61 72  |............lfar|
00000050  61 76 6f 68 61 72 6c 69  65 65 6c 74 61 63 68 6f  |avoharlieeltacho|
00000060  6f 78 74 72 6f 74 6f 6c  66 6f 74 65 6c 6e 64 69  |oxtrotolfotelndi|
00000070  61 75 6c 69 65 74 69 6c  6f 69 6d 61 69 6b 65 6f  |aulietiloimaikeo|
00000080  76 65 6d 62 65 72 73 63  61 72 61 70 61 75 65 62  |vemberscarapaueb|
00000090  65 63 6f 6d 65 6f 69 65  72 72 61 61 6e 67 6f 6e  |ecomeoierraangon|
000000a0  69 66 6f 72 6d 69 63 74  6f 72 68 69 73 6b 65 79  |iformictorhiskey|
000000b0  72 61 79 61 6e 6b 65 65  75 6c 75                 |rayankeeulu|
000000bb

```

Equivalent assembly code:

```
org 0x100
use16
    mov si, nato
    xor cx, cx
@@: push bx
    mov bp, sp
    push 0x240a
    mov cl, [len+bx]
    sub sp, cx
    mov di, sp
    rep movsb
    add bx, 'A'
    mov bh, ' '
    xchg bh, bl
    push bx
    mov bl, ':'
    xchg bh, bl
    push bx
    mov dx, sp
    mov ah, 0x09
    int 0x21
    mov sp, bp
    pop bx
    inc bx
    cmp bx, 26
    jne @b
    ret

len db 3,4,6,4,3,6,3,4,4,5,3,3,3,7,4,3,5,4,5,4,6,5,6,3,5,3
nato db "lfaravoharlieeltachooxtrotolfotelndiaulietiloimaikeovemberscarapauebecomeoierraangoniformictorhiskeyrayankeeulu"

```
> 1 votes

# Answer
# Vyxal 3, 78 76 bytes

```
m':ᵛ+"vD∦C∑:ḋᵉ∑7ðȮ÷m^¹,ṫ₈Cⁿ«⁾hƒu~Φ∑₈DᴳkƓᶤNGġṀ<ϩɠ←⁰øWᵘ₉Πȧƛ₄∦ιqṘᶴ]←Ṭ}₈NḋẠᵃ”ṂZ'

```

Try it Online!
> 1 votes

# Answer
## Batch, 216 bytes

```
@for %%w in (Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu)do @set l=%%w&call echo %%l:~,1%%: %%l%%

```
> 0 votes

# Answer
# CJam, ~~160~~ 158 bytes

```
'A"lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu"S/{_": "\_)QN@}fQ;

```

Try it online!

**Explanation**

```
'A                         Push the character 'A'
  "..."S/                  Split huge string on spaces
         {           }fQ   For each word Q:
          _                  Duplicate top of stack (the character)
           ": "\             Push ": ", swap top stack elements; results in "A: A"
                _)           Duplicate the char on top and increment it (the next letter)
                  QN         Push Q and a newline
                    @        Bring the third-top element of the stack to the top
                              (brings the next character on top for the next iteration)
                        ;  Delete the top stack element, since at the end there will be a
                            '[' character on top

```
> 0 votes

# Answer
## IBM/Lotus Notes Formula - 195 Bytes

```
L:=@Explode("Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliet Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu");@Left(L;1)+": "+L

```

Formula will by default apply a given function to each value in a list in turn so no `for` loop needed. `@Explode` (equivalent to `split` in other more sensible languages) defaults to `" "`,`","` or `";"` if no separator is supplied in the function call. As an aside, `@Implode` also equates to `join`. I guess formula is a bit too verbose and was not really made for golfing but some of the list operators are still cool and work as well as they did 20 odd years ago.

No TIO available for LN so screenshot shown below:
> 0 votes

# Answer
# C (gcc), 393 bytes

```
#define p printf
long a[]={0x16C,0xf7f13f,0x59c3f18,0x15fc5,0xF83,0x5f0f3f5f9f0f,0x6c0f,0xC55f0f,0x194e,0x5f59c6f,0xfc9,0x1d9,0x5b9,0x3f52d57f0f,0x3f134f,0x11f1,0x35256f,0xf5d0f,0x13f3f59,0xf7e1,0xd3f0f69e,0x3f0f5f39,0xafb4f98,0xaf13f,0x55be1,0x6fc6f};i,j;d(long n){for(;n;n/=16){if(j=n&15){if(j>14)n/=16,j+=n&15;p("%c",96+j);}else n=0;}}r(){for(i=0;i<26;p("\n"))p("%c: %1$c",i+65),d(a[i++]);}

```

I thought it would be shorter than it is. I was wrong..

Each `long int` in `long a[]` represents a word containing the remaining letters of the required mnemonic once the first letter has been removed. Letters are encoded right to left whereby if the 4 lower bits are `0xF` then it adds it to the next 4 bits and shifts it all down appropriately, repeating until the variable is empty.

Try it online!
> 0 votes

# Answer
# C, 199 bytes

```
f(){char*s=" AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu";while(*++s){printf("\n%c: %c"+*s/96*5,*s,*s);}}

```
> 0 votes

# Answer
## Perl, 188 bytes

```
$n=64;$x="LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUlietIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu";while($x=~/.[a-z]*/g){$_=chr(++$n)."\l$&
";s/(.).*/$1: $&/;print}

```

Ungolfed version:

```
$x="LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUlietIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu";
$n=64;
while ($x =~ /([A-Z][a-z]*)/g) {
    $y = chr(++$n) . "\l$1\n";
    $y =~ s/(.)(.*)/$1: $1$2/;
    print $y;
}

```
> 0 votes

# Answer
# Perl, 185 164 163 bytes

Saved 11 12 bytes with help from @manatwork

```
print$a=chr$i+++65,": $a\l$_\n"for split/(?=[A-Z])/,LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUlietIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu

```
> 0 votes

# Answer
## REXX, 192 bytes

```
@='lpha ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu'
do #=1 to 26
  c=d2c(#+64)
  say c':' c||word(@,#)
  end

```
> 0 votes

# Answer
# Java, ~~300~~ 275 bytes

```
interface x{static void main(String[]a){for(int i=0;i<26;i++) System.out.println(String.format("%c: %c%s",'A'+i,'A'+i,"lfa_ravo_harlie_elta_cho_oxtrot_olf_otel_ndia_uliet_ilo_ima_ike_ovember_scar_apa_uebec_omeo_ierra_ango_niform_ictor_hiskey_ray_ankee_ulu".split("_")[i]));}}

```

Ungolfed version with comments:

```
interface x {
    static void main(String[] a) {
        for (int i = 0; i < 26; i++)            // For all characters in alphabet
            System.out.println(                 // Print string
                    String.format("%c: %c%s",   // Formatted string(similar to printf)
                            'A'+i,              // Letter
                            'A'+i,              // Letter
                            "lfa_ravo_harlie_elta_cho_oxtrot_olf_otel_ndia_uliet_ilo_ima_ike_ovember_scar_apa_uebec_omeo_ierra_ango_niform_ictor_hiskey_ray_ankee_ulu".split("_")[i])); // Absurdly long string containing all words without first letters, divided into an array by _
    }
}

```
> 0 votes

# Answer
# q, 167 bytes

Link to interpreter download

```
-1@.Q.A,'": ",/:.Q.A,'" "vs"lpha ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu";

```
> 0 votes

# Answer
# Japt `-R`, 108 bytes

I suspect there may be another byte or 2 to be saved here, possibly by interleaving with the uppercase alphabet, but I'm running out the door so it'll have to do for now.

Note the trailing space.

```
`lfaæ1ÃÉr¦e³ltawÖoxÉwolfÙ*lÙAawªià5¹µ±kewovem¼rws¯r°pawue¼cÙ o±ØÇ¯fmØtØkeyÙ°nkeewªu`qÔËi°Id ²i1":

```

Test it

```
`...`qÔËi°Id ²i1":
`...`                   :Compressed string "lfawravowharlieweltawchowoxtrotwolfwotelwndiawulietwilowimawikewovemberwscarwapawuebecwomeowierrawangowniformwictorwhiskeywraywankeewulu"
     q                  :Split on
      Ô                 :  "w"
       Ë                :Map
        i               :  Prepend
         °I             :    Prefix increment I, initially 64
           d            :    Get character at that codepoint
             ²          :    Repeat twice
              i1":      :    Insert ": " at 0-based index 1
                        :Implicit output joined with newlines

```
> 0 votes

# Answer
# Thunno 2 `N`, 81 bytes

```
’lfaŒ¥ȷþ<ƭ`Ṃ⁸Ø⁽ÄƝḲƲḤJulietƒḍɲḄẠ[Ḷ⁸Ọ¦ṢĖḞɠṘ»oẹ⁽ẓẇṅ⁼ṡ÷ẏƬ»|»⁸“¶’"[A-Z]"ḄkAZıẸD`: +ƤJƤ

```

Attempt This Online!

#### Explanation

```
’...’"[A-Z]"ḄkAZıẸD`: +ƤJƤ  # Full program
’...’                       # Push compressed string "lfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJulietKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu"
     "[A-Z]"Ḅ               # Split on uppercase letters
             kAZ            # Zip with the uppercase alphabet
                ı           # Map over this list of pairs:
                 ẸD         #  Dump onto stack and duplicate the letter
                   `: +     #  Append ": " to one copy
                       Ƥ    #  Prepend this to the other copy
                        JƤ  #  Join and prepend this to the string
                            # Implicit output, joined on newlines

```
> 0 votes

# Answer
# Pip `-l`, ~~132~~ 124 bytes

```
_.": "._MAZ.:J(zA*":yE-HFZ[`\0,A-%[z5/gh4!R
c}FNu3GM%uHk{yKs.B/OVMKb XP14DXDT[Em%
.rUog"FD126TD25)^'w

```

The code contains unprintable characters which do not display correctly on StackExchange. Here's a hexdump:

```
00000000: 5f2e 223a 2022 2e5f 4d41 5a2e 3a4a 287a  _.": "._MAZ.:J(z
00000010: 412a 2205 3a79 452d 4812 465a 5b60 1b5c  A*".:yE-H.FZ[`.\
00000020: 3006 2c41 2d25 5b7a 352f 6768 1008 1334  0.,A-%[z5/gh...4
00000030: 2152 1215 0a63 7d46 4e75 3305 474d 2575  !R...c}FNu3.GM%u
00000040: 1048 6b7b 794b 732e 1c42 2f4f 5619 4d07  .Hk{yKs..B/OV.M.
00000050: 074b 6220 5850 1131 3444 5844 545b 456d  .Kb XP.14DXDT[Em
00000060: 250a 191b 172e 1b72 0117 5517 6f67 2246  %......r..U.og"F
00000070: 4431 3236 5444 3235 295e 2777            D126TD25)^'w

```

Attempt This Online!

### Explanation

Similar compression approach to another recent kolmo answer:

```
_.": "._MAZ.:J(zA*"..."FD126TD25)^'w
                  "..."               String of characters
                A*                    Get ASCII code of each
                       FD126          Treat those as base-126 digits and convert
                                      to base 10
                            TD25      Convert to list of base-25 digits
              (z                )     Index into lowercase alphabet
             J                        Join into a single string
                                 ^'w  Split on w's
                                      This gives a list ["lpha";"ravo";...;"ulu"]
         AZ                           Uppercase alphabet
        M                             Map this function to each letter:
_                                      The letter
 .": "                                 Concatenate colon-space
      ._                               Concatenate the letter again
           .:                         Concatenate that list itemwise with the list
                                      from earlier
                                      Print each on a separate line (-l flag)

```

Base 126 was chosen to avoid having any `"` characters in the string.
> 0 votes

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


title: Make 1's and 2's composite

text:
# Question
Title: Make 1's and 2's composite
# Input

An integer `k` composed of `1` and `2`, with at least 3 digits and at most 200 digits.

# Output

Another integer `k'` obtained by removing **at most** one (**could be none**) digit from `k`, such that `k'` is composite, and then another integer `p` for a non-trivial (that is, not 1 or `k'`) factor of `k'`.

# Test Cases

```
121212 -> 121212 10101
11121 -> 1112 506
12211 -> 2211 201
2122121211212 -> 2122121211212 2
212221112112211 -> 21221112112211 4933994911

```

Assume that there is always a valid output.

# Answer
> 4 votes
# Jelly,  ~~15~~  13 bytes

```
DŒPḌẒÐḟṪÆḌṪṭƊ

```

A monadic Link that accepts an integer, `k`, and yields a pair of integers, `[k', p]`.

**Try it online!**

### How?

Creates the powerset of `k`s digits to look for candidates for `k'`. Jelly produces powersets that are sorted by length, so `k` will be at the right and all other *valid* `k'` candidates to the right of any other junk.

The code then takes, as `k'`, the rightmost that is not prime (due to length this is also composite), which will either be `k` or `k` less one of its digits. It then tacks on the largest proper divisor of this, `p`.

```
DŒPḌẒÐḟṪÆḌṪṭƊ - Link: integer, k         e.g. 212
D             - decimal digits {k}            [2,1,2]
 ŒP           - powerset                      [[],[2],[1],[2],[2,1],[2,2],[1,2],[2,1,2]]
   Ḍ          - convert from decimal digits   [0,2,1,2,21,22,12,212]
     Ðḟ       - discard those for which:
    Ẓ         -   is prime?                   [0,1,21,22,12,212]
       Ṫ      - tail                          212
            Ɗ - last three links as a monad - f(k'=that):
        ÆḌ    -   proper divisors of k'       [1,2,4,53,106]
          Ṫ   -   tail                        106
           ṭ  -   tack to k'                  [212,106]

```

# Answer
> 4 votes
# Vyxal 3, 12 bytes

```
ι*J⌊ᵐϩṄ¬:ḟh;

```

Try it Online!

Outputs largest possible `k'` and the first prime factor. Takes input as a string

## Explained

```
ι*J⌊ᵐϩṄ¬:ḟh;
ι             # Range 0 -> len input
 *            # And to each index, remove the letter at that position in the input
  J           # Add the input to that list so the unaltered input is an option
   ⌊          # Convert each to int
    ᵐϩ        # Get the maximum by
      Ṅ¬      # Not a prime
        :ḟ    # Push a list of prime factors of that without popping
          h;  # And pair the first of those with k'

```

Created with the help of Luminespire.

# Answer
> 3 votes
# Brachylog, 7 bytes

```
⊇PḋṀh;P

```

Try it online!

Outputs a list with the factor `p` first, and `k'` second.

### Explanation

Since it’s been proven in a comment that it’s always possible for any input, we can state that P is a subset of the input without specifying the number of digits to remove. Since  will try the biggest subsets first (including the original input), it will succeed with at most 1 digit removed.

```
⊇P         P is an integer which is a subset of the input integer
  PḋṀ      P has Ṁany prime ḋivisors (at least 2, so P is composite)
    Ṁh;P   Output = [First prime divisor of P, P]

```

# Answer
> 2 votes
# JavaScript (Node.js), 64 bytes, string input

```
f=(x,p=9n)=>BigInt(a=x.replace(p%3n,''))%(b=p/3n)?f(x,-~p):[a,b]

```

Try it online!

# JavaScript (Node.js), 68 bytes

```
f=(x,k=1n,p=3n)=>(a=x%k+x/k/10n*k)>p>a%p?[a,p]:f(x,p>5?k*10n:k,8n^p)

```

Try it online!

Fast. Use fact that input is only 1 and 2.

> Proof that it's always possible: For all 1 or 2, remove one digit if odd number of digits, then it's always 11x10101; Otherwise, one of keep, remove a 1, and remove a 2 result 0 modulo 3
>
> Neil：Edge case `111` falls under `0 modulo 3` case.

# Answer
> 2 votes
# JavaScript (ES11), 60 bytes

Similar to l4m2's strategy, but we first test whether \\$11\\$ is a divisor of either \\$n\\$ or \\$\lfloor n/10\rfloor\\$ before considering removing a digit according to \\$n\bmod 3\\$.

Expects a BigInt and returns `"k',p"` as a comma-separated string.

```
n=>(x=n)%11n&&(x/=10n)%11n?`${n},3`.replace(n%3n,""):x+[,11]

```

Try it online!

---

# JavaScript (ES6), 51 bytes

A more limited version without BigInts. This time we first attempt to remove a digit and move to \\$p=11\\$ only on failure.

Expects a string and returns `[k',p]`.

```
n=>(q=n.replace(n%3,''))%3?[q%11?q/10|0:q,11]:[q,3]

```

Try it online!

# Answer
> 2 votes
# Charcoal, 26 bytes

```
Ｉ⮌⌈ＥＩＥ³Φθ⁻μ⌕θＩι⟦⌈Φι∧λ¬﹪ιλι

```

Try it online! Link is to verbose version of code. Explanation: Just tries removing one `1` and one `2` since by @l4m2's comment at least one of the two or three numbers will be composite. (Removing every possible digit turns out to take the same length but it will of course be slower.)

```
      ³                     Literal integer `3`
     Ｅ                      Map over implicit range
        θ                   Input as a string
       Φ                    Filtered where
          μ                 Current index
         ⁻                  Does not equal
           ⌕                Index of
              ι             Outer value
             Ｉ              Cast to string
            θ               In input string
    Ｉ                       Cast to integer
   Ｅ                        Map over values
                  ι         Current value
                 Φ          Filter on implicit range
                    λ       Inner value
                   ∧        Logical And
                       ι    Outer value
                     ¬﹪     Is divisible by
                        λ   Inner value
                ⌈           Take the maximum
                         ι  Current value
               ⟦            Make into list
  ⌈                         Take the maximum
 ⮌                          Reversed
Ｉ                           Cast to string
                            Implicitly print

```

31 bytes for a very fast version which only looks for factors below `12` (except for `11` itself, which is a special case):

```
Ｉ⮌⌈ＥＩＥ³Φθ⁻μ⌕θＩι⟦⌈Φ⌊⟦¹²ι⟧∧λ¬﹪ιλι

```

Try it online! Link is to verbose version of code.

# Answer
> 1 votes
# Retina 0.8.2, 47 bytes

```
.|$
$`$'¶
.+
$*
1G`^(..+)\1+$
(..+)\1+$
$.& $.1

```

Try it online! Link includes faster test cases. Removes the earliest possible digit. Explanation:

```
.|$
$`$'¶

```

List the number with each digit removed in turn, then end with the original input.

```
.+
$*

```

Convert all of the numbers to unary.

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

```

Keep only the first composite number.

```
(..+)\1+$
$.& $.1

```

Convert it and its highest proper factor to decimal.

In Retina 1 you would be able to fold those last two stages into a single stage, something like this:

```
0L$m`^(..+)\1+$
$.& $.1

```

(The `m` flag is not needed in Retina 0.8.2 because there the `G` stage type splits the input into lines and then matches each line in turn against the regex.)

# Answer
> 1 votes
# Pyth, 12 bytes

```
eP
e-#PTsMy`

```

Try it online!

### Explanation

```
                # implicitly assign Q = eval(input())
ePe-#PTsMy`Q    # implicitly add Q
          `Q    # str(Q)
         y      # powerset
       sM       # map to integers
   -#PT         # filter for non-primes
  e             # print last value in list
eP              # print largest prime factor of value

```

# Answer
> 0 votes
# Vyxal 3 `o`, 18 bytes

```
Ṅ[ṢḶṪ⸠LĠt“⌊ᶻṄh]ỌḄt

```

Try it Online!

prints k' and the largest prime factor

```
Ṅ[ṢḶṪ⸠LĠt“⌊ᶻṄh]ỌḄt
Ṅ                   # is prime?
 [                  #
  ṢḶṪ               # group sublists by length and drop the tail
     ⸠LĠt           # group by max length, take the longest
         “⌊ᶻṄ       # convert to number and filter by not prime
             h      # take the first number left
              ]     #
               Ọ    # print k'
                Ḅt  # largest prime of k'

```

Created with the help of Luminespire.

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
æʒp≠}θDÒθ‚

```

Try it online or verify all test cases.

**Explanation:**

```
æ        # Get the powerset of the (implicit) input
 ʒ       # Filter, only keeping those which are:
   ≠     #  NOT
  p      #  a prime number
 }θ      # After the filter: pop and keep the last/maximum
   D     # Duplicate it
    Ò    # Pop and get its prime factors
     θ   # Pop and keep the last/maximum again
      ‚  # Pair the two together
         # (after which this pair is output implicitly as result)

```

The `ʒp≠}` can be a number of other things with a similar result: `ÐpÏK`; `DÒ˜K`; `¤ÅPK`.

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


title: Verify a Minesweeper board

text:
# Question
Title: Verify a Minesweeper board
Your goal is to check whether a completed Minesweeper board is valid. This means that each number is a correct count of mines in cells adjacent to it, including diagonals. The board does not wrap around.

As usual, you should give a function or program, and shortest code in bytes wins.

See also past challenges to generate, solve, and fully implement Minesweeper.

**Input:**

A single string like this: `02X2 13X2 X211`.

* The rows of the minesweeper board are given separated by spaces. So, the above represents the 3x4 board:

`02X2`
`13X2`
`X211`
* Each cell is a character: `X` for a mine, or a number `0` through `8`.
* All rows have the same length.
* There are at least 3 rows and 3 columns.
* The input doesn't start or end with a space, but you may include a newline at the end if you wish.

**Output:**

A consistent Truthy on correct boards, and a consistent Falsey value on incorrect boards. *Consistent* means that all Truthy outputs are the same and all Falsey outputs are the same.

**Test cases**

Each line is a separate test case.

`True`:

```
02X2 13X2 X211
XXXX XXXX XXXX XXXX
XX4X2 5X6X4 XX6XX 4XX54 2X4XX

```

`False`:

```
02X2 13X2 X212
XXXX XXXX X7XX XXXX
XX5X2 5X6X4 XX6XX 4XX54 2X5XX

```

# Answer
> 12 votes
# Python 2, ~~132 129~~ 128

```
def f(s):w=s.find(' ');E=dict(enumerate(s));return all(E[i]in' X'+`sum(E.get(i+d/3*~w+d%3+w,5)>'O'for d in range(9))`for i in E)

```

I used `enumerate` in a golf...and even used `range` elsewhere in the same program. Clearly something is wrong here.

Edit: Iterate over `dict(enumerate(s))` rather than `enumerate(s)`, so `enumerate` does not need to be called twice.

# Answer
> 10 votes
# Pyth, 43

```
Jhxzd!f-@zT+" X"`sm/:+*JNztd+d2\Xm+T*kJU3Uz

```

Try it here.

**Explanation:**

* `Jhxzd`: This is the location of the first space in the input + 1. (`z` in the input, `d` is space.) It is the separation in the input between vertically adjacent cells on the board.
* `!f`: This is the logical not (`!`) of a filter (`f`), which will be `True` if and only if the expression is falsy for every element of the sequence.
* `-@zT`: Take the character at location `T` (the lambda variable) from the input, and remove any appearances of: (This will be truthy if the character is not removed, and falsy if it is.
* `+" X"`: Remove space, X, and
* ```: Repr of
* `sm`: sum of map to
* `/ \X`: count of "X" in
* `:+*JNz`: The slice of the input prefixed by `J` dummy characters
* `td+d2`: From d-1 to d+2.
* `m+T*kJU3`: For d in \[T, T+J, T+2\*J\].
* `Uz` For T in `range(len(input))`.

# Answer
> 7 votes
## APL (NARS2000) (74)

```
{~0∊(G>9)∨G=(⍴G)↑{+/∊9<⍵∘⌷¨G∘.⊖(G←2-⍳3)∘.⌽⊂Z}¨⍳⍴Z←G↑⍨2+⍴G←¯1+⎕D⍳⊃⍵⊂⍨⍵≠' '}

```

Also works in Dyalog APL if `⎕ML` is set to `3`.

Explanation:

* `⊃⍵⊂⍨⍵≠' '`: split  on the spaces and use the lists to form a matrix.
* `G←¯1+⎕D⍳`: find the index in `⎕D` for each value, subtract 1, and store this in `G`. (`⎕D` contains the digits, any non-digit will turn into `10`).
* `Z←G↑⍨2+⍴G`: add two lines and columns of zeroes at the edge of the matrix, to deal with the wraparound
* `{`...`}¨⍳⍴Z`: for each position in `Z`, find the amount of bombs in the Moore neighbourhood of that position:
    + `G∘.⊖(G←2-⍳3)∘.⌽⊂Z`: rotate `Z` left, right, up, down, left-up, right-up, left-down, and right-down.
    + `⍵∘⌷¨`: for each of these, find the element at  in each of these rotated matrices
    + `+/∊9<`: count how many elements are higher than 9 (this is the amount of bombs).
* `(⍴G)↑`: remove the added lines of zeroes again,
* `G=`: check whether each element in `G` is equal to the amount of bombs surrounding that position (this should be true for all non-bomb squares),
* `(G>9)∨`: and check whether the elements in `G` are higher than `9` (these are the bombs).
* `~0∊`: return `1` if the resulting matrix contains no zeroes (=all squares are either bombs or the correct number), and `0` if it does.

# Answer
> 5 votes
# C#, 321 320 305

```
bool s(string B){var L=B.Split(' ').Select(s=>' '+s+' ').ToList();var b=new string(' ',L[0].Length);L.Insert(0,b);L.Add(b);Func<int,int,IEnumerable<int>>E=Enumerable.Range;return E(1,b.Length-2).All(x=>E(1,L.Count-2).All(y=>L[y][x]=='X'||L[y][x]-'0'==E(x-1,3).Sum(X=>E(y-1,3).Sum(Y=>L[Y][X]=='X'?1:0))));}

```

First attempt golfing anything, and I know that C# isn't the ideal language.

I hope writing an instance method is allowed, otherwise add another 7 characters for `static`.

Spaced out:

```
bool s(string B) {
    var L = B.Split(' ').Select(s => ' ' + s + ' ').ToList();
    var b = new string(' ', L[0].Length);
    L.Insert(0, b);
    L.Add(b);
    Func<int, int, IEnumerable<int>> E = Enumerable.Range;
    return E(1, b.Length - 2).All(x =>
        E(1, L.Count - 2).All(y =>
            L[y][x] == 'X' ||
            L[y][x] - '0' == E(x - 1, 3).Sum(X =>
                E(y - 1, 3).Sum(Y =>
                  L[Y][X] == 'X' ? 1 : 0))));
}

```

Using Linq saves some space compared to for loops, but it's harder to debug.

I learned a few things like converting `char => int` by subtracting `'0'`.

It seemed simpler to pad out the board with spaces so iterating over it would be easier.

# Answer
> 5 votes
## Python 2, 121

```
def f(B):n=B.find(' ')+1;R=range(len(B));print all(B[I]in' X'+`sum(2>I%n-i%n>-2<I/n-i/n<2<B[i]>'W'for i in R)`for I in R)

```

This is heavily inspired by feersum's answer. The order of the day is overkill: rather than checking for mines in the 9 neighbors of the cell, check every single cell to see whether it's a neighboring mine.

We check if two cells are neighbors with `2>r>-2<c<2`, where `r` and `c` are the row and column differences of cells, equivalent to `{r,c}<{-1,0,1}`. These coordinates are computed from the cell indices `I` and `i` as `c=I%n-i%n` and `r=I/n-i/n`. It's more efficient to index directly into the string and extract rows and columns than to convert it to a 2D object like a list of lists. The mine check is `B[i]>'W'`, equivalent here to `B[i]=='X'`.

Using `enumerate` would have saved two characters over the ugly `range(len(B))` except that it returns an iterator object which does not support two nested loops through it.

# Answer
> 4 votes
# Python 2, 140

```
s=input();w=s.index(' ')+1
print all(c in'X 'or(int(c)==sum(s[max(0,a-1):max(0,a+2)].count('X')for a in[i-w,i,i+w]))for i,c in enumerate(s))

```

# Answer
> 4 votes
# JavaScript (ES6), ~~135~~ ~~133~~ ~~125~~ 122

```
f=s=>s.split(" ")[e="every"]((l,i,a)=>[...l][e]((c,j)=>!(-[-1,0,k=1][e]((y,m,q)=>q[e](x=>k+=(a[i+y]||0)[j+x]=="X"))-c+k)))

```

Provide input to the function as a string:

```
f("XX4X2 5X6X4 XX6XX 4XX54 2X4XX");

```

For an explanation, see the old version, below. The new version replaces the `for` loops with `every` calls, and uses the variable `e="every"` to do `someArray[e](...)` instead of `someArray.every(...)`.

Also, the counter `k` is now indexed at `1` so that the `k+=...` expression is always truthy, in order to keep the `every` loop running. We eliminate that extra `1` by subtracting the `true` result (which numerically coerces to `1`) returned by the `every` operation `[-1,0,k=1][e](...)`.

---

Old version:

```
f=s=>s.split(" ").every((l,i,a)=>[...l].every((c,j)=>{q=[-1,k=0,1];for(y of q)for(x of q)k+=(a[i+y]||0)[j+x]=="X";return c=="X"||k==c}))

```

Code with spaces and comments:

```
f=s=>s.split(" ")                 // split on spaces
      .every((l,i,a)=>             // for every line
                                   //     l: line string, i: line number, a: whole array
          [...l].every((c,j)=>{    // for every character
                                   //     c: character, j: index in string
              q=[-1,k=0,1];        // define counter k=0 and q=[-1,0,1]
              for(y of q)          // use q to loop adjacent spaces
                  for(x of q)

                      k+=              // add the following boolean to k:

                          (a[i+y]      //   from line number i+y...
                                 ||0)  //   (or a dummy zero, to prevent lookups on undefined)
                          [j+x]        //   ...get index j+x from the above value...
                                =="X"; //   ...and compare it to "X"

              return !(k-c)     // after the loop, this character passed if
                                // the char equals the number of counted X's (so k-c is 0)
                                // or it is an X itself (so `k-c` is NaN)
          })
      )

```

The JavaScript `every` array method takes a callback and applies the callback to every element of the array. If any callback returns a falsey value, the `every` call returns `false`.

Booleans in JS are coerced to 1 or 0 when part of an addition. For each surrounding space, we "add" the boolean result of comparing its value to `X` and then add that value to the counter `k` in the expression `k += (... == "X")`. Therefore, `k` contains a count of the number of surrounding `X`s, because `true` counts as `1` and `false` counts as `0`.

# Answer
> 3 votes
# CJam, ~~70 65~~ 63 bytes

```
1l_S#):L)S*+:Q{Ii33/2%[0~1LL)L(L~)L~_))]W):Wf+Qf='X/,(scI==&}fI

```

This can be golfed a lot.

Gives `1` for a valid board and `0` for an invalid board.

**Test cases**

```
{-1:W;
1l_S#):L)S*+:Q{Ii33/2%[0~1LL)L(L~)L~_))]W):Wf+Qf='X/,(scI==&}fI
}6*]N*

```

Input

```
02X2 13X2 X211
XXXX XXXX XXXX XXXX
XX4X2 5X6X4 XX6XX 4XX54 2X4XX
02X2 13X2 X212
XXXX XXXX X7XX XXXX
XX5X2 5X6X4 XX6XX 4XX54 2X5XX

```

Output

```
1
1
1
0
0
0

```

Try it online here

# Answer
> 3 votes
# JavaScript (ES6) 98

Using *some* to apply a function to each character of the string.
The function returns

* false if blank
* NaN if 'X' (repeatedly subtracting values from a non numeric char like 'X' gives NaN)
* A numeric value of 0 if there are the right number of adiacent 'X', else non 0.
The inner check is made using *map* just because it's shorter than *forEach*

*some* returns true at the first truthy value (in this case, nonzero) meaning a failed check. The result is negated to give a more recognizable true/false.

```
F=v=>![...v].some(
  (x,p)=>x!=' '&&[1,-1,l=v.search(' '),-l,++l,-l,++l,-l].map(q=>x-=v[p+q]=='X')|x
)

```

**Test** In FireFox / FireBug console

```
;["02X2 13X2 X212","XXXX XXXX X7XX XXXX","XX5X2 5X6X4 XX6XX 4XX54 2X5XX"
,"02X2 13X2 X211","XXXX XXXX XXXX XXXX","XX4X2 5X6X4 XX6XX 4XX54 2X4XX","111 1X1 111"]
.forEach(t => console.log(t, F(t)))

```

*Output*

```
02X2 13X2 X212 false
XXXX XXXX X7XX XXXX false
XX5X2 5X6X4 XX6XX 4XX54 2X5XX false
02X2 13X2 X211 true
XXXX XXXX XXXX XXXX true
XX4X2 5X6X4 XX6XX 4XX54 2X4XX true
111 1X1 111 true

```

# Answer
> 1 votes
# R, 156 chars

```
a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v])

```

With indents, spaces and line breaks, for legibility:

```
a = b = do.call(rbind,strsplit(scan(,""),"")) #Reads stdin and turn into a matrix
for(i in 1:nrow(a)) #Ugly, ugly loop
    for(j in 1:ncol(a))
        b[i,j] = sum(a[abs(i-row(a))<2 & abs(j-col(a))<2]=="X")
v = a!="X"
all(b[v]==a[v])

```

Examples:

```
> a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v])
1: XX4X2 5X6X4 XX6XX 4XX54 2X4XX
6:
Read 5 items
[1] TRUE
> a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v])
1: XXXX XXXX XXXX XXXX
5:
Read 4 items
[1] TRUE
> a=b=do.call(rbind,strsplit(scan(,""),""));for(i in 1:nrow(a))for(j in 1:ncol(a))b[i,j]=sum(a[abs(i-row(a))<2&abs(j-col(a))<2]=="X");v=a!="X";all(b[v]==a[v])
1: XX5X2 5X6X4 XX6XX 4XX54 2X5XX
6:
Read 5 items
[1] FALSE

```

# Answer
> 1 votes
# Vyxal 3 `g`, 23 bytes

```
Ṃᵛf:Þȯᵛᵛ'XCZᵗZ⌊ᵛᶻ0cᵛᵛ≈f

```

Try it Online!

---
Tags: code-golf, game, grid, minesweeper
---


title: Is my Graph Graceful?

text:
# Question
Title: Is my Graph Graceful?
A Graceful Graph is a type of Simple Graph. Graceful graphs are special because there is a way to label all their nodes with positive integers so that when the edges are also labeled with the differences of the nodes they connect, no two edges have the same label and every label up to the number of edges is used.

## Worked Out Example

Here is a Simple graph that we suspect is a Graceful graph

Let us try the following labeling:

Note we are permitted to skip integers in our node labeling. Now we label every edge with the positive difference between the nodes it connects. For increased visibility I have labeled these in red.

Each edge has a unique number and no number between between 1 and 7 (the number of edges we have) is left out. Thus our graph is graceful.

# Task

Given a graph, via any reasonable method of input, output a truthy value if it is graceful and a falsy value otherwise.

This is so the objective is to minimize your byte count.

## Test Cases

Here graphs are represented as an array of edges:

```
3 nodes:

[(0,1),(0,2),(1,2)]

True

Labeling:

Node 0 -> 0
Node 1 -> 2
Node 2 -> 3

```

---

```
5 nodes:

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

False

```

---

```
5 nodes:

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

True

Labeling:

Node 0 -> 0
Node 1 -> 1
Node 2 -> 3
Node 3 -> 6
Node 4 -> 10

```

---

```
9 nodes

[(0,1),(1,2),(1,7),(1,8),(2,3),(2,6),(3,4),(4,5)]

True

Labeling:

Node 0 -> 0
Node 1 -> 1
Node 2 -> 3
Node 3 -> 6
Node 4 -> 10
Node 5 -> 15
Node 6 -> 11
Node 7 -> 7
Node 8 -> 8

```

---

```
5 nodes

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

False

```

# Answer
> 6 votes
# Jelly, 12 bytes

```
FSŒ!ị@€ḅ-AċJ

```

Takes an array of edges as 1-indexed node pairs.

Try it online! (Horrendously inefficient. Don't bother with the actual test cases.)

### How it works

```
FSŒ!ị@€ḅ-AċJ  Main link. Argument: A (array of pairs)

FS            Flatten and sum, yielding s. This is an upper bound for the labels
              a graceful labeling (if one exists) would require.
  Œ!          Take all permutations of [1, ..., s].
      €       For each permutation P:
    ị@          Replace each integer in A with the element of P at that index.
       ḅ-     Convert all pairs from base -1 to integer, mapping (a,b) to b-a.
         A    Take absolute values.
           J  Yield the indices of A, i.e., [1, ..., len(A)].
          ċ   Count the occurrences of [1, ..., len(A)] in the result to the left.

```

# Answer
> 4 votes
## Mathematica, 121 116 bytes

*Edit: Saved 5 bytes thanks to JungHwan Min and Martin Ender*

```
Cases[Range[1+Tr[n=Range@Length[e=EdgeList@#]]]~Tuples~VertexCount@#,w_/;Sort[Abs[#-#2]&@@w[[List@@#]]&/@e]==n]!={}&

```

## Explanation

Pure function which takes a Mathematica `Graph` object with vertices `{1, 2, ..., k}` for some nonnegative integer `k`. In the worst case, we will only need vertex labels ranging from `1` to `1 + (1 + 2 + ... EdgeCount@#)`. Since it saves us some bytes later, we will let `e` be the list of edges and `n` be the list `{1, 2, ..., EdgeCount@#}`, so the vertex weights will be drawn from `Range[1+Tr[n=Range@Length[e=EdgeList@#]]]`. We generate a list of all `Tuples` of length `VertexCount@#`, then we choose the `Cases` which give graceful labelings and check to see that the result is `Unequal` to the empty list `{}`. Gracefulness of the list of vertex weights `w` is checked by `Map`ping the function `Abs[#-#2]&@@w[[List@@#]]&` over the list of edges `e`, `Sort`ing the result, and checking whether the result is `Equal` to `n`. Here is a breakdown of that function:

```
               List@@#     Replace the Head of the edge with List; i.e., UndirectedEdge[a,b] becomes {a,b}.
            w[[       ]]&  Select the corresponding vertex weights from the list w.
          @@               Replace the Head of that expression (List) with the function
Abs[#-#2]&                   which returns the absolute difference between its first two arguments.
                           This effectively passes the vertex weights into the absolute difference function.

```

# Answer
> 1 votes
# Python3, 449 bytes

```
R=range
def f(g):
 q=[(v:={**{i:-1 for j in g for i in j},0:0},[],{*v}-{0})]
 while q:
  m,e,n=q.pop(0)
  if not n:
   if all(i in e for i in R(1,len(g)+1)):return m
   continue
  for i in n:
   if(k:=[N for j in g if i in j and m[(N:=j[j[1]!=i])]!=-1]):
    y=[m[N]for N in k]
    for o in{*R(min(y)+1,max(y)+len(g)+1)}-{*m.values()}:
     E=[abs(Y-o)for Y in y]
     if all(U not in e and U<=len(g)for U in E):q+=[({**m,i:o},e+E,n-{i})]
    break

```

Try it online!

---
Tags: code-golf, decision-problem, graph-theory
---


title: Return neighbors index in an 3x3 grid

text:
# Question
Title: Return neighbors index in an 3x3 grid
Alright, my second attempt at a code golf, let's see how this goes.

Pretend you have a 3x3 grid of digits, from 0 to 8:

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

```

Return the neighbors the input has as indexes of the array.

**Rules:**

* It's code golf, so shortest answer wins.
* The pretend array's index can start at 0 or 1. (all examples use 0 though)
* The submission can be just a procedure/function/method, but an example would be nice
* The returned value can be in any order (if the input is `0` you could output either `13` or `31`)
* If you want, the output can be a list of numbers, e.g. `[0,4,6]` instead of `046`
* Diagonals don't count, as shown by the examples.

**Examples:**

```
0 -> 13
3 -> 046
4 -> 1357

```

# Answer
# Jelly, ~~16~~ 13 bytes

```
9Ḷ,d3ạ/S€=1T’

```

Try it online!

### How it works

```
9Ḷ,d3ạ/S€=1T’  Main link. Argument: n (0, ..., 8)

9              Set the return value to 9.
 Ḷ             Unlength; yield [0, ..., 8].
  ,            Pair; yield [[0, ..., 8], n].
   d3          Divmod 3; yield [[[0, 0], ..., [2, 2]], [n:3, n%3]]].
     ạ/        Reduce by absolute difference, yielding
               [[|0 - n:3|, |0 - n%3|], ..., [[|2 - n:3|, |2 - n%3|]].
       S€      Sum each, yielding
               [|0 - n:3| + |0 - n%3|, ..., [|2 - n:3| + |2 - n%3|].
         =1    Compare the sums with 1.
           T   Truth; yield all 1-based indices of 1.
            ’  Decrement to yield all 0-based indices of 1.

```
> 2 votes

# Answer
# MATL, ~~17~~ 16 bytes

```
9:qWIe1Y6Z+i)BPf

```

The array is 1-based, that is, contains numbers from `1` to `9`.

Try it online! Or verify all test cases.

### Explanation

Consider input `2` as an example.

```
9:q  % Push [0 1 2 ... 8]
     % STACK: [0 1 2 ... 8]
W    % Rise to 2, element-wise
     % STACK: [1 2 4 ... 256]
Ie   % Reshape as 3-row matrix (column-major order)
     % STACK: [1   8  64;
               2  16 128;
               4  32 256]
1Y6  % Push [0 1 0; 1 0 1; 0 1 0]
     % STACK: [1   8  64;
               2  16 128;
               4  32 256],
              [0   1   0;
               1   0   1;
               0   1   0]
Z+   % Convolution, maintaining size
     % STACK: [10  81 136;
               21 170 336;
               34 276 160]
i    % Take input, n
     % STACK: [10  81 136;
               21 170 336;
               34 276 160],
               2
 )   % Get n-th entry (1-based; column-major order)
     % STACK: 21
B    % Convert to binary
     % STACK: [1 0 1 0 1]
P    % Flip
     % STACK: [1 0 1 0 1]
f    % Find: gives indices of nonzeros. Implicitly display
     % STACK: [1 3 5]

```
> 9 votes

# Answer
## Mathematica, 32 bytes

```
GridGraph@{3,3}~AdjacencyList~#&

```

Uses a graph instead of an array. `GridGraph@{3,3}` constructs a 3x3 grid-shaped graph, shown below, which Mathematica helpfully labels with the numbers 1–9 for the vertices by default. Then `~AdjacencyList~#&` tells you the neighbours of a vertex.
> 6 votes

# Answer
# Mathematica, 40 bytes

```
{24,135,26,157,2468,359,48,579,68}[[#]]&

```

1-indexed. Just looks up the answer. Can someone do better in Mathematica?
> 4 votes

# Answer
# Octave, ~~42~~ ~~40~~ 39 bytes

```
@(n,x=~e(3),y=x(n)=1)find(bwdist(x)==1)

```

1-based index.

Verify all test cases.

Explanation:

```
x=~e(3);         % create a 3*3 matrix of zeros
x(n)=1;          % set the element with index n to 1
d=bwdist(x);     % compute the distance transform of the matrix
find(d == 1)     % find where the distance is 1.

```

Example: `n = 2`

```
x =

   0   0   0
   1   0   0
   0   0   0

```

(In Octave data is stored column-wise.)

```
d =

   1.00000   1.41421   2.23607
   0.00000   1.00000   2.00000
   1.00000   1.41421   2.23607

```

logical index where distance is 1:

```
d == 1

 1   0   0
 0   1   0
 1   0   0

find(d ==1)

 1
 3
 5

```
> 4 votes

# Answer
# Python 2, 71 bytes

```
lambda n:filter(abs,[(n-3)*(n>3),(n+3)*(n<7),~-n*(n%3!=1),-~n*(n%3>0)])

```

1-indexed
Try it online!

---

Getting the result from a predefined list of results is shorter (46 bytes):

```
[13,204,15,406,1357,248,37,468,57].__getitem__

```

0-indexed
Try it online!
> 3 votes

# Answer
# C, ~~100~~ ~~92~~ ~~91~~ ~~83~~ ~~78~~ 74 bytes

```
p(n){putchar(n+48);}f(n){n>3&&p(n-3);n<7&&p(n+3);n%3&&p(n+1);--n%3&&p(n);}

```

1-indexed. Thanks to @Neil for saving 4 bytes.

Try it online!

**Hardcoded version, 56 bytes**

```
l[]={13,204,15,406,1357,248,37,468,57};
#define L(n)l[n]

```

0-indexed
> 2 votes

# Answer
# Haskell, ~~74 71~~ 68 bytes

```
f n=[x|x<-[n-3,n-1..n+3],0<x,x<10,gcd 3x<2||n-1/=x,gcd 3n<2||n+1/=x]

```

Try it online! Uses a 1-indexed grid. Example usage: `f 3` returns `[2,6]`.

Edit: Saved ~~3~~ 6 bytes thanks to Ørjan Johansen!

---

For ~~77~~ 75 bytes, the following function `#` works for an arbitrary grid size `m`:

```
n#m=[x|x<-[n-m,n-1,n+1,n+m],0<x,x<=m*m,gcd x m<m||n-1/=x,gcd n m<m||n+1/=x]

```

Try it online! For each `n` the list `[n-m,n-1,n+1,n+m]` contains all four neighbours. For each entry `x` in this list we check `-1<x` and `x<m*m` to make sure `x` is not above or below the grid, `mod n 3>0||n-1/=x` to enforce the left grid border and `mod(n+1)m>0||n+1/=x` for the left border.
> 2 votes

# Answer
# Ruby, ~~51 48~~ 45 bytes

```
->a{[a+3,a-3][a/6..a/3]+[a+1,a-1][a%-3..a%3]}

```

Try it online!

Create 2 arrays, with vertical and horizontal neighbours, then select one or more of them.

### Ruby hardcoded, 44 bytes

```
->a{%w(13 024 15 046 1357 248 37 468 57)[a]}

```

... Not worth it.
> 2 votes

# Answer
# Python 2, 51 bytes

```
lambda x:[x+3,x-3][x/6:x/3+1]+[x+1,x-1][x%-3:x%3+1]

```

Based on a previous version of my Ruby answer, I found it interesting because it was mostly the same code, using a different trick, and produces the same result. Getting this one right helped me golf the ruby answer a little more.

Basically, ruby has it shorter because the array slice index are inclusive, python needs a `+1` to compensate.

### Explanation

Get the 2 arrays (vertical and horizontal neighbours), then select one or both based on some calculations.
> 2 votes

# Answer
# Java 7, 63 bytes (hardcoded)

```
int c(int i){return new int[]{31,420,51,640,7531,842,73,864,75}[i];}

```

0-indexed
(Reversed order output because `024` and `046` aren't valid integers.)
~~Still working on a non-hardcoded version, but~~ I can assure you it won't be shorter..

Try it here.

---

**82 bytes**

```
String c(int n){return""+(n>3?n-3:"")+(n<7?n+3:"")+(n%3>0?n+1:"")+(--n%3>0?n:"");}

```

1-indexed
Based on *@Steadybox*' C answer

Try it here.
> 1 votes

# Answer
# Vyxal 3, 9 bytes

```
kd⁻ṪÞo1⁾i

```

Try it Online!

```
kd⁻ṪÞo1⁾i
        i  # value of program at index of input
kd⁻Ṫ       # digits 0-8 in a 3x3 square
    Þo     # grid neighbors
      1⁾   # flatten by 1

```

Created with the help of Luminespire.
> 1 votes

# Answer
# APL (Dyalog Classic), 34 bytes

```
⌷∘42 531 62 751 8642 953 84 975 86

```

1-indexed, hardcodes the values :(

Try it online!
> 1 votes

# Answer
# JavaScript + lodash, 71 bytes

```
f=a=>_.range(9).filter(b=>a>b?f(b).includes(a):[,1,,1][b-a]&&b%3|a%3<2)

```
> 0 votes

# Answer
## Batch, 116 bytes

```
@set c=cmd/cset/a%1
@set/ar=%1%%3
@if %1 gtr 2 %c%-3
@if %r% gtr 0 %c%-1
@if %r% lss 2 %c%+1
@if %1 lss 6 %c%+3

```

0-indexed.
> 0 votes

---
Tags: code-golf, grid
---