title: A Tiny Explorer

text:
# Question
Title: A Tiny Explorer
You are an explorer, mapping an unknown world. Your ship is carried on the wind. Where it goes, who knows?

Each day, in your spyglass, you see features to the north, south, east and west. You always see four such features, corresponding to the cardinal directions. Your spyglass reports ASCII symbols like this:

`~~.*`, `~~~~`, `~.^^`, `~#~#`

The symbols are in the order (north, south, east, west).

These are the symbols: `~` = sea, `.` = coast, `^` = mountain, `*` = tree, `#` = invalid (no observation, this occurs whenever you see the edge of the world, or the landscape is obscured by fog). Your spyglass sees exactly one unit in every direction.

Each night, you look up at the stars to see how far you've travelled. Looking at the stars reports an ascii symbol like this:

`n`, `s`, `e`, `w`

corresponding to North, South, East and West, respectively. You always move exactly one unit to the north, south, east or west every night. So you, as explorer will be receiving an endless stream of symbols:

`~~.*n~~~~s~~.*s~.**`

Your task is to output a 2D map of the world (where `?` are unknown parts of the map, north is up, east is right):

```
?~~~??????
?~~~??????
?~~~.^^.??
?~~.***.~~
~~.*^^*.~~
~~~..~~~~~
~~~~~~~~~~
~~~~~~~~~~

```

For the sake of simplicity let's assume you start in the bottom left corner of the map. Assume all maps are 8x8.

Here is a simple 3x3 example. Assume the map looks like this:

```
~.~
~^~
~.~

```

With the following input: `~#.#n~~^#s`

You will get this output:

```
~??
~^?
~.?

```

More example inputs and outputs:

input `~#~#n~~~#n~~~#n~~~#n~~~#n~~.#n~~.#n#~~#e#.~~e#.~~e#.~~e#.~~e#~~~e#~~~e#~#~s~~#~s~~#~s~~#~s~~#.s~~#~s~~#~s~##~w~#~~w.#~~w^#~~w.#~~`

output

```
~~~~~~~~
~....~~~
~.????~~
~~????~~
~~????.~
~~????~~
~~?.^.~~
~~~~~~~~

```

Input:

`~#~#e~#~~e~#~~e.#~~e^#~~n.~..n~^~.n~.~~n.~~.n.~~*n~.~.n#.~~w#.~~w#.~~s~*..s..*.s*~.~s.~~~s`

Output:

```
?~~~~~??
?....~??
?.**.~??
?~..~~??
?~~~~~??
?~~..~??
~~~.^.??
~~~~~~??

```

# Answer
# MATL, ~~68~~ ~~59~~ 58 bytes

```
'?'7XJQtX"'s'jh5e"@2#1)t35>)-1l8t_4$h9M)b'nsew'=8M*sJ+XJ+(

```

**Try it online!**

### Explanation

The map is kept in the bottom of the stack and gradually filled. The current position of the explorer is stored in clipboard J.

The map uses matrix coordinates, so (1,1) is upper left. In addition, column-major linear indexing is used. This means that the elements of the 8×8 matrix representing the map are accessed with a *single index* as follows:

```
1  9 17 25 33 41 49 57
2 10 18 26 34 42 50 58
3 11 19 27 35 43 51 59
4 12 20 28 36 44 52 60
5 13 21 29 37 45 53 61
6 14 22 30 38 46 54 62
7 15 23 31 39 47 55 63
8 16 24 32 40 48 56 64

```

So for example the element (3,2) of the matrix is the element with linear index 11. Movement towards North, South, East and West respectively corresponds to adding -1, 1, 8 or -8 to the linear index. The array \[-1 1 8 -8\] serves to encode two different things:

* The possible displacements of the explorer.
* The relative positions of features detected with the spyglass. These positions are relative to the current position of the explorer.

The input string is arranged into chunks of `5` characters. Since the first chunk is missing the first character (that which indicates movement), an initial `s` is arbitrarily included to make all chunks the same size. To compensate for this, the explorer starts at position 7, not 8, so the initial displacement to the South (add 1 to the linear index) leaves them at position 8.

The chunks of 5 characters are processed in a loop. The first character updates the position, and the remaining 4, if different than `#`, are written into the adequate entries of the matrix that represents the map.

```
'?'          % push '?'. The map will initially be filled with this
7XJ          % push 7: initial position of the explorer. Copy into clipboard J
Qt           % add 1. Duplicate
X"           % 8x8 matrix containing '?'
'n'jh        % take input string. Prepend 'n'
5e           % reshape into a 5-column matrix
"            % for each column (chunk)
  @          %   push current chunk
  2#1)       %   split chunk into its first char and an array with the other 4
  t35>       %   duplicate. Logical index of chars different than #
  )          %   apply that index to keep characters different than #
  -1l8t_4$h  %   array [-1 1 8 -8]
  9M         %   push logical index again
  )          %   apply that index to keep only relevant relative positions
  b          %   bubble up in stack: move first char of chunk to top
  'nsew'=    %   logical index that tells if that char is 'n', 's', 'e' or 'w'
  8M         %   push array [-1 1 8 -8] again
  *          %   multiply element-wise. Only one of the four results will be nonzero
  s          %   sum of the array. Gives displacement of the explorer
  J+         %   push position of the explorer and add to compute new position
  XJ         %   update position in clipboard J
  +          %   add updated position of explorer to relative positions of features
  (          %   write those fearttures into the indexed entries of the map
             % end for each. Implicitly display

```
> 9 votes

# Answer
# C, ~~210~~ ~~208~~ 207 bytes

This one uses printf and scanf to read input, and a linearized array instead of x,y; so I feel it is sufficiently different from millibyte's.

Golfed:

```
 main(p){char*i,*j,m[80];for(p=73,i=m+p;p--;m[p]=63);for(p=8;scanf("%5s",i)>0;p+=*j=='n'?8:*j=='s'?-8:*j=='e'?1:-1)for(j=i;j-i<4;j++)if(*j^35)m[p+"qajh"[j-i]-'i']=*j;for(p=72;m[p]=0,p-=8;)printf("%s\n",m+p);}

```

Somewhat-ungolfed:

```
main(p){
    char*i,*j,m[80];
    for(p=73,i=m+p;p--;m[p]=63);                   // fill with ?
    for(p=8;scanf("%5s",i)>0;
            p+=*j=='n'?8:*j=='s'?-8:*j=='e'?1:-1)  // read 5-at-a-time
        for(j=i;j-i<4;j++)
            if(*j^35)m[p+"qajh"[j-i]-'i']=*j;      // update map positions
    for(p=72;m[p]=0,p-=8;)printf("%s\n",m+p);      // output line-by-line
}

```

Representation:

```
  // board: (vertically reversed when printed)
    0  1  2  3  4  5  6  7
    8  9  10 ...
    16 18 19 ...
    ...
    56 57 58 59 60 61 62 63

  // offsets and offset order, or why "qajh":
    s2      -8       a
  w4  e3  -1 0+1   h i j
    n1      +8       q   <- offset by +'i'

```

Also, you start at position 8 because this shaves a char or so off the print-loop.
> 4 votes

# Answer
# Ruby, ~~169~~ 147 bytes

Full program. Takes in the input string from STDIN (you probably need to pipe it in from a file to prevent any trailing newlines from messing things up) and outputs the resultant map to STDOUT.

Trimmed a ton by putting all the strings into one and then splitting them later.

```
m=??*64
d=0
x=56
gets.each_char{|c|d<4?(w=x+(d>2?-1:d>1?1:d<1?-8:d<2?8:0)
m[w]=c if c>?$):x+=c>?v?-1:c<?f?1:c>?q?8:-8
d+=1;d%=5}
puts m.scan /.{8}/

```

Ungolfed:

```
m = ?? * 64                 # 64 "?" symbols
                            # y axis counts downwards; 0-7 is top row
d = 0                       # Keep track of which direction we're looking
x = 56                      # Position, bottom left corner (0,7)
gets.each_char do |c|       # For each character from first line of STDIN
    if d < 4                # Looking in a direction
        if    d > 2         # d == 3; looking west
            w = x - 1
        elsif d > 1         # d == 2; looking east
            w = x + 1
        elsif d < 1         # d == 0; looking north
            w = x - 8
        else                # d == 1; looking south
            w = x + 8
        end
        m[w] = c if c > ?$  # Only '#' gets rejected by this step
    else                    # Moving in a direction
        if    c > ?v        # c == 'w'
            x -= 1
        elsif c < ?f        # c == 'e'
            x += 1
        elsif c > ?q        # c == 's'
            x += 8
        else                # c == 'n'
            x -= 8
        end
    end
    d = (d + 1) % 5         # Look in the next direction
end
puts m.scan /.{8}/          # Split map into rows of 8

```
> 3 votes

# Answer
# C, ~~265~~ ~~226~~ 224 bytes

```
a[8][8];x;y;i;main(c){for(;c=getchar(),c+1;y+=(c=='n')-(c=='s'),x+=(c=='e')-(c=='w'))for(i=5;--i;c=getchar())i&&c-35&&(a[x+(i==2)-(i==1)][y-(i==3)+(i==4)]=c);for(y=8;y--;putchar(10))for(x=0;x<8;)putchar((i=a[x++][y])?i:63);}

```

The map is 8x8, I didn't notice that before. And here is the 265 bytes solution that works for maps with variable dimensions:

```
a[99][99];c;x;X;y;i;k;p;main(Y){for(;c=getchar(),c+1;y+=(c=='n')-(c=='s'),x+=(c=='e')-(c=='w'))for(i=5;--i;c=getchar())i&&c-35&&(a[k=x+(i==2)-(i==1),X=X<k?k:X,k][p=y-(i==3)+(i==4),Y=Y<p?p:Y,p]=c);for(y=Y+1;y--;putchar(10))for(x=0;x<=X;)putchar((i=a[x++][y])?i:63);}

```
> 2 votes

# Answer
# Fortran, 263 251 247 235 234 216 bytes

1D version (similar to the one by Don Muesli):

```
#define R read(*,'(a)',advance='no',eor=1)c
#define F(x)R;if(c/='#')a(x+i)=c
program t
character::a(64)='?',c
integer::k(4)=[8,-8,1,-1],i=57
do
F(-8)
F(8)
F(1)
F(-1)
R
i=i+k(index('snew',c))
enddo
1 print'(8a)',a
end

```

2D version:

```
#define R read(*,'(a)',advance='no',eor=1)c
#define F(x,y)R;if(c/='#')a(x+m,y+l)=c
#define G(x,y)j=index(x,c);if(j==2)j=-1;y=y+j
program t
character::a(8,8)='?',c
l=8;m=1
do
F(,-1)
F(,1)
F(1,)
F(-1,)
R
G('sn',l)
G('ew',m)
enddo
1 print'(8a)',a
end

```

To enable free form and pre-processing, the file needs the extension `.F90`, e.g. `explorer.F90`. The input is read from STDIN:

```
echo "~#~#e~#~~e~#~~e.#~~e^#~~n.~..n~^~.n~.~~n.~~.n.~~*n~.~.n#.~~w#.~~w#.~~s~*..s..*.s*~.~s.~~~s" | ./a.out
?~~~~~??
?....~??
?.**.~??
?~..~~??
?~~~~~??
??~..~??
~~~.^.??
~~~~~~??

```
> 2 votes

# Answer
# Lua, 354 bytes (try it online)

Golfed:

```
n=(...)r={}y=8x=1q="?"for i=1,8 do r[i]={q,q,q,q,q,q,q,q}end for u in n:gsub("#",q):gmatch(".....")do a,b,c,d,e=u:match("(.)(.)(.)(.)(.)")if a~=q then r[y-1][x]=a end if b~=q then r[y+1][x]=b end if c~=q then r[y][x+1]=c end if d~=q then r[y][x-1]=d end y=y+(("n s"):find(e)or 2)-2x=x+(("w e"):find(e)or 2)-2 end for i=1,8 do print(table.concat(r[i]))end

```

Slightly ungolfed:

```
n = "~#~#e~#~~e~#~~e.#~~e^#~~n.~..n~^~.n~.~~n.~~.n.~~*n~.~.n#.~~w#.~~w#.~~s~*..s..*.s*~.~s.~~~s"

r={} y=8 x=1 q="?"
for i=1,8 do r[i]={q,q,q,q,q,q,q,q} end
for u in n:gsub("#",q):gmatch(".....") do
  a,b,c,d,e=u:match("(.)(.)(.)(.)(.)")
  if a~=q then r[y-1][x]=a end
  if b~=q then r[y+1][x]=b end
  if c~=q then r[y][x+1]=c end
  if d~=q then r[y][x-1]=d end
  y=y+(("n s"):find(e)or 2)-2
  x=x+(("w e"):find(e)or 2)-2
end
for i=1,8 do print(table.concat(r[i])) end

```
> 1 votes

# Answer
# Kotlin, 242 bytes

```
{val m=Array(8){Array(8){'?'}}
var d=7
var i=0
for(c in it)(mapOf('n' to{d--},'s' to{d++},'w' to{d-=8},'e' to{d+=8},'#' to{i++})[c]?:{m[d%8+listOf(-1,1,0,0)[i%4]][d/8+listOf(0,0,1,-1)[i%4]]=c
i++})()
m.forEach{for(c in it)print(c);println()}}

```

The newlines can be replaced with semicolons if wished.

Try Here
> 1 votes

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


title: Create an ABACABA city

text:
# Question
Title: Create an ABACABA city
Here is the 3rd ABACABA city:

```
  _
A|_|
B|__|
A|_|_
C|___|
A|_|
B|__|
A|_|

```

It is made out of the ABACABA sequence, which is basically:

* A (1st iteration)
* place B - AB
* repeat A - ABA (2nd iteration)
* Place C - ABAC
* Repeat ABA - ABACABA (3rd iteration)

and you get the idea.

The buildings have a height (corresponded by no. of underscores) equal to the letters converted to numbers as A = 1, B = 2 e.t.c.

### Input

An iteration number 1\<=*n*\<=26.

### Output

The ABACABA city of order *n*, including the letters at the start of the lines.

# Answer
# Python 2, 82 bytes

```
f=lambda n,s=1:n*"'"and"  _"*s+f(n-1,0)+"_"*(n-2)+"\n%c|%s|"%(64+n,"_"*n)+f(n-1,0)

```

I noticed no one had posted the binary recursion method and decided to give it a shot...and now with a trick borrowed from Sherlock9, it is the shortest python answer! (Also, thanks to xnor for one more shortening.) (And then Dennis who shaved a handful more...)

Ungolfed:

```
def f(n,s=1):
    if n>0:
        strsofar = "  _" if s==1 else ""        #prepend overhang for top-level call
        strsofar += f(n-1,0)                    #build the city above the current line
        strsofar += "_"*(n-2)                   #add the overhang to reach the current tower
        strsofar += "\n%c|%s|" % (64+n, "_"*n)  #write the current (center) line
        strsofar += f(n-1,0)                    #build the city below the current line
        return strsofar
    else:
        return ""                               #only this line will be executed when n==0 (base case)

print "  _"+f(input())

```
> 6 votes

# Answer
# MATL, 59 bytes

```
vi:"t@wv]!-1hPXJtPvX>"'|'@Z"63+h6MJ2+X@)(]XhcJ64+!wh!32H:(!

```

This uses current release (15.0.0) of the language.

**Try it online!**

---

(If the letters didn't have to be included in the output: the following would work, 48 bytes):

```
vi:"t@wv]!-1hPXJtPvX>"' |'X@1=o)@Z"63+h6MJ2+X@)(

```

### Explanation

```
v        % vertically concatenate the stack contents: gives an empty array
i:       % input number n. Generate [1,2,...,n]
"        % for each k in [1,2,...n]
  t      %   duplicate
  @      %   push k
  wv     %   swap, vertically concatenate
]        % end. Poduces the numeric ABACABA: [1 2 1 3 1 2 1]: ceiling heights
!        % transpose into a row
-1h      % append -1
PXJ      % reverse array. Copy into clipboard J
tP       % duplicate. Reverse again, so undo the reversing
v        % vertically concatenate reversed and non-reversed row arrays
X>       % max of each column. Gives array of wall heights: [1 2 2 3 3 2 2 1]
"        % for each value in that array
  '|'    %   push "floor" char
  @      %   push height
  Z"     %   create string with that many spaces
  63+    %   transform spaces into "wall" chars, '_'
  h      %   concatenate horizontally
  6M     %   push "floor" char '|' again, to be used as ceiling
  J      %   push array of ceiling heights
  2+X@)  %   index into that to get height of current building
  (      %   at that position, overwrite the string with '|'
]        % end
Xhc      % concatenate all strings into a 2D char array, padding with spaces
J        % push array of ceiling heights (numeric ABACABA sequence)
64+      % add 64 to transform into letters
!        % transpose into column array
wh       % swap, concatenate horizontally. This appends letters below the floor
!        % transpose
32H:(    % overwrite first two positions (in linear order) with spaces
!        % transpose back. Implicitly display

```
> 3 votes

# Answer
## Python 2, 99 bytes

```
b=1;i=2**input('  _\n')-1
while i:i-=1;a=len(bin(i&-i))-2;print'%c|%s|'%(64+b,'_'*b)+'_'*(a+~b);b=a

```

To find the `i`th number of the ABACABA sequence, write `i` in binary, count the number of trailing zeroes, and add one. We use the classic bit trick `i&-i` to find the greatest power of `2` that divides `i`, then compute bit length. Actually, we count `i` down from `2**n-1` to `0`, which is fine because the ABACABA sequence is symmetric.

We track both the current and last number of the sequence with the help of a "previous" variable `b`. This tells us how many underscores to print as the "overhang". The final building is drawn correctly without overhang because `0` is treated as have bit length `1`.

The string format for printing is taken from Sp3000, as is the trick of using the `input` to print the first line.
> 3 votes

# Answer
# CJam, ~~37~~ 35 bytes

```
SS'_Lri{[H)'_*_2>N@H'A+'|@'|6$]+}fH

```

This is an iterative implementation of the recursive algorithm from @quintopia's answer.

Try it online!

### How it works

```
SS'_     e# Push two spaces and an underscore.
L        e# Push "".
ri       e# Read an integer I from STDIN.
{        e# For each H in [0 ... I-1]:
  [      e#   Set an array marker.
    H)   e#     Push Push H+1.
    '_*  e#     Push a string of that many underscores.
    _2>  e#   Push a copy and remove the first two underscores.
    N    e#   Push a linefeed.
    @    e#   Rotate the longer string of underscores on top of it.
    h'A+ e#   Add H to the character 'A', pushing the corresponding letter.
    '|  e#    Push a vertical bar.
    @   e#    Rotate the string of underscores on top of it.
    '|  e#    Push another vertical bar.
    6$  e#    Push a copy of the previous iteration (initially "").
  ]     e#   Wrap everything up to the former marker in an array.
}fH     e#

```
> 2 votes

# Answer
## JavaScript (ES6), 162 bytes

```
n=>(a=[...Array(1<<n)]).map((_,i)=>i?(a[i]=String.fromCharCode(64+(n=1+Math.log2(i&-i)))+`|${"_".repeat(n)}|`,a[i-1]+='_'.repeat(--n&&--n)):a[i]='  _')&&a.join`\n`

```

Where `\n` is the literal newline character.
> 1 votes

# Answer
## Python 2, ~~123~~ 121 bytes

```
f=lambda n:n*[n]and f(n-1)+[n]+f(n-1)
L=f(input('  _\n'))
for i,j in zip(L,L[1:]+L):print'%c|%s|'%(64+i,'_'*i)+'_'*(j+~i)

```

ideone link *(-2 bytes thanks to @xsot)*

`f` generates the ABACABA sequence as a list of numbers, e.g. `f(3) = [1, 2, 1, 3, 1, 2, 1]`. The offset of the input by 1 compared to the ABACABA sequence challenge lets us golf off a byte in `f`.

The first line is printed separately, after which all other lines are printed using an expression which takes into account the current number and the next number. Just for fun, the first line is printed using `input()`.
> 1 votes

# Answer
# Pyth - 64 62 bytes

Probably could be golfed more, but good enough for now.

```
Lsl.&Jhb_J"  _"Vtt^2Qpr@G=ZyN1p"|_"p*\_Zp\|W<=hZyhNp\_)d)"A|_|

```

Try it here!

Explanation:

```
            |Predefined vars: Q = evaluated input, G = lowercase alphabet
L           |Lambda definition. y(b) = return (following code)
   .&       |bitwise and
     Jhb    |J = b + 1, pass b + 1 to the bitwise and
        _J  |-J
  l         | base 2
 s          |̲c̲o̲n̲v̲e̲r̲t̲ ̲t̲o̲ ̲i̲n̲t̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲
          "  _"                              |print "  _" with a trailing newline
               Vtt^2Q                        |For N in 2^Q - 2
                     pr      1               |print in caps
                         =ZyN                |Z = y(N) remember the first lambda?
                       @G                    |G[Z], basically convert 1-26 to A-Z
                              p"|_"          |print "|_", no trailing newline
                                   p*\_Z     |print "_" Z times
                                        p\|  |̲p̲r̲i̲n̲t̲ ̲"̲|̲"̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲
                                           W<=hZyhN             |While ++Z<y(N+1)
                                                   p\_          |print "_"
                                                      )k        |end while,
                                                                |print newline
                                                        )"A|_|  |end for,
                                                                |print "A|_|"

```
> 1 votes

# Answer
# Python 3.5 - 262 236 220 bytes:

-16 bytes thanks to @CatsAreFluffy! My entire function can now finally be in a single line! :)

```
from collections import*
def a(v):o=OrderedDict;j=[chr(i+97)for i in range(26)];d=o((j[i],('  '+'_'*(i+1)+'\n'+j[i]+'|'+'_'*(i+1)+'|'))for i in range(26));f=lambda w:'a'[w:]or f(w-1)+j[w]+f(w-1);[print(d[g])for g in f(v)]

```

It may be a bit long, and it may print new lines in between building, but in does what it needs to. You can test it out yourself to confirm it.

**EDIT:**

My previous golfed code did not print the right pattern whatsoever. However, now the one shown above does, and it does it good in my opinion. You can also run it for yourself to confirm that.

**Note:** The program prints all lowercase letters behind every "building". I hope that's okay.

# Ungolfed version with Explanation:

```
from collections import*
def a(v):
    o=OrderedDict # Assign the OrderedSict function to "o"
    j=[chr(i+97)for i in range(26)] # Create a list with all 26 lowercase letters of the alphabet
    d=o((j[i],('  '+'_'*(i+1)+'\n'+j[i]+'|'+'_'*(i+1)+'|'))for i in range(26)) # Create a dict assigning each letter it's corresponding building with its corresponding length
    f=lambda w:'a'[w:]or f(w-1)+j[w]+f(w-1) # Return the ABACABA sequence based on the user input
    [print(d[g])for g in f(v)] # Print out the building according to the sequence returned by the above lambda function (thanks to @CatsAreFluffy for this method to print it! :) )

```

Basically what I am doing is first importing the collections module's Ordered Dictionary function, and then creating an ordered dictionary, with each lower case letter in the list "j" being assigned to its corresponding building, with its corresponding length in underscores. Then I compute the sequence, based on the user's input, using the `f=lambda w:"a"[w:]or f(w-1)+j[w]+f(w-1)` function, and then based on the sequence returned by that, the buildings, with each's corresponding letter behind it, are printed out.
> 0 votes

# Answer
# Ruby, 129 bytes

Anonymous function, returns a multiline string.

```
->x{a=->n{n<1?[]:(b=a[n-1];b+[n]+b)}
r="  _
"
a[x].zip(a[x][1,9**x]<<0).map{|n,m|r+=(64+n).chr+"|#{?_*n}|#{?_*(m+~n)if m>n}
"}
r}

```
> 0 votes

# Answer
# JavaScript (ES6), 143

There are 2 newline inside the backticks that are significant and counted.

```
n=>`  _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)).join`
`

```

... or 138 if the letters can be lowercase.

```
n=>`  _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>(x+9).toString(36)+u(x)+u(t[i+1]-x-1)).join`

```

**Less golfed**

```
n=>{
  // recursive function for ABACABA returning an array of integers
  var r=n=>n?[...r(n-1),n,...r(n-1)]:[]
  // function to build "|__..."
  // if argument <=0 just returns the vertical bar
  var u=n=>'|'+'_'.repeat(n>0&&n)
  var t = r(n)
  t = t.map((x,i)=>
    // current building + extension to the len of next building if needed
    String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)
  )
  return ' _\n' // the top line is fixed
    + t.join('\n')
}

```

**Test**

```
solution=
n=>`  _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)).join`
`

function update() {
  var n=+N.value
  if (n>=0 && n<=26) O.textContent=solution(n)
}

update()
```

```
#N { width: 2em }
```

```
N:<input id=N value=4 oninput='update()'><pre id=O></pre>
```
> 0 votes

# Answer
# Powershell, 67 Bytes

```
1..(Read-Host)|%{'  _'}{$x+=@([char]($_+96)+'|'+'_'*$_+'|')+$x}{$x}

```
> 0 votes

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


title: Parse a Quaternion

text:
# Question
Title: Parse a Quaternion
If you don't know already, a quaternion is basically a 4-part number. For the purposes of this challenge, it has a *real* component and three *imaginary* components. The imaginary components are represented by the suffix `i`, `j`, `k`. For example, `1-2i+3j-4k` is a quaternion with `1` being the real component and `-2`, `3`, and `-4` being the imaginary components.

In this challenge you have to parse the string form of a quaternion (ex. `"1+2i-3j-4k"`) into a list/array of coefficients (ex. `[1 2 -3 -4]`). However, the quaternion string can be formatted in many different ways...

* It may be normal: `1+2i-3j-4k`
* It may have missing terms: `1-3k`, `2i-4k` (If you have missing terms, output `0` for those terms)
* It may have missing coefficients: `i+j-k` (In this case, this is equivalent to `1i+1j-1k`. In other words, a `i`, `j`, or `k` without a number in front is assumed to have a `1` in front by default)
* It may not be in the right order: `2i-1+3k-4j`
* The coefficients may be simply integers or decimals: `7-2.4i+3.75j-4.0k`

There are some things to note while parsing:

* There will always be a `+` or `-` between terms
* You will always be passed valid input with at least 1 term, and without repeated letters (no `j-j`s)
* All numbers can be assumed to be valid
* You can change numbers into another form after parsing if you want (ex. `3.0 => 3`, `0.4 => .4`, `7 => 7.0`)

Parsing/quaternion builtins and standard loopholes are disallowed. This includes `eval` keywords and functions. Input will be a single string and output will be a list, an array, values separated by whitespace, etc.

As this is , shortest code in bytes wins.

### Tons o' test cases

```
1+2i+3j+4k             => [1 2 3 4]
-1+3i-3j+7k            => [-1 3 -3 7]
-1-4i-9j-2k            => [-1 -4 -9 -2]
17-16i-15j-14k         => [17 -16 -15 -14]

7+2i                   => [7 2 0 0]
2i-6k                  => [0 2 0 -6]
1-5j+2k                => [1 0 -5 2]
3+4i-9k                => [3 4 0 -9]

42i+j-k                => [0 42 1 -1]
6-2i+j-3k              => [6 -2 1 -3]
1+i+j+k                => [1 1 1 1]
-1-i-j-k               => [-1 -1 -1 -1]

16k-20j+2i-7           => [-7 2 -20 16]
i+4k-3j+2              => [2 1 -3 4]
5k-2i+9+3j             => [9 -2 3 5]
5k-2j+3                => [3 0 -2 5]

1.75-1.75i-1.75j-1.75k => [1.75 -1.75 -1.75 -1.75]
2.0j-3k+0.47i-13       => [-13 0.47 2.0 -3] or [-13 .47 2 -3]
5.6-3i                 => [5.6 -3 0 0]
k-7.6i                 => [0 -7.6 0 1]

0                      => [0 0 0 0]
0j+0k                  => [0 0 0 0]
-0j                    => [0 0 0 0] or [0 0 -0 0]
1-0k                   => [1 0 0 0] or [1 0 0 -0]

```

# Answer
# Pyth, 48 bytes

```
jm+Wg\-K--e|d0G\+K1+]-I#GJczfT.e*k<b\.zm/#dJ"ijk

```

Demonstration Test suite

The output format is newline separated. The test suite code uses space separation, for ease of reading, but is otherwise the same.

Outputs a `-0` in the last 2 cases, which I hope is OK.

Explanation to follow.
> 5 votes

# Answer
# Retina, 115

```
\b[ijk]
1$&
^(?!.*\d([+-]|$))
0+
^(?!.*i)
+0i+
^(?!.*j)
0j+
^(?!.*k)
0k+
O$`[+-]*[\d.]*(\w?)
$1
-
+-
^\+

S`[ijk+]+

```

Try it online!

1 byte saved thanks to @Chris Jester-Young.

A bug fixed and 6 bytes saved thanks to @Martin Büttner

Found a couple bugs involving some edge cases, bumped up byte count quite a bit.

Returns the numbers newline separated. Anyway, this has a mostly elegant solution that sort of gets ruined by edge cases but hey I got to use sort mode, that means I used the right tool for the job, right?

### Explanation:

Stage by stage, as usual.

```
\b[ijk]
1$&

```

The only characters in the input that can create word boundaries are `-+.`. This means that if we find a boundary followed by a letter, we have an implicit `1` which we add in with the replacement. `$&` is a synonym for `$0`.

```
^(?!.*\d([+-]|$))
0+

```

Big thanks to Martin for this one, this one adds in the implicit `0` for the real part if it was missing in the input. We make sure that we can't find a number that is followed by a plus or minus sign, or the end of the string. All the complex numbers will have a letter after them.

```
^(?!.*i)
+0i+

```

The next 3 stages are all pretty much the same, barring which letter they impact. All of them look to see if we can't match the letter, and if we can't we add a `0` term for it. The only reason `i` has an extra `+` before it is to prevent the real value from being unreadable with the `i`s coefficient, the other numbers are all separated by their complex variable.

```
O$`[+-]*[\d.]*(\w?)
$1

```

Ah, the fun part. This uses the newish sort stage, denoted by the `O` before the option separator backtick. The trick here is to grab the whole number followed optionally by a word character, which in this case will only ever match one of `ijk`. The other option used is `$` which causes the value used to sort these matches to be the replacement. Here we just use the optional letter left over as our sort value. Since Retina sorts lexicographically by default, the values are sorted like they would be in a dictionary, meaning we get the matches in `"", "i", "j", "k"` order.

```
-
+-

```

This stage puts a `+` sign in front of all the minus signs, this is needed if we have a negative value for `i` in the split stage, later.

```
^\+

```

We remove the leading `+` to make sure we have no extra leading newline.

```
S`[ijk+]+

```

Split the remaining lines on runs of the complex variables or the plus sign. This nicely gives us one value per line.
> 9 votes

# Answer
# Lua, ~~185~~ ~~187~~ ~~195~~ ~~183~~ 166 bytes (try it online) \[used regex\]

Thanks to *@Chris Jester-Young* for the improved regex.

Thanks to *@Katenkyo* for bringing it down to 166 bytes.

Golfed:

```
r={0,0,0,0}for u in(...):gsub("([+-])(%a)","%11%2"):gmatch("-?[%d.]+%a?")do n,i=u:match("(.+)(%a)")r[i and(" ijk"):find(i)or 1]=(n or u)end print(table.concat(r," "))

```

Ungolfed:

```
n = "42i+j-k+0.7"

result = {0,0,0,0}

for unit in n:gsub("([+-])(%a)","%11%2"):gmatch("-?[%d.]+%a?") do
  num, index = unit:match("(.+)(%a)")
  if index == "i" then
    result[2] = num
  elseif index == "j" then
    result[3] = num
  elseif index == "k" then
    result[4] = num
  else
    result[1] = unit
  end
end

print(table.concat(result," "))

```
> 3 votes

# Answer
## Perl 5, 125 bytes

```
#!perl -p
%n=(h,0,i,0,j,0,k,0);$n{$4//h}=0+"$1@{[$3//$5//1]}"while/([+-]?)(([\d.]+)?([ijk])|([\d.]+))/g;s/.*/@n{qw(h i j k)}/

```
> 3 votes

# Answer
# C, 236 bytes

```
char j,n[9][9],s[9],y[9],i=8,k,*p=n[8];main(c){for(**n=48;c=getchar(),c+1;)c-32&&(c<46&&(k&&(y[1]=i),k=0,s[--i]=c-43,p=n[i])||c>57&&(k||(*p=49),k=0,y[c-103]=i)||(*p++=c,k=1));for(k&&(y[1]=i);++j<5;)printf("%c%s ",s[y[j]]?45:0,n[y[j]]);}

```

(For values like -0 or -0.0, the minus sign is also printed in the output, ~~but since the challenge states that "you can change numbers into another form after parsing if you want", and if -0 appears in the input, it follows that it's also acceptable in the output.~~ @GamrCorps has now clarified that this is ok.)
> 3 votes

# Answer
## JavaScript (ES6), ~~103~~ 100 bytes

```
f=s=>s.replace(/(?=.)(\+|-|)([\d.]*)(\w?)/g,(_,s,x,c)=>a[c.charCodeAt()&3]=+(s+(x||1)),a=[0,0,0,0])&&a

```

Edit: Saved 3 bytes by switching from `parseInt` to `charCodeAt`, which conveniently just needs `&3` to get me the correct array index.
> 3 votes

# Answer
# JavaScript (ES6) 106

```
s=>(s.replace(/([+-]?)([\d.]*)(\w?)/g,(a,b,c,d)=>a&&(s[d||9]=b+(c||1)),s={}),[...'9ijk'].map(i=>+s[i]||0))

```

**Test**

```
f=s=>(s.replace(/([+-]?)([\d.]*)(\w?)/g,(a,b,c,d)=>a&&(s[d||9]=b+(c||1)),s={}),[...'9ijk'].map(i=>+s[i]||0))

function Test()
{
  var t,k,r,ts=TS.value.split('\n')

  O.textContent=ts.map(x=>x.trim()&&(
    [t,k]=x.split('=>').map(x=>x.trim()),
    console.log(t,'*',k),
    k=k.match(/[\d+-.]+/g).map(x=>+x),
    r=f(t),
    t+' => '+r+(r+''==k+''?' OK':' KO (check: '+k+')')
  )).join('\n')
}

Test()
```

```
#TS { width:90%; height:10em}
```

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

Test data (modify if you like)<button onclick='Test()'>repeat test</button>
<textarea id=TS>
1+2i+3j+4k             => [1 2 3 4]
-1+3i-3j+7k            => [-1 3 -3 7]
-1-4i-9j-2k            => [-1 -4 -9 -2]
17-16i-15j-14k         => [17 -16 -15 -14]

7+2i                   => [7 2 0 0]
2i-6k                  => [0 2 0 -6]
1-5j+2k                => [1 0 -5 2]
3+4i-9k                => [3 4 0 -9]

42i+j-k                => [0 42 1 -1]
6-2i+j-3k              => [6 -2 1 -3]
1+i+j+k                => [1 1 1 1]
-1-i-j-k               => [-1 -1 -1 -1]

16k-20j+2i-7           => [-7 2 -20 16]
i+4k-3j+2              => [2 1 -3 4]
5k-2i+9+3j             => [9 -2 3 5]
5k-2j+3                => [3 0 -2 5]

1.75-1.75i-1.75j-1.75k => [1.75 -1.75 -1.75 -1.75]
2.0j-3k+0.47i-13       => [-13 0.47 2.0 -3]
5.6-3i                 => [5.6 -3 0 0]
k-7.6i                 => [0 -7.6 0 1]

0                      => [0 0 0 0]
0j+0k                  => [0 0 0 0]
-0j                    => [0 0 0 0]
1-0k                   => [1 0 0 0]
</textarea>
```
> 1 votes

# Answer
# PowerShell, 178 bytes

```
param($a);$p="(-?)([\d.]+)?";$g={param($s)if($a-match"$p$s"){if(($r=$matches)[2]){$r[1]+$r[2]}else{$r[1]+1}}else{0}};$a-match"$p(\+|-|$)">$null;+$matches[2];"i","j","k"|%{&$g $_}

```

---

**Ungolfed with Explanation**

```
# Get the whole string into a variable
param($a)
# Pattern shared getting both imaginary and real numbers.
$p="(-?)([\d.]+)?"
# Anonymous function that will locate a imaginary number using a letter sent as a parameter.
# If no value is assigned a signed 1 is returned. If no value is matched 0 is returned
$g={param($s)if($a-match"$p$s"){if(($r=$matches)[2]){$r[1]+$r[2]}else{$r[1]+1}}else{0}}
# Locate the real component if any. Null is converted to 0
$a-match"$p(\+|-|$)">$null;+$matches[2]
# Call the anonymous function using each of the imaginary suffixes.
"i","j","k"|%{&$g $_}

```

Not super impressed but it is a result nonetheless.
> 0 votes

# Answer
# PHP, 179 bytes

```
$a=[''=>0,'i'=> 0,'j'=>0,'k'=>0];preg_match_all("/([-+]?)(\d*(\.\d+)?)([ijk]?)/",$argv[1],$m,2);foreach($m as$n)if($n[0])$a[$n[4]]=$n[1].($n[2]===''?1:$n[2]);echo implode(',',$a);

```

Try the test suite.
> 0 votes

# Answer
# Python 3.5 - 496 bytes \[using Regular Expressions\]:

```
from re import*
def wq(r):
 a=sub('[+](?![0-9])','+1',sub('[-](?![0-9])','-1',r));q=lambda x:(not x.isdigit(),''.join(filter(str.isalpha,x)))
 for z in findall('(?<![0-9])[a-z]',a):a=a.replace(z,('+1{}'.format(z)))
 if not str(sorted(((sub('[.]','',sub('[+-]',' ',a))).split(' ')),key=q)[0]).isdigit():a+='+0, '
 for i in list(set(findall('[a-z]',a))^{'i','j','k'}):a+='+0{}, '.format(i)
 print(findall('[-]?\d+(?:\.\d+)?',''.join(sorted(sub('(?<=[A-Za-z0-9])(?=[+-])',', ',a).split(' '),key=q))))

```

It may be long, but in my defense, it works perfectly in doing what the OP wants, since all the test cases given were successful using my code.

# Ungolfed version with explanation included:

```
from re import*
def w(r):
    # Substitute all minus (-) and plus (+) signs NOT followed by a number  (if there are any) with a "-1"/"+1", respectively.
    a=sub('[+](?![0-9])','+1',sub('[-](?![0-9])','-1',r))
    # Lambda function created for later use to sort the Quaternion. This function, when given as a key to the "sorted" function, arranges the input Quaternion in the order where the whole number comes first, and then the rest are placed in order of increasing letter value (i,j,k in this case)
    q=lambda x:(not x.isdigit(),''.join(filter(str.isalpha,x)))
    # The following "for" loop replaces the letters NOT preceded by a number with a one followed by that letter
    for z in findall('(?<![0-9])[a-z]',a):
        a=a.replace(z,('+1{}'.format(z)))
    # The following first substitutes all pluses and minuses (+ and -) with a space, and then that new string is split at those spaces, and returned as a list. After that, the list is sorted according the the "lambda" function shown above. Then, the first item in that list, which is supposed to be a lone number, is checked to make sure that it indeed is a lone number. If it isn't, then "+0, " is appended to the Quaternion.
    if not str(sorted(((sub('[.]','',sub('[+-]',' ',a))).split(' ')),key=q)[0]).isdigit():
        a+='+0, '
    # The following "for" loop finds ALL the letters NOT in the list, by finding the symmetric difference between a set of all the letters found, and a set containing all the letters needed. For the letters not in the list, a '+0' is added the quaternion, followed by that letter, and then a comma and a space.
    for i in list(set(findall('[a-z]',a))^{'i','j','k'}):
        a+='+0{}, '.format(i)
    # Finally, in this last step, a ", " is added IN BETWEEN unicode characters and pluses/minuses (+/-). Then, it splits at those spaces, and the commas separate different parts of the Quaternion from each other (otherwise, you would get something like `12i+3j+4k` from `2i+3j+4k+1`) in a returned list. Then, that list is sorted according to the lambda expression "q" (above), and then, finally, the NUMBERS (of any type, courtesy to Regex) are extracted from that joined list, and printed out in the correct order.
    print(findall('[-]?\d+(?:\.\d+)?',''.join(sorted(sub('(?<=[A-Za-z0-9])(?=[+-])',', ',a).split(' '),key=q))))

```

If the above is a little too hard to read, basically what is happening is that:

1. If there are any, all + or - signs NOT followed by a number are replaced with a "+1"/"-1", respectively.
2. A `lambda` function is defined, which, when used in a `sorted` function as a key, sorts the list according to putting the whole number first, and then ordering the rest in increasing letter value ("i",then "j", then "k" in this instance).
3. The Quaternion, now having all +/- signs replaced with a 1 if needed, is searched, using Regular Expressions, for ALL letters NOT preceded by at least one number, and those letters that match are replaced with a "+1" followed by that letter.
4. The "if" statement then replaces ALL +/- signs with a space, and then the modified Quaternion is now "split" at those spaces, and returned in a list. Then, the list is sorted according to the lambda function explained earlier. Finally, the first item in that list is checked to make sure it's a number, since it's supposed to be, and if it's not, then a "+0, " is added to the Quaternion.
5. The second "for" loop finds ALL the letters NOT in the Quaternion by finding a symmetric difference between a set of those letters found in the expression, and then a set including all letters required. If any are found, then a "+0" followed by the missing letter and a space is added to the Quaternion.
6. Finally, in this last step, a ", " is added *in between* each character followed by a +/- symbol, and then the Quaternion is split at those spaces, then the list returned is sorted, for the last time, according to the lambda function defined as "q" earlier on. The commas in the expression separate each part of the quaternion (otherwise, you would be getting something like `14i+5j+6k` from `4i+5j+6k+1`). Lastly, that now sorted list is joined together into a string, and only the **numbers** *of any type* (courtesy of Regular Expressions) are extracted, and finally returned in a list, in the correct order, every single time.
> 0 votes

---
Tags: code-golf, parsing, complex-numbers
---


title: Child Genotypes

text:
# Question
Title: Child Genotypes
**The Challenge**

Everybody loves genetics, right? In this challenge, you will be given the genotypes of two parents. You must find each possible genotype of a child produced by the parents. You must account for dominant and recessive alleles as well as incomplete dominance and codominance.

An example input for the parents could be:

```
R'RxRr

```

Parent one (on the left) has a incompletely dominant R allele and a dominant R allele. Parent two (on the right) has a dominant R allele and a recessive allele.

Each parent is separated from the other by an x. The input will not contain an x allele.

An incompletely dominant allele will be followed by an apostrophe ('). Codominant alleles just refers to multiple different types of alleles combined together (A and W for example).

**Rules**

* Shortest code wins (measured in bytes).
* Each possibly genotype must be separated from the other genotypes by a comma.
* Phenotypes don't matter.
* Any letter can be used in the input except for x (which differentiates the parents).
* Duplicate genotypes should only be printed once.
    + Duplicates contain the exact same letters of the same case and type of allele. IF you have WY and YW in your answer, they are considered duplicates.
* No more than three different letters will be used in one input.
* The order of the letters in the output does not matter.
* Answer can be in the form of a string or an array.

**Examples**

Input 1 (the previous example):

```
R'RxRr

```

Output 1:

```
R'R,R'r,RR,Rr

```

Alternate output 1 (array):

```
{R'R,R'r,RR,Rr}

```

Input 2:

```
RWxRR

```

Output 2:

```
RR,WR
//Or an array, whichever you want

```

Input 3:

```
WYxY'y

```

Output 3:

```
WY',Wy,YY',Yy
//Once again, an array is fine

```

# Answer
> 6 votes
## Pyth, ~~20~~ 18 bytes

```
{msSd*Fc:z".'?"1\x

```

Test suite.

```
         z          get input
        : ".'?"1    regex match for any character followed by an optional '
       c        \x  chop on the element "x", resulting in [["R'","R"],["R","r"]]
     *F             splat over Cartesian product, resulting in pairs of "genes"
                      from the first "parent" and from the second
 m  d               map over each resulting pair...
   S                sort (so that we can dedup later)
  s                 concatenate
{                   remove duplicates

```

# Answer
> 5 votes
# JavaScript (ES6), ~~114~~ ~~112~~ ~~104~~ ~~90~~ 88 bytes

```
f=>(c=new Set,[z,y]=f.split`x`.map(b=>b.match(/.'?/g)),z.map(e=>y.map(g=>c.add(e+g))),c)

```

Thanks to Doorknob, Downgoat, Kenny Lau and Neil for helping me golf this down a bit :)

# Answer
> 3 votes
# Ruby, ~~82~~ 77 bytes

Anonymous function, takes the input string as its argument.

Edited to properly account for `ABxAB`.

-5 bytes from @Doorknob.

```
->g{a,b=g.split(?x).map{|s|s.scan /.'?/}
a.product(b).map{|s|s.sort*""}.uniq}

```

# Answer
> 1 votes
# Python 3.5 - 196 bytes:

```
def b(r):import itertools,re;r=[];[r.append(h)for h in itertools.permutations(re.sub("(?<=[a-zA-Z'])(?=[a-zA-Z])",' ',r.replace('x','')).split(' '),2)if h[::-1]not in r and h not in r];return r

```

A nice one liner, using some regular expressions.

**Note:** Around each letter with an apostrophe are double quotes, and I hope that's okay (e.g., in the output, `R'` would come out as `"R'"`). Also, for the last test case, it returns `[('W', "Y'"), ('W', 'y'), ('Y', 'W'), ('Y', "Y'"), ('Y', 'y'), ('y', "Y'")]` instead of just `WY',Wy,YY',Yy`. I also hope that is okay. If any of these conditions are an issue, just let me know, and I will fix them.

---
Tags: code-golf
---


title: Final Fantasy XV UNCOVERED!

text:
# Question
Title: Final Fantasy XV UNCOVERED!
Since I am INSANELY hyped for the Final Fantasy XV Uncovered event, I want *you* to write me a program to tell me when it is!!!

# The input

Your take input in the form of `HH:MM XDT`, where `HH` is a number in the range `1-12`, `MM` is a number between `0-60`, and `XDT` is a time zone, with `X` being one of `E` (eastern, UTC-4), `C` (central, UTC-5), `P` (pacific, UTC-7), or `M` (mountain, UTC-6). This is a time assumed to be PM. Valid inputs include:

```
1:00 EDT (1 PM Eastern Daylight Time)
4:05 MDT (4:05 PM Mountain Daylight Time)
12:23 PDT (12:23 PM Pacific Daylight Time)
1:10 CDT (1:10 PM Central Daylight Time)

```

The input may be assumed to be valid.

# The output

Your program must do the following:

1. Convert the given time to PDT and output `It is XX:XX PM PDT.`, where `XX:XX` is the converted time. Note that you do *not* need to handle any case where converting the time would cross the AM/PM boundary.
2. Print one of the following:

1. If the converted time is *before* 6:00 PM PDT, print `X minutes until the pre-show!`, replacing `X` with the number of minutes until 6:00 PM PDT.
    2. If the converted time is *after or equal to 6:00 PM PDT and before 7:00 PM PDT*, print `Pre-show started X minutes ago; UNCOVERED is starting in Y minutes!`, where `X` is the number of minutes that have passed since 6:00 PM PDT, and `Y` is the number of minutes until 7:00 PM PDT.
    3. If the converted time is *after or equal to 7:00 PM PDT*, print `UNCOVERED started X minutes ago!`, where `X` is the number of minutes that have passed since 7:00 PM PDT.

Each string printed *must* be followed by a newline.

# Scoring

This is code golf, so the shortest program wins.

# Answer
## JavaScript (ES6), 257 bytes

```
s=>(t=` minutes`,a=s.match(/(\d+):(\d+) (.)/),h=+a[1]+"PMCE".search(a[3]),m=420-h*60-a[2],`It is ${h}:${a[2]} PM PDT
${h<6?m-60+t+` until the pre-show`:h<7?`Pre-show started ${60-m+t} ago; UNCOVERED is starting in ${m+t}`:`UNCOVERED started ${-m+t} ago`}!`)

```
> 1 votes

# Answer
# Python (335 bytes)

```
t=raw_input().replace(*': ').split();x='PMCE'.index(t[2][0]);t[0]=int(t[0])+x;print '%s:%s PM PDT' % tuple(t[:1]);x=t[0]*60+int(t[1]);print ['%s minutes until the pre-show!'%(360-x),'Pre-show started %s minutes ago; UNCOVERED is starting in %s minutes!'%((x-360),(420-x)), 'UNCOVERED started %s minutes ago!'%(x-420)][(x>360)+(x>420)]

```

Output:

```
1:00 MDT
2:00 PM PDT
240 minutes until the pre-show!

6:00 CDT
8:00 PM PDT
UNCOVERED started 60 minutes ago!

6:50 PDT
6:50 PM PDT
Pre-show started 50 minutes ago; UNCOVERED is starting in 10 minutes!

```
> 3 votes

# Answer
# Lua, ~~357~~ ~~335~~ 332 bytes

**Thanks to @Katenkyo for chopping off 22 bytes.**

Golfed:

```
h,m,t=(...):match("(%d+):(%d+) (.)")f=tonumber h=(f(h)-("PMCE"):find(t))%12+1m=f(m)print("It is "..h..":"..m.." PM PDT.")a=" minutes"b="UNCOVERED"n=(6-h)*60-m r=h<6 and n..a.." until the pre-show!"or h<7 and"Pre-show started "..m..a.." ago; "..b.." is starting in "..(n+60)..a.."!"or b.." started "..(m+(h-7)*60)..a.." ago!"print(r)

```

(Try it online)

Ungolfed:

```
n = "7:10 CST"

h,m,t = n:match("(%d+):(%d+) (.)")
h = (tonumber(h) - ("PMCE"):find(t))%12 + 1
m = tonumber(m)
print("It is "..h..":"..m.." PM PDT.")

n = (6-h)*60-m

if h<6 then
  r=n.." minutes until the pre-show!"
elseif h<7 then
  r="Pre-show started "..m.." minutes ago; UNCOVERED is starting in "..(n+60).." minutes!"
else
  r="UNCOVERED started "..(m+(h-7)*60).." minutes ago!"
end

print(r)

```
> 2 votes

# Answer
# C, 333 bytes

```
#define p printf
char s[9];main(t){gets(s);s[5]=0;s[1]-=2+s[6]%2-s[6]%3;s[1]<48&&(s[1]+=10,--*s);
t=*s*600+s[1]*60+s[3]*10+s[4]-32568;p("It is %s PM PDT.",s);
t<0?p("%d minutes until the pre-show!",-t):t<60?p(
"Pre-show started %d minutes ago; UNCOVERED is starting in %d minutes!",t,60-t):
p("UNCOVERED started %d minutes ago!",t-60);}

```

333 bytes after removing the unnecessary newlines (all but the one after the #define).
> 1 votes

# Answer
# PHP, ~~347~~ ~~328~~ ~~327~~ 322 bytes

```
<?=$u="UNCOVERED";$m=" minutes";$s=" started ";$p="re-show";$z=['P'=>0,'M'=>1,'C'=>2,'E'=>3];$i=explode(":",$argv[1]);$h=$i[0]%12-$z[$argv[2][0]];$o=$i[1];$t=60-$o;$a="$s$o$m ago";echo"It is ".(($h+11)%12+1).":$o".($h<0?" A":" P")."M PDT.\n".($h<6?$t."$m until the p$p!":($h<7?"P$p$a; $u is starting in $t$m!":"$u$a!"));?>

```

### exploded view

```
<?=
  $u = "UNCOVERED";
  $m = " minutes";
  $s = " started ";
  $p = "re-show";
  $z = [ 'P' => 0,
         'M' => 1,
         'C' => 2,
         'E' => 3 ];

  $i = explode(":", $argv[1]);
  $h = $i[0]%12 - $z[$argv[2][0]];
  $o = $i[1];
  $t = 60 - $o;
  $a = "$s$o$m ago";

  echo "It is " . (($h+11)%12+1) . ":$o" . ($h < 0 ? " A" : " P") . "M PDT.\n" .
       ($h < 6 ? $t . "$m until the p$p!"
               : ($h < 7 ? "P$p$a; $u is starting in $t$m!"
                         : "$u$a!"));
?>

```

Runs as `php script.php HH:MM XDT`. Takes in the time and time zone as `$argv` entries, regexes `$argv[1]` out into `$i = [HH, MM]`, determines the time zone from the first character in `$argv[2]`, maths out how many minutes past 6PM PDT that is, then ternaries the `echo`.

Could drop 2 bytes by using `$u=UNCOVERED`, but it'd be the only error here and I like that this works cleanly.
> 1 votes

# Answer
# PowerShell 292 Bytes

```
$r,$i,$s,$u="re-show"," minutes"," start","UNCOVERED";$h,$m,$z=$args[0]-split":| ";$h=+$h-"PMCE".IndexOf($z[0]);"It is $h`:$m PM PDT.";if(($t=$h*60+$m-360)-lt0){"$($t*-1)$i until the p$r!"}else{if($t-gt59){"$u$s`ed $($t-60)$i ago!"}else{"P$r$s`ed $t$i ago; $u is$s`ing in $(($t-60)*-1)$i!"}}

```

---

**Less Golfed Explanation**

```
# Some string literals.
$r,$i,$s,$u,$g="re-show"," minutes"," start","UNCOVERED"," ago"
# Get the hours, minutes and zone into variables.
$h,$m,$z=$args[0]-split":| "
# Offset the time based on the passed timezone.
$h=+$h - "PMCE".IndexOf($z[0])
# Display current PDT time.
"It is $h`:$m PM PDT."

# Based on adjusted time value for PDT determine what string to show.
# Several string literals were used to save space.
if(($t=$h*60+$m-360)-lt0){
    # Show has not started yet
    "$($t*-1)$i until the p$r!"
}else{
    if($t-gt59){
        # Between 6 and 7
        "$u$s`ed $($t-60)$i$g!"
    }else{
        # It's after 7. Should have check more often.
        "P$r$s`ed $t$i$g; $u is$s`ing in $(($t-60)*-1)$i!"
    }
}

```

The literal for " ago" was removed in code but for now left in explanation in case of other changes.
> 0 votes

---
Tags: code-golf
---


# Question
Title: Write a program to fabricate elaborate acronyms
"Hey Bob, I need a new acronym. Something better than 'Automated Support System'. I need you to fabricate me an acronym!"

"Sure thing Joe! I'd love to fabricate an elaborate way to renovate, and not replicate something that you can tolerate."

"Alright Bob, make sure it can separate itself from the old acronym we need to terminate! It'll be great, or at least, that's just what I speculate."

Okay, apologies. I had a lot of fun writing that. Here's the challenge:

You are now Bob. You need to write a program that accepts a string of words from standard input:

> This is an example string of words

The character encoding must be ASCII. Delimeters can be spaces and newlines only. From this string of words, it forms an acronym, which it shoots straight to standard output (or equivalent output log):

> T.I.A.E.S.O.W.

The program must read the words, case-insensitive, and output the first letter of each word, capitalized, followed by a period.

This is code-golf. Shortest program wins. Go nuts!

# Answer
# Pyth, 11 bytes

```
sm+hrd1\.cz

```

Straight forward split, append dots, uppercase and join.
> 1 votes

# Answer
# Jelly, 8 bytes

```
ŒtḟŒlp”.

```

Explanation:

```
ŒtḟŒlp”.
Œt       # Convert the string to Title Case (lowercases then uppercase beginnings of word)
   Œl    # And on the other side, convert the string to lowercase
  ḟ      # filter: remove the elements from the right side (lowercase) from the left side (Title Cased). Only leaves the initials
     p”. # Cartesian product with a dot.

```

Golfed down under the Pyth one, thanks Dennis and Fry!
> 2 votes

# Answer
# Retina, 23 bytes

Try it online!

```
(\S)\S+(\s|$)
$1.
T`l`L

```
> 2 votes

# Answer
# Python 2, 54 bytes

Pretty sure this can be optimized, but eh.

First golfing attempt! Woot!

```
lambda s:"".join([b[0].upper()+"."for b in s.split()])

```

Thanks to DenkerAffe for shaving off a whopping 22 bytes!
> 1 votes

# Answer
# Pyth, 12 bytes

```
ss*hMcrz1d\.

ss*hMcrz1d\.
       z     # Input
      r 1    # Uppercase
     c   d   # Split by d (d=space)
   hM        # Map, tahe the "h"ead.
  *     \.   # Product with dot
ss           # Join twice

```
> 0 votes

# Answer
# Pylongolf2 (beta7+), 14 bytes

```
c| l1╨3♀~

```

Unfortunately I Pylongolf2 can't put a character between
all of the items in the stack so the output has no dots in it.

```
c          read input
 |         split by space (note the space after |)
   l1      take the first characters.
     ╨3    convert to uppercase
       ♀   pop the array
        ~  print everything

```
> 0 votes

---
Tags: code-golf, printable-ascii
---


title: Evaluate a minimax tree

text:
# Question
Title: Evaluate a minimax tree
Alice and Bob are playing a little game. First, they draw a tree from a root node (indicated by a thick dot), with no internal nodes, with numbers at the leaves. Any node may have any number of children.

We start at the root, and first to play is Alice (A). She must select one of the current node's children. Then it's Bob's turn, and he similarly selects a child node. This continues until a leaf node is reached.

When a leaf node is reached, the game is over. It is Alice's goal to end at a node with as large of a value as possible, and Bob's goal to end at a node with as small of a value as possible.

Given a tree in nested array form, return the value of the leaf that will be reached if both Alice and Bob play perfectly.

---

Examples:

```
18: [[67, [[100, [[67, 47], [86], 21, 16], [[46, [14], 35, 85], [71, [18, 63, 69], 99, 22], 3]]], [[18, 32, 42, 80]], [[36, 70], [86, 53, 46, 59], [[41], 86, 35]]], 3]
60: [[[84, 35], [44, 60]], [[24, 98], [16, 21]]]
58: [[53, 77], [58, [82, 41]], 52]
59: [[93, [100, 53], 58, 79], [63, 94, 59], [9, [55, 48]], [40, 10, 32]]
56: [[20, 10, [[[89, 22, 77, 10], 55], [24, 28, 30, 63]]], [[49, 31]], 17, 56]
0: [0]

```

You may assume that the root node never is a leaf node and points to at least one leaf node. You may assume that leafs are nonnegative numbers.

---

Shortest code in bytes wins.

# Answer
> 2 votes
# Jelly, 7 bytes

```
Nß€¬¡ṂN

```

Try it online! or verify all test cases.

This uses the algorithm from @xnor's answer. For comparison purposes, a more straightforward approach that alternately computes minima and maxima weighs **8 bytes**:

```
ß€¬¡€Ṃ€Ṁ

```

### How it works

```
Nß€¬¡ṂN  Main link. Argument: x (array or integer)

N        Negate. For an array, this negates all integers in it.
   ¬     Logical NOT. For an array, this applies to all integers in it.
    ¡    Apply the second link to the left once if ¬ returned an array or 1, or not
         at all if it returned 0.
 ß€      Recursively call the main link on all elements at depth 1 of -x.
         If -x == 0, € will cast 0 to range before mapping ß over it.
         Since the range of 0 is [], mapping ß over it simply yields [].
     Ṃ   Minimum.
         For an integer, Ṃ simply returns the integer. For [], Ṃ returns 0.
      N  Negate the minimum.

```

# Answer
> 8 votes
## Python 2, 53 bytes

```
f=lambda l,c=1:c*l if l<[]else-min(f(x,-c)for x in l)

```

The main question is how to alternate between `max` and `min` each layer. Using the fact that `max(l) == -min([-x for x in l])`, we instead negate every second layer and recurse with `-min`. To negate every second layer, we pass down a multiplier `c` that alternates `+1` and `-1`, and when we reach a leaf, we adjust its value by the multiplier. We recognize being at a leaf via the condition `l<[]`, since Python 2 treats numbers as less than lists.

It's hard to shorten the `else/if` ternary because either branch could give a Truthy (nonzero) or Falsey (zero) value.

# Answer
> 1 votes
## JavaScript (ES6), 53 bytes

```
f=(a,s=1)=>a.map?s*Math.max(...a.map(b=>s*f(b,-s))):a

```

Uses a similar approach to @xnor's answer. If the numbers are nonzero, then only 49 bytes:

```
f=(a,s=1)=>+a||s*Math.max(...a.map(b=>s*f(b,-s)))

```

# Answer
> 1 votes
# Pyth, 21 bytes

```
M?sIG*GH_hSmgd_HGLgb1

```

My first Pyth answer! Thanks to Dennis for the help :).

```
M                      # define a binary function (G, H)
 ?sIG                  # if G (first argument) is the same with s applied
                       # (check if it's an integer, so, a leaf node)
     *GH               # in such a case, calculate G*H
        _              # negation
         hS            # take the first element of the sorted list (that's the min)
           mgd_HG      # map over G, applying ourself (g) recursively,
                       # with the current lambda's value (d)
                       # and the negation of H
                 Lgb1  # Define a unary function to call our previous
                       # one with the correct base argument (1)

```

# Answer
> 1 votes
## Mathematica, 13 bytes

```
-Min[#0/@-#]&

```

or equivalently

```
Max[-#0/@-#]&

```

This evaluates to an unnamed function that takes the tree and returns the result.

This is also essentially the same as xnor's solution: at each level we swap the sign of the list and the result and use `Min` all the way down. This turned out incredibly golfy in Mathematica, because:

* `Min` can take either individual numbers or lists or even several lists. It just gives you the minimum value across all of its arguments. That means it works both on lists as well as leaves (where it just returns the leaf).
* `/@` which is short for `Map` is a very general higher-order function in Mathematica. It doesn't just map a function over lists, it can map them over any expression whatsoever. Numbers are such an expression, but they don't contain any elements to be mapped over. That means we can safely map any function over numbers, which doesn't affect the number at all.

Both of those things together mean we can write the code without any conditionals, since the `Min` and `Map` operations are no-ops on numbers, and subsequently the two negations cancel out so that the function becomes the identity when given a number.

Finally, thanks to `#0` it is possible to write unnamed recursive functions in Mathematica, which saves a few more bytes.

# Answer
> 0 votes
# Ruby, 46 bytes

Used @xnor's trick with `min` for alternating between max and min.

```
f=->n,a=1{n==[*n]?-n.map{|c|f[c,-a]}.min: a*n}

```

# Answer
> 0 votes
# Julia, ~~27~~ 25 bytes

```
!a=0==0a?a:-minimum(!,-a)

```

This uses the algorithm from @xnor's answer. Try it online!

---
Tags: code-golf, game, tree-traversal
---


title: Identify arborally satisfied point sets

text:
# Question
Title: Identify arborally satisfied point sets
An arborally satisfied point set is a 2D set of points such that, for any axis-aligned rectangle that can be formed using two points in the set as opposite corners, that rectangle contains or touches at least one other point. Here is an equivalent definition from Wikipedia:

> A point set is said to be arborally satisfied if the following property holds: for any pair of points that do not both lie on the same horizontal or vertical line, there exists a third point which lies in the rectangle spanned by the first two points (either inside or on the boundary).

The following image illustrates how the rectangles are formed. This point set is NOT arborally satisfied because this rectangle needs to contain at least one more point.

In ASCII art, this point set can be represented as:

```
......
....O.
......
.O....
......

```

A slight modification can make this arborally satisfied:

```
......
....O.
......
.O..O.
......

```

Above, you can see that all rectangles (of which there is only one) contain at least three points.

Here is another example of a more complex point set that is arborally satisfied:

For any rectangle that can be drawn spanning two points, that rectangle contains at least one other point.

## The Challenge

Given a rectangular grid of points (which I represent with `O`) and empty space (which I represent with `.`), output a *truthy* value if it is arborally satisfied, or a *falsey* value if it is not. This is code-golf.

Additional rules:

* You can choose to have the characters `O` and `.` swapped out with any other pair of printable ASCII characters. Simply specify which character mapping your program uses.
* The grid will always be rectangular. A trailing newline is allowable.

## More Examples

**Arborally satisfied:**

```
.OOO.
OO...
.O.OO
.O..O
....O

..O..
OOOO.
...O.
.O.O.
...OO

O.O.
..O.
OOOO
.O.O
OO..

...
...
...

...
..O
...

O.....
O.O..O
.....O

OOO.OO

```

**Not Arborally Satisfied:**

```
..O..
O....
...O.
.O...
....O

..O..
O.OO.
...O.
.O.O.
...OO

O.....
..O...
.....O

```

# Answer
> 7 votes
# Snails, 29 ~~30 39~~ bytes

```
!{t\Oo\.+c\.,\O!{t\O{w!(.,~}2

```

It works by tracing out 2 sides of the rectangle, and then checking whether there is some square containing an O such that traveling in a straight line from the square in 2 of the cardinal directions would result in hitting a side of the rectangle.

Prints the maximum of 1 and the grid's area if the input is "arborally satisfied"; otherwise 0.

# Answer
> 3 votes
# Oracle SQL 11.2, ~~364~~ 344 bytes

```
WITH v AS(SELECT MOD(LEVEL-1,:w)x,FLOOR((LEVEL-1)/:w)y FROM DUAL WHERE'O'=SUBSTR(:g,LEVEL,1)CONNECT BY LEVEL<=LENGTH(:g))SELECT a.*,b.*FROM v a,v b WHERE b.x>a.x AND b.y>a.y MINUS SELECT a.*,b.*FROM v a,v b,v c WHERE((c.x IN(a.x,b.x)AND c.y>=a.y AND c.y<=b.y)OR(c.y IN(a.y,b.y)AND c.x>=a.x AND c.x<=b.x))AND(c.x,c.y)NOT IN((a.x,a.y),(b.x,b.y));

```

:g is the grid as a string
:w is the width of the grid

Returns no line as truthy, return the rectangles that do not match the criteria as falsy

Un-golfed

```
WITH v AS
(
  SELECT MOD(LEVEL-1,:w)x,FLOOR((LEVEL-1)/:w)y,SUBSTR(:g,LEVEL,1)p
  FROM   DUAL
  WHERE  'O'=SUBSTR(:g,LEVEL,1)
  CONNECT BY LEVEL<=LENGTH(:g)
)
SELECT a.*,b.*FROM v a,v b
WHERE b.x>a.x AND b.y>a.y
MINUS
SELECT a.*,b.*FROM v a,v b,v c
WHERE((c.x IN(a.x,b.x) AND c.y>=a.y AND c.y<=b.y) OR (c.y IN(a.y,b.y) AND c.x>=a.x AND c.x<=b.x))
  AND(c.x,c.y)NOT IN((a.x,a.y),(b.x,b.y));

```

The view v compute the coordinates of each O point.
The first part of the minus return all rectangles, the where clause insures that a point can not be paired with itself.
The second part search for a third point in each rectangle. That point needs to have one coordinate,x or y, equals to that coordinate for one of the two points defining the rectangle. The other coordinate of that third point needs to be in the range bounded by that coordinate for each of the points defining the rectangle.
The last part of the where clause insures that the third point is not one of the two points defining the rectangle.
If all the rectangles have at least a third point then the first part of the minus is equal to the second part and the query returns nothing.

# Answer
> 2 votes
# PHP, 1123 bytes, 851 bytes, 657 bytes

(newbie php)

```
<?php
$B=array_map("str_split",array_map("trim",file('F')));$a=[];$b=-1;foreach($B as $c=>$C){foreach($C as $d=>$Z){if($Z=='O'){$a[++$b][]=$c;$a[$b][]=$d;}}}$e=array();foreach($a as $f=>$l){foreach($a as $g=>$m){$h=$l[0];$i=$l[1];$j=$m[0];$k=$m[1];if($h!=$j&&$i!=$k&&!(in_array([$g,$f],$e,1)))$e[]=[$f,$g];}}$A=array();foreach($e as $E){$n=$E[0];$o=$E[1];$q=$a[$n][0];$s=$a[$n][1];$r=$a[$o][0];$t=$a[$o][1];$u=($q<$r)?$q:$r;$v=($s<$t)?$s:$t;$w=($q>$r)?$q:$r;$X=($s>$t)?$s:$t;$Y=0;foreach($a as $p){$x=$p[0];$y=$p[1];if($x>=$u&&$x<=$w&&$y>=$v&&$y<=$X){$Y=($x==$q&&$y==$s)||($x==$r&&$y==$t)?0:1;}if($Y==1)break;}if($Y==1)$A[]=1;}echo count($A)==count($e)?1:0;

```

explaination (commented code) :

```
<?php
//read the file
$lines=array_map("str_split",array_map("trim",file('F'))); // grid in file 'F'

//saving coords
$coords=[]; // new array
$iCoord=-1;
foreach($lines as $rowIndex=>$line) {
    foreach($line as $colIndex=>$value) {
        if ($value=='O'){
            $coords[++$iCoord][]=$rowIndex;//0 is x
            $coords[$iCoord][]=$colIndex;  //1 is y
        }
    }
}

/* for each point, draw as many rectangles as other points
 * without creating 'mirror' rectangles
 */
$rectangles=array();

foreach ($coords as $point1Index=>$point1) {
     //draw
     foreach ($coords as $point2Index=>$point2) {
            $point1X=$point1[0];
            $point1Y=$point1[1];
            $point2X=$point2[0];
            $point2Y=$point2[1];
            //if not on the same line or on the same column, ...
            if ($point1X!=$point2X &&   // same line
                $point1Y!=$point2Y &&   // same column
                !(in_array([$point2Index,$point1Index],$rectangles,true)) //... and if no 'mirror one' already
             ) $rectangles[]=[$point1Index,$point2Index]; //create a new rectangle
     }
 }

//now that we have rectangles and coords
//try and put a third point into each
$tests=array();
foreach ($rectangles as $rectangle) {
    $pointA=$rectangle[0];    // points of the rectangle
    $pointB=$rectangle[1];    // __________"____________
    $xA=$coords[$pointA][0];
    $yA=$coords[$pointA][1];
    $xB=$coords[$pointB][0];
    $yB=$coords[$pointB][1];
    $minX=($xA<$xB)?$xA:$xB;
    $minY=($yA<$yB)?$yA:$yB;
    $maxX=($xA>$xB)?$xA:$xB;
    $maxY=($yA>$yB)?$yA:$yB;

    $arborally=false;
    foreach ($coords as $point) {
        $x=$point[0];
        $y=$point[1];
        if ($x>=$minX &&
            $x<=$maxX &&
            $y>=$minY &&
            $y<=$maxY) {
                $arborally=($x==$xA&&$y==$yA) || ($x==$xB&&$y==$yB)?0:1; //same point (pointA or pointB)
        }
        if ($arborally==true) break;//1 found, check next rectangle
    }
    if ($arborally==true) $tests[]=1;//array of successes

}

echo count($tests)==count($rectangles)?1:0; //if as many successes than rectangles...

?>

```

# Answer
> 2 votes
# MATL, 38 bytes

```
Ti2\2#fh!XJ"J@-XKtAZ)"@K-@/Eq|1>~As2>*

```

This uses a 2D char array as input, with rows separated by `;`. So the first example is

```
['......';'....O.';'......';'.O..O.';'......']

```

The rest of the test cases in this format are as follows.

* Arborally satisfied:

```
['.OOO.';'OO...';'.O.OO';'.O..O';'....O']
['..O..';'OOOO.';'...O.';'.O.O.';'...OO']
['O.O.';'..O.';'OOOO';'.O.O';'OO..']
['...';'...';'...']
['...';'..O';'...']
['O.....';'O.O..O';'.....O']
['OOO.OO']

```
* Not arborally satisfied:

```
['..O..';'O....','...O.';'.O...';'....O']
['..O..';'O.OO.';'...O.';'.O.O.';'...OO']
['O.....';'..O...';'.....O']

```

**Try it online!** You can also **verify all test cases at once**.

### Explanation

The code first gets the coordinates of characters `O` in the input. It then uses two nested loops. The outer loop picks each point P (2-tuple of its coordinates), compares with all points, and keeps points that differ from P in the two coordinates. Those are the points than can form a rectangle with P. Call them set R.

The inner loop picks each point T from R, and checks if the rectangle defined by P and T includes at least 3 points. To do that, it subtracts P from all points; that is, moves the origin of coordinates to P. A point is in the rectangle if each of its coordinates divided by the corresponding coordinate of T is in the closed interval \[0, 1\].

```
T          % push "true"
i          % take input 2D array
2\         % modulo 2: gives 1 for 'O', 0 for '.'
2#f        % row and column coordinates of ones. Gives two column arrays
h!         % concatenate horizontally. Transpose. Each point is a column
XJ         % copy to clipboard J
"          % for each column
  J        %   push all points
  @-       %   subtract current point (move to origin)
  XK       %   copy to clipboard K
  tA       %   logical index of points whose two coordinates are non-zero
  Z)       %   keep only those points. Each is a column
  "        %   for each column (point)
    @K-    %     push that point. Subtract all others
    @/     %     divide by current point
    Eq|1>~ %     true if in the interval [0,1]
    A      %     true if that happens for the two coordinates
    s      %     sum: find out how many points fulfill that
    2>     %     true if that number is at least 3
    *      %     multiply (logical and). (There's an initial true value at the bottom)
           %   end
           % end
           % implicit display

```

# Answer
> 1 votes
# C, 289 bytes

```
a[99][99],x,X,y,Y,z,Z,i,c;main(k){for(;x=getchar(),x+1;x-10||(y=0,i++))a[y++][i]=x;for(;X<i;X++)for(x=0;a[x][X]-10;x++)for(Y=X+1;Y<i;Y++)for(y=0;a[y][Y]-10;y++)if(x-y&&!(a[x][X]-79||a[y][Y]-79)){c=0;for(Z=X;Z<=Y;Z++)for(z=x<y?x:y;z<=(x>y?x:y);)a[z++][Z]-79||c++;c-2||(k=0);}putchar(k+48);}

```

Requires trailing newline, which is permitted (without the newline, the code would be two bytes larger). Outputs 0 (not arborally satisfied) or 1 (arborally satisfied).

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


# Question
Title: Write a program that converts unary input to binary, decimal, and hexadecimal equivalents
Write a program that accepts input (through stdin) as a string of unary numbers delimited by spaces, and prints the equivalent string of numbers in binary, decimal, and hexadecimal. These unary symbols are allowed:

* stroke, `'/'` or `'\'`
* Decimal `1`
* ASCII `'I'`
* ASCII `'-'`

Your program does *not* have to support all symbols, but it must use at least one. Zero should be represented as simply two spaces (the lack of unary symbols)

e.g. if the input is

**Test Cases:**

Input:

```
1 11 111 1111111111

```

Example Output:

```
1 2 3 10

1 2 3 A

1 10 11 1010

```

Output must be to standard output. If no standard output is available, use whatever output logging stream is available.

It does not have to print the converted strings in any particular order; it must print the binary, hexadecimal, and decimal string equivalents, but it does not have to print in that specific order.

This is code-golf, so shortest program wins!

# Answer
# Python 3, 68 bytes

```
i=input().split(" ")
for f in[bin,str,hex]:print(*map(f,map(len,i)))

```

Outputs like such:

```
0b1 0b10 0b11
1 2 3
0x1 0x2 0x3

```

If the `0b` and `0x` are not allowed then that can be solved at the cost of 17 extra bytes by changing the second line to:

```
for f in[bin,str,hex]:print(*(f(len(n))[2*(f!=str):]for n in i))

```

Or using this version (minified version of My Ham DJ's answer):

```
i=input().split(" ")
for b in"dxb":print(*("{:{}}".format(len(x),b)for x in i))

```
> 6 votes

# Answer
## JavaScript (ES6), 76 bytes

```
s=>[2,10,16].map(b=>s.split` `.map(n=>n.length.toString(b)).join` `).join`
`

```
> 5 votes

# Answer
# Pyth, 12 bytes

```
mjLld[2T16)c

```

Try it here!

Output is a list of lists with each sublist containing the binary, decimal and hex representation of the corrosponding input number as a list of digits.
> 1 votes

# Answer
# Python 3.5, 61 bytes:

(*+17 since zeroes count as an extra space*)

```
lambda g:[(bin(len(f)),hex(len(f)),len(f))for f in g.split(" ")]

```

Pretty much speaks for itself. It is a lambda function, so you must provide input. Then, the function takes "g", which is your input, and outputs the correct values. If, for instance, the input is `"111 11"`, output is as follows:

> \[('0b11', '0x3', 3), ('0b10', '0x2', 2)\]

I honestly think that including the `0b` and `0x` is a better choice than removing them, since then this way, you can differentiate between those numbers that are hexadecimal, those which are binary, and those which are just plain denary (decimal).

And now, if the input is, for instance, `"011"`, it counts the `0` as an extra space, and as a result outputs `[('0b10', '0x2', 2)]`.

**EDIT:** AS per @isaacg's input, I have now fixed by program, and it should work as it should. The code now has the ability for extra spaces between ones to become zeroes. Now, if the input is, for instance, `11<space><space>1`, the output is `[('0b1', '0x1', 1), ('0b0', '0x0', '0'), ('0b10', '0x2', 2)]` counting the extra space as a `'0 '`.
> 1 votes

# Answer
## Pyke, 14 bytes

```
dcmlD
mb2Rmb16

```

Try it here
> 1 votes

# Answer
# Ruby, ~~89~~ 58 bytes

Anonymous function; Returns a list of lists where each sublist contains binary, decimal, and hex representations, and accounts for extra spaces.

@manatwork is a Ruby wizard

```
->s{[2,10,16].map{|b|s.split(/ /).map{|n|n.size.to_s(b)}}}

```

Without the need to check for the spare spaces meaning 0, it drops to 53 bytes:

```
->s{[2,10,16].map{|b|s.split.map{|n|n.size.to_s(b)}}}

```
> 0 votes

# Answer
## Java, 136 bytes

```
s->{String[]l=s.split(" ",-1);s="";for(int i=2;i<17;i+=i<3?8:6){for(String n:l)s+=Integer.toString(n.length(),i)+" ";s+="\n";}return s;}

```

Try it online!

This is an anonymous function (lambda) that takes a String and returns a String representing the output as described.

Full explanation will come later today.
> 0 votes

---
Tags: code-golf, base-conversion
---


title: Make this code explanation pretty again

text:
# Question
Title: Make this code explanation pretty again
# Introduction

Most code-golfers here add explanations to their submissions, so it's easier to understand what's going on. Usually the codelines go on the left and the corresponding explanation to the right with some kind of separator. To make it look pretty, the separators are all on the same column. Also long explanation text is usually wrapped to the next line, so the readers don't have to scroll horizontally to read everything.

However, when you want to edit this explanation because you made some crazy golfs, you often end up spending time to make your explanation pretty again. Since this is a very repetitive task, you want to write a program for this.

# The Challenge

Given several lines of code with explanation and a separator, output the nicely formatted code with explanation.

### Example

**Input**

```
shM-crz1dc4."ANDBYOROF  # z = input

     rz1      # convert input to uppercase
    c   d        # split input on spaces
         c4."ANDBYOROF        # create a list of the words from a packed string which shall be ignored
   -          # filter those words out
 hM                # only take the first letter of all words
s                   # join them into one string

```

**Output**

```
shM-crz1dc4."ANDBYOROF     # z = input

     rz1                   # convert input to uppercase
    c   d                  # split input on spaces
         c4."ANDBYOROF     # create a list of the words from a packed string which shall be
                           # ignored
   -                       # filter those words out
 hM                        # only take the first letter of all words
s                          # join them into one string

```

*One cookie for the first one who can find out what this code does.*

### The formatting algorithm

* Find the longest code-line (excluding the explanation and the spaces between code and separator).
* Add 5 spaces after this code-line and append the corresponding separator with explanation. This is now the reference line.
* Adjust every other line to this reference line, so that the seperators are all in the same column.
* Wrap all lines that are longer than 93 characters to a new line in the following way:
    + Find the last word which end is at column 93 or lower.
    + Take all words after this one and wrap them to a new line with the leading separator and the correct spacing. The space between those two words has to be deleted, so the first line ends with a word character and the second line starts with one after the separator.
    + If the resulting line is still longer than 93 characters do the same again until every line is below 94 characters.

### Notes

* A word consists of non-whitespace characters. Words are separated by a single space.
* The word wrapping is always possible. This means that no word is so long that it would make the wrapping impossible.
* The input will only contain printable ASCII and won't have any trailing whitespaces
* The separator will only appear once per line.
* While the explanation can have unlimited length, the separator and the code can only have a combined maximum length of `93 - 5 = 87` chars. The 5 chars are the spaces between code and separator. Code and separator will always be at least one character long.
* The input may contain empty lines. Those will never contain any characters (except a newline if you take input as multiline string). Those empty lines have to be present in the output as well.
* Every line will have some code, a separator and an explanation. Exceptions are empty lines.
* You may take the input in any reasonable format, as long as it is not pre-processed. Make it clear in your answer which one you use.
* Output can be a multiline string or a list of strings.

# Rules

# Test cases

Input format here is a list of string representing the lines and a single string for the separator. Both are separated by a comma. Output is a list of strings.

```
['shM-crz1dc4."ANDBYOROF  # z = input', '', '     rz1      # convert input to uppercase', '    c   d        # split input on spaces', '         c4."ANDBYOROF        # create a list of the words from a packed string which shall be ignored', '   -          # filter those words out', ' hM                # only take the first letter of all words', 's                   # join them into one string'], "# " -> ['shM-crz1dc4."ANDBYOROF     # z = input', '', '     rz1                   # convert input to uppercase', '    c   d                  # split input on spaces', '         c4."ANDBYOROF     # create a list of the words from a packed string which shall be', '                           # ignored', '   -                       # filter those words out', ' hM                        # only take the first letter of all words', 's                          # join them into one string']
['codecodecode   e#Explanation', 'sdf dsf sdf e#A Very very very very very very very very very long long long long long long long long long long long explanation and it keeps getting longer and longer', '', 'some more codee#  and some more explanation'], "e#" -> ['codecodecode       e#Explanation', 'sdf dsf sdf        e#A Very very very very very very very very very long long long long long ', '                   e#long long long long long long explanation and it keeps getting longer', '                   e#and longer', '', 'some more code     e# and some more explanation']

```

**Happy Coding!**

# Answer
> 3 votes
# Ruby, ~~245~~ ~~237~~ ~~220~~ ~~216~~ ~~212~~ ~~209~~ 205 bytes

Anonymous function. Pretty basic approach (find max length, add 5, then do processing on each line, with recursion to deal with wrapping) and there might be another approach that saves more bytes.

I deleted the answer earlier that didn't fulfill all the requirements; I didn't want to have a half-answered code as an answer (it was getting downvotes for being incomplete too) but it should do everything the question asks for, now.

```
->x,d{l,S=0," "
s=->n{m,q=n.size,94-l-d.size
m>q ?(i=n.rindex(S,q)
n[0,i]+"
"+S*l+d+s[n[i+1,m]]):n}
x.map{|n|c,t=n.split d
c=(c||S).rstrip
l=[l,5+c.size].max
[c,t]}.map{|c,t|c+S*(l-c.size)+d+s[t]if t}*"
"}

```

---

### Changelog:

* Saved some bytes by leveraging some of the promises in the input, especially the promise that all non-empty lines have the separator character and an explanation.
* Managed to golf a little more by saving the split strings from the first `map` call and taking out some unnecessary `strip` functions based on the promise that the words in the explanation always have exactly one space between them. Also, `" "` is assigned to a constant now since I use it so much.
* Chained both of the `map` calls together by leveraging the power of higher-order functions, meaning that the first map call will set the length variable `l` correctly even if it's called after the declaration of the helper function `s`. -4 bytes.
* Abused multiline strings to replace `\n` with actual newlines, plus a little trick using `if` over ternary operators (when `join` is called on an array with `nil` values, they become empty strings)
* `.join` can apparently be replaced with a `*`.

# Answer
> 9 votes
# LiveScript, ~~243~~ ~~236~~ ~~233~~ ~~228~~ ~~219~~ 225 bytes

```
f = (x,k,m+5)->l=(.length);x.=map(->it/"#k"=>..0-=/ +$/;m>?=5+l ..0);i=0;[..0&&..0+' '*(m- l ..0)+k+..1 for x]=>while i<(l ..),++i=>j=(s=..[i])lastIndexOf ' ' 93;(..splice i+1 0 ' '*m+k+s[j to]*'';s.=substr 0 j) if 94<l s;..[i]=s

```

How it works: mostly like the Java code. Start off by aliasing length (LiveScript allows to create a function from operators by using parentheses). `.=` is `a = a.b` \- which we use here to map.

`=> blabla ..` is the Smalltalk-ish cascade construct: the left side of `=>` is accessible as `..` for the rest of the block; and will be returned. Here, it's the element split on k. Note: I'm using string interpolation, because `/` only means "split" with a literal string.

LS allows us to use `a-=/regexp/` in this lambda as well (also works with string literals): it's just sugar for a `.replace` call.

Finally, the `>?=` is the combinatory `>?`-assign operator, which returns the greater of two operands.

LS has Python/Haskell-style for comprehensions, with nothing fancy in them, except the "string * times" to repeat the space long enough.

This for comprehension serves as the topic (see the block about cascades anove).

We then loop into each element of the array (the one we just built with the comprehension), and if any line is bigger than 93chars, we find the last index of , split there, and push the separated line right after this current iteration's (... So that the next iteration will split again if the line's too big).

Only last thing fancy `a[j to]` is a range (from j to the end), but since it uses Array methods we have to join it back to a string, which we do using overloaded `*`: `*''`.

example

```
s = """this is kod # Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
d # y

efgh # z"""

f = (x,k,m=5)->l=(.length);x.=map(->it/"#k"=>..0-=/ +$/;m>?=5+l ..0);i=0;[..0&&..0+' '*(m- l ..0)+k+..1 for x]=>while i<(l ..),++i=>j=(s=..[i])lastIndexOf ' ' 93;(..splice i+1 0 ' '*m+k+s[j to]*'';s.=substr 0 j) if 94<l s;..[i]=s

console.log (f s / '\n', '#') * \\n

```

output:

```
this is kod     # Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
                # tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
                # veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                # commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
                # velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
                # cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
                # est laborum.
d               # y

efgh            # z

```

# Answer
> 6 votes
## Java, 347 + 19 = 366 bytes

Requires

```
import java.util.*;

```

Thus the +19 bytes.

```
(c,s)->{int p=0,i=0,t;String l;for(;i<c.size();i++){l=c.get(i);l=l.replaceAll(" *"+s,s);p=Math.max(l.indexOf(s),p);c.set(i,l);}p+=5;for(i=0;i<c.size();i++){l=c.get(i);t=l.indexOf(s);while(t>-1&t<p)l=l.substring(0,t)+" "+l.substring(t++);t=93;if(l.length()>t){while(l.charAt(t)!=' ')t--;c.add(i+1,s+l.substring(t));l=l.substring(0,t);}c.set(i,l);}}

```

Takes in the format `f.accept(List<String> code, String seperator)`. Formats in-place. A version that creates and returns a new `List<String>` would be trivial to implement but cost some bytes.

Indented + example usage:

```
static BiConsumer<List<String>, String> prettify = (code, seperator) -> {
    int space = 0, i=0, t;
    String line;
    for (; i<code.size(); i++) { // for each line
        line = code.get(i); // get line
        line = line.replaceAll(" *" + seperator, seperator); // strip space before seperator
        space = Math.max(line.indexOf(seperator), space); // save biggest space until seperator
        code.set(i, line); // save line
    }
    space += 5;
    for (i=0; i<code.size(); i++) { // for each line
        line = code.get(i); // get line
        t = line.indexOf(seperator); // get index of seperator
        while (t>-1&t<space) // while the seperator exists and is further left than desired
            line = line.substring(0,t) + " " + line.substring(t++); // move it right by adding a space before it
        t = 93; // get desired line length
        if (line.length()>t) { // if the line is longer than that
            while (line.charAt(t)!=' ') t--; // scan backwards for a space
            code.add(i+1, seperator + line.substring(t)); // add a line after this one with seperator and the rest of the line
                                                          // the next pass will space it correctly
            line = line.substring(0,t); // cut off this line at that point
        }
        code.set(i, line); // save edited line back to List
    }
};

public static void main(String[] args) {
    List<String> code = new ArrayList<>();
    code.add("shM-crz1dc4.\"ANDBYOROF  # z = input");
    code.add("");
    code.add("     rz1      # convert input to uppercase");
    code.add("    c   d        # split input on spaces");
    code.add("         c4.\"ANDBYOROF        # create a list of the words from a packed string which shall be ignored");
    code.add("   -          # filter those words out");
    code.add(" hM                # only take the first letter of all words");
    code.add("s                   # join them into one string");
    prettify.accept(code, "#");
    code.stream().forEach(System.out::println);
}

```

... I should probably run this through itself :P

# Answer
> 2 votes
# PowerShell, ~~224~~ ~~217~~ 235 bytes

```
param($d,$s)$d=$d-split"`r`n";$p="\s+\$([char[]]$s-join"\")\s";$m=($d|%{($_-split$p)[0].Length}|sort)[-1];$d|%{$l,$c=$_-split$p;$c=if($c){"$s "+(("$c "-split"(.{1,$(87-$m)})\s"|?{$_})-join"`n$(" "*($m+5))$s ")}$l.PadRight($m+5," ")+$c}

```

Updated the logic to determine the max code string length. Updated to allow multiple separators that include regex meta characters.

---

**Little Explanation**

This takes in a whole newline delimited string for input.

```
param($d,$s)
# $d is a newline delimited string. $s is the separator.
# Take the string and turn it into a string array. Stored as $d
$d=$d-split"`r`n"
# Save a regex pattern as it is used more than once
$p="\s+\$([char[]]$s-join"\")\s"
# Get the longest string of code's length
$m=($d|%{($_-split$p)[0].Length}|sort)[-1]
# Split each line again into code and comment. Write out each line with formatted explanations based on separator column position $m
$d|%{
# Split the line
$l,$c=$_-split$p
# Build the comment string assuming there is one.
$c=if($c){"$s "+(("$c "-split"(.{1,$(87-$m)})\s"|?{$_})-join"`n$(" "*($m+5))$s ")}
# Pad the right amount of space on the code and add the comment string.
$l.PadRight($m+5," ")+$c
}

```

**Sample Output with some Lorem Ipsum**

```
shM-crz1dc4."ANDBYOROF     # z = input

     rz1                   # convert input to uppercase
    c   d                  # split input on spaces
         c4."ANDBYOROF     # But I must explain to you how all this mistaken idea of
                           # denouncing pleasure and praising pain was born and I will give
                           # you a complete account of the system, and expound the actual
                           # teachings of the great explorer
   -                       # filter those words out
 hM                        # only take the first letter of all words
s                          # join them into one string

```

# Answer
> 1 votes
# MATLAB, ~~270~~ ~~265~~ 262 bytes

```
function d=f(I,s);S=@sprintf;R=@regexprep;m=regexp(I,['\s*\',s]);L=max([m{:}])+4;a=@(x)S('%-*s%s',L,x,s);b=@(x)R(R(x,S('(.{1,%d}(\\s+|$))',93-L),S('$1\n%*s ',L+1,s)),['\n\s*\',s,' $'],'');c=R(I,['(.*?)\s*\',s,'\s*(.*$)'],'${a($1)} ${b($2)}');d=S('%s\n',c{:});end

```

The program accepts the input `I` in the form of a cell array of strings where each element of the cell array is a separate line of the input. It also accepts a second input which indicates what the comment character is (i.e. `#`). The function returns a multi-line string that is properly formatted.

**Brief Explanation**

```
function d = f(I,s)
    %// Setup some shortcuts for commonly-used functions
    S = @sprintf;
    R = @regexprep;

    %// Find the location of the space AFTER each code block but before a comment
    m = regexp(I, ['\s*\',s]);

    %// Compute the maximum column location of the code and add 4 (5 - 1)
    L = max([m{:}]) + 4;

    %// This is a callback for when we detect code
    %// It left justifies and pads the string to L width
    a = @(x)S('%-*s%s', L, x, s);

    %// This is a callback for when we detect a comment.
    b = @(x)R(...
            R(x, ...
                S('(.{1,%d}(\\s|$))', 93 - L), ... Regex for wrapping text to desired width
                S('$1\n%*s ', L+1, s)), ... Append a newline and padding for next line
            ['\n\s*\',s,' $'], ''); ... Remove the trailing newline (to be improved)

    %// Perform replacement of everything.
    c = R(I, ...
            ['(.*?)\s*\',s,'\s*(.*$)'], ... Match "code comment_char comment"
            '${a($1)} ${b($2)}');   ... Replace using the output of the callbacks

    %// Concatenate all of the strings together with a newline in between
    d=S('%s\n',c{:});
end

```

**Example Input**

```
I = {
    'shM-crz1dc4."ANDBYOROF  # z = input'
    ''
    '     rz1      # convert input to uppercase'
    '    c   d        # split input on spaces'
    '         c4."ANDBYOROF        # create a list of the words from a packed string which shall be ignored'
    '   -          # filter those words out'
    ' hM                # only take the first letter of all words'
    's                   # join them into one string'
};

disp(f(I,'#'));

```

**Example Output**

```
shM-crz1dc4."ANDBYOROF     # z = input

     rz1                   # convert input to uppercase
    c   d                  # split input on spaces
         c4."ANDBYOROF     # create a list of the words from a packed string which shall be
                           # ignored
   -                       # filter those words out
 hM                        # only take the first letter of all words
s                          # join them into one string

```

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


title: Determine the type of an input

text:
# Question
Title: Determine the type of an input
The challenge is simple: Determine the type of an input, and output an identifier telling what type it is.

* "UI", Unsigned integer: `0`, `1`,`34`, `111111111111111111111111111111111111111111`
* "SI", Signed integer: `+0`, `+1`, `+42`, `-1`, `-3`, `-111111111111111111111111111111111111111111`
* "UD", Unsigned decimal: `0.0`, `1.23`, `1234.1234`
* "SD", Signed decimal: `-0.0`, `+0.0`, `-1.235`
* "LE", Letter: `a`-`z` and `A`-`Z`
* "SY", Symbol: ASCII code points: `[32-47, 58-64, 91-96, 123-126]` (i.e. all characters except numbers and letters)
* "ST", String: Two or more character that can't be parsed as any of the above number formats

**Rules:**

* The input will be 1-99 characters long
* The input will only contain printable ASCII characters, code points: 32-126.
* The output should be the two identifier letters as defined above (UI, SI ...)
* Standard I/O rules apply

**Examples:**

```
UI:
0
01
34
12938219383278319086135768712319838871631827319218923

SI:
-0
+01
+1
-123
+123

UD:
0.0
3.1415
2.718281828459045235360287471352662497757

SD:
+0.0
-3.1415
+2.718281828459045235360287471352662497757

LE:
a
k
L
Z

SY:
@
"
+
-

ST:
Hello, World!
f2!"
+23df
1234A
'"!
.012
1.
UI
+-1
5+3

```

# Answer
> 0 votes
# Pyth - 47 bytes

Can prolly golf a few bytes off with some slicing tricks.

```
.x-+?@z"+-"\S\U?@z\.\D\Isz?!tz?}rzZG"LE""SY""ST

```

Test Suite.

# Answer
> 5 votes
# JavaScript (ES6), 99

```
x=>(z=x.match(/^([+-])?\d+(\.\d+)?$/))?'SU'[+!z[1]]+'DI'[+!z[2]]:x[1]?'ST':parseInt(x,36)?'LE':'SY'

```

**Test**

```
f=x=>(z=x.match(/^([+-])?\d+(\.\d+)?$/))?'SU'[+!z[1]]+'DI'[+!z[2]]:x[1]?'ST':parseInt(x,36)?'LE':'SY'

console.log=x=>O.textContent+=x+'\n'

;console.log(['0','01','34','12938219383278319086135768712319838871631827319218923'].map(x=>f(x)+' '+x).join`\n`)
;console.log(['-0','+01','+1','-123','+123'].map(x=>f(x)+' '+x).join`\n`)
;console.log(['0.0','3.1415','2.718281828459045235360287471352662497757'].map(x=>f(x)+' '+x).join`\n`)
;console.log(['+0.0','-3.1415','+2.718281828459045235360287471352662497757'].map(x=>f(x)+' '+x).join`\n`)
;console.log([...'akLZ'].map(x=>f(x)+' '+x).join`\n`)
;console.log([...'@"+-'].map(x=>f(x)+' '+x).join`\n`)
;console.log(['Hello, World!','f2!"','+23df','1234A',`'"!`,'.012','1.','UI','+-1','5+3'].map(x=>f(x)+' '+x).join`\n`)
```

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

# Answer
> 3 votes
# Turing Machine Code, 1544 bytes

Try it online!

```
0 + _ r s
0 - _ r s
0 0 _ r u
0 1 _ r u
0 2 _ r u
0 3 _ r u
0 4 _ r u
0 5 _ r u
0 6 _ r u
0 7 _ r u
0 8 _ r u
0 9 _ r u
0 a _ r l
0 b _ r l
0 c _ r l
0 d _ r l
0 e _ r l
0 f _ r l
0 g _ r l
0 h _ r l
0 i _ r l
0 j _ r l
0 k _ r l
0 l _ r l
0 m _ r l
0 n _ r l
0 o _ r l
0 p _ r l
0 q _ r l
0 r _ r l
0 s _ r l
0 t _ r l
0 u _ r l
0 v _ r l
0 w _ r l
0 x _ r l
0 y _ r l
0 z _ r l
0 A _ r l
0 B _ r l
0 C _ r l
0 D _ r l
0 E _ r l
0 F _ r l
0 G _ r l
0 H _ r l
0 I _ r l
0 J _ r l
0 K _ r l
0 L _ r l
0 M _ r l
0 N _ r l
0 O _ r l
0 P _ r l
0 Q _ r l
0 R _ r l
0 S _ r l
0 T _ r l
0 U _ r l
0 V _ r l
0 W _ r l
0 X _ r l
0 Y _ r l
0 Z _ r l
0 * _ r y
s 0 _ r s
s 1 _ r s
s 2 _ r s
s 3 _ r s
s 4 _ r s
s 5 _ r s
s 6 _ r s
s 7 _ r s
s 8 _ r s
s 9 _ r s
s . _ r d
s _ _ r i
s * _ r T
u 0 _ r u
u 1 _ r u
u 2 _ r u
u 3 _ r u
u 4 _ r u
u 5 _ r u
u 6 _ r u
u 7 _ r u
u 8 _ r u
u 9 _ r u
u . _ r D
u _ _ r I
u * _ r T
l _ _ r L
l * _ r T
y _ _ r S
y * _ r T
d 0 _ r d
d 1 _ r d
d 2 _ r d
d 3 _ r d
d 4 _ r d
d 5 _ r d
d 6 _ r d
d 7 _ r d
d 8 _ r d
d 9 _ r d
d _ _ r e
d * _ r T
i 0 _ r i
i 1 _ r i
i 2 _ r i
i 3 _ r i
i 4 _ r i
i 5 _ r i
i 6 _ r i
i 7 _ r i
i 8 _ r i
i 9 _ r i
i _ _ r j
i * _ r T
D 0 _ r D
D 1 _ r D
D 2 _ r D
D 3 _ r D
D 4 _ r D
D 5 _ r D
D 6 _ r D
D 7 _ r D
D 8 _ r D
D 9 _ r D
D _ _ r E
D * _ r T
I 0 _ r I
I 1 _ r I
I 2 _ r I
I 3 _ r I
I 4 _ r I
I 5 _ r I
I 6 _ r I
I 7 _ r I
I 8 _ r I
I 9 _ r I
I _ _ r J
I * _ r T
L * L r M
M * E r halt
S * S r Y
Y * Y r halt
e * S r f
f * D r halt
j * S r k
k * I r halt
E * U r f
J * U r k
T _ S r U
T * _ r T
U * T r halt

```

# Answer
> 2 votes
# Retina, ~~98~~ 97 bytes

A nice way to practise my regex skills indeed.

Try it online!

```
^(?![+-]?\d+(\.\d+)?$)..+
ST
^([+-]?)\d+$
$1UI
^([+-]?)\d+\.\d+$
$1UD
i`^[a-z]$
LE
^.$
SY
[+-]U
S

```

# Answer
> 1 votes
# Lua, 157 bytes

Try it online!

Golfed:

```
n=(...)m=string.match s=m(n,"^[+-]")and"S"or"U"print(m(n,"^[+-]?%d+%.%d+$")and s.."D"or m(n,"^[+-]?%d+")and s.."I"or m(n,"^%w$")and"LE"or#n==1 and"SY"or"ST")

```

Ungolfed:

```
n = "2.718281828459045"

s = n:sub(1,1):match("[+-]") and "S" or "U"

if n:match("^[+-]?%d+%.%d+$") then
    print(s.."D")
elseif n:match("^[+-]?%d+") then
    print(s.."I")
elseif n:match("^%w$") then
    print("LE")
elseif #n==1 then
    print("SY")
else
    print("ST")
end

```

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

```
s=>"UISIUDSDLESYST".substr(s.match(/^((\d+)|([+-]\d+)|(\d+\.\d+)|([+-]\d+\.\d+)|([A-Z])|(.)|(.*))$/i).indexOf(s,2)*2-4,2)

```

Alternative version, also 120 bytes:

```
s=>"STUISIUDSDLESY".substr(s.match(/^(?:(\d+)|([+-]\d+)|(\d+\.\d+)|([+-]\d+\.\d+)|([A-Z])|(.)|.*)$/i).lastIndexOf(s)*2,2)

```

# Answer
> 0 votes
# Java, 192 bytes

```
String t(String v){for(String[]x:new String[][]{{"\\d+","UI"},{"[-+]\\d+","SI"},{"\\d+\\.\\d+","UD"},{"[-+]\\d+\\.\\d+","SD"}})if(v.matches(x[0]))return x[1];return (v.length()==1?"SY":"ST");}

```

# Answer
> 0 votes
# Javascript (ES6), 138 bytes

I tried to use a `replace` to be more "fancy".

This creates an anonymous function that returns the string of the type.

```
s=>s.replace(/^((([+-])?(\d+)(\.\d+)?)|([a-z])|([ -~])|([^\0]*))$/i,(_,a,b,c,d,e,f,g)=>b?(c?'S':'U')+(e?'D':'I'):(f?'LE':'S'+(g?'Y':'T')))

```

Any tips to improving this will be entirely welcome.

# Answer
> 0 votes
# Python 3.5 - 241 240 bytes:

(*Saved 1 byte thanks to @CatsAreFluffy*)

```
import re
def r(g):
 y={'^\d+$':'UI','^[+-]\d+$':'SI','^[0-9]\d*(\.\d+)?$':'UD','[+-](?=[0-9]\d*(\.\d+))':'SD','[a-zA-Z]+':'LE','^[^A-Za-z0-9]+$':'SY'};d=[y[i]for i in list(y.keys())if re.match(i,g)]
 if len(d)>0:return d[0]
 else:return'ST'

```

It may be a bit long, but does the job pretty much perfectly. This was a really good way to improve my regular expression skills. Thanks for the challenge. :) I will try and shorten it more if I can.

# Answer
> 0 votes
# Tcl 414 Bytes

ungolfed implementation, readable:

```
proc a b {
  if {[string index $b 0] eq "+" || [string index $b 0] eq "-"} {
    set c S
  } elseif {[string match {[A-Za-z]} $b]} {
    return LE
  } elseif {[regexp {^(?![+-]?\d+(\.\d+)?$)..+} $b]} {
    return ST
  } elseif {[regexp {[^a-zA-Z0-9.]} $b]} {
    return SY
  } else {
    set c U
  }
  if {[string match *.* $b]} {
    return $c\U
  } else {
    return $c\I
  }
}
puts [a $argv]

```

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


title: Is this a Lucas number?

text:
# Question
Title: Is this a Lucas number?
Write a program or function that takes an input greater than or equal to 2. It should output a truthy or falsy value corresponding to whether the input is a Lucas number or not. You may take input from STDIN, or whichever source is most suitable to you.

This question is different to this one because this question is specifically for Lucas numbers only, and not Fibonacci numbers at all, whereas that question was Lucas number, Fibonacci numbers and both possible combinations of them. This question was, however, inspired by that question and is similar in some regards.

Lucas numbers are the numbers that result from the rules following: the first Lucas number is a 2, the second is a 1, and each term after that is the sum of the previous two. Yes, it is very similar to the Fibonacci sequence, but this has the added advantage of converging closer to the golden ratio, phi, faster than Fibonacci numbers do.

# Example inputs/outputs

```
Input   Output
--------------
3       True
4       True
7       True
8      False
10     False
3421   False
9349    True

```

etc.

# Some limitations

* Your program/function must run in a reasonable amount of time. It should terminate within seconds and minutes, not hours and days.
* Your program must not calculate all the Lucas numbers up to the input number

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

# Answer
> 2 votes
# MATL, ~~19~~ ~~17~~ ~~16~~ 18 bytes

```
2^5*20t_h+X^Xj1\~a

```

**Try it Online!**

**Explanation**

```
2^          % Implicitly grab the input and square it
5*          % Multiply the result by 5
20          % Create the literal number 20
t_          % Duplicate and negate the second 20
h           % Concatenate 20 and -20 to get [20 -20]
+           % Add the array to the result of 5*n^2
X^          % Compute the square root
Xj          % Ensure that the result is a real number
1\          % Compute the remainder to test for perfect squares
~a          % Check to see if any had a remainder of zero (returns a boolean)

```

# Answer
> 1 votes
# Python, ~~69~~ ~~67~~ 53 characters

```
lambda x:0in(((5*x**2+20)**.5)%1,((5*x**2-20)**.5)%1)

```

This works in both Python 2.x and 3.x.

See this answer to see how it works - `n` is a Lucas number if either `5n^2+20` or `5n^2-20` is a perfect square. My program checks to see if either of their square roots are integers and checks if 0 is in the tuple that results.

# Answer
> 1 votes
# Python, ~~45~~ 43 characters

```
lambda n:0in[(5*n*n+k)**.5%1for k in-20,20]

```

Based on a proof given here.

# Answer
> 1 votes
# MATLAB, 43 bytes

```
@(n)~all(rem(real(sqrt(5*n^2+[-20 20])),1))

```

Inspired by Anders Kaseorg's answer

---
Tags: code-golf, math, sequence
---