text:
Place a stone on an empty Go board
See also: Make a move on a Go board.
Task
Go is a board game where two players (Black and White) place stones on the intersections of grid lines on a 19×19 board. Black moves first — for example, on D4:

In this challenge, you must take a Go board coordinate like D4 as input, and output an ASCII representation of a board with the first move played at the given point.

Note that there is no column I. This is, historically, to reduce confusion with J and L.

This output consists of 19 lines, each containing 19 characters. The point with the stone on it is marked O. Empty points on the board are shown as ., except for the nine star points (at D4, D10, D16, K4, K10, K16, Q4, Q10, and Q16), which are marked *.
For example, given F5 as an input, your answer’s output must be:
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
.....O.............
...*.....*.....*...
...................
...................
...................

And given Q16 as input, your output must be:
...................
...................
...................
...*.....*.....O...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................

Rules

You may write a function that takes the coordinate as an argument, or a program that reads the coordinate from the command line or from STDIN.
You may choose to accept input either in lower-case or upper-case, but your answer doesn’t need to handle both.
The input is always a single string like a1 or T19, never a string + number or two strings.
If you write a full program, your answer must be printed to STDOUT as a string, optionally followed by a trailing newline. If your answer is a function, you may print to STDOUT, or return a string, or return an array/list of strings (rows), or return a two-dimensional array or nested list of characters.
This is code-golf. The shortest answer in bytes wins.

Just to be sure, "the coordinate as an argument" is meant to imply that we cannot take two arguments, like f("G", 14), correct?

Correct. ------

Congrats on 20k!!

"This is, historically, to reduce confusion with J and L." But both J and L are on the board??!

Yep. Also, of course, the missing letter has probably caused more confusion and surprise than anything…

@Fatalize, J and L look quite distinct since the lower parts turn in separate directions. As with j and l, one descends, the other goes up. But i and j are a bit similar, and so are i, l and I...

@Fatalize Yes, and I is not, so that you can't confuse I with J or I with L.

MATL, 33 bytes
'*O.'19: 6\4=&*Hj1&)Uw64-t8>-&(P)

Try it online!
Explanation
'*O.'    % Push string with needed characters. Will be indexed into
19:      % Push numeric vector [1 2 ... 19]
6\4=     % 1 for values that equal 4 mod 6, 0 for the rest
&*       % Multiply by transposed version of itself with broadcast. This gives
         % the 19×19 board with 0 instead of '.' and 1 instead of '*'
H        % Push 2. This will correspond to 'O' (stone)
j        % Input string, such as 'Q16'
1&)      % Split into its first char ('Q') and then the rest ('16')
U        % Convert to number (16)
w        % Swap, to move 'Q' to top
64-      % Subtract 64. Thus 'A' gives 1, 'B' gives 2 etc
t8>-     % Duplicate. Subtract 1 if it exceeds 8. This corrects for missing 'I'
&(       % Fill a 2 at coordinates given by the number and the letter
P        % Flip upside down, because matrix coordinates start up, not down
)        % Index the string '*O.' with the 19×19 array containing 0,1,2.
         % Implicitly display

C, 212 195 193 181 171 132 103 98 bytes
Saved 1 byte thanks to @FryAmTheEggman, 5 bytes thanks to @orlp
Call f() with the position to play (must be capitalized), and it prints out the resulting board.
i;f(char*p){for(i=380;i--;)putchar(i%20?i^20*atoi(p+1)+64-*p+(*p>72)?i%6^4|i/20%6^3?46:42:79:10);}

Try it on ideone.

98 bytes putchar(i%20?i^20*atoi(p+1)+64-*p+(*p>72)?i%6^4|i/20%6^3?46:42:79:10)

Thanks. I was looking for a way to reduce that modulo expression.

C (gcc), 132 128 109
i;m;f(char*s){for(i=380;i--;putchar(m?m^84-*s+(*s>73)|(i/20+1)^atoi(s+1)?m%6^4|i/20%6^3?46:42:79:10))m=i%20;}

Ideone
A function that prints the board to STDOUT. Requires the letter coordinate to be capital. Printing in one loop seems to be slightly shorter than the previous nested loop approach.

MATLAB, 135 bytes
A first attempt, nothing clever, just to see how much better others can do:
function go(a)
b=repmat('.',19);
b(4:6:end,4:6:end)='*';
a=sscanf(a,'%c%d');
a(1)=a(1)-64;
if a(1)>8
a(1)=a(1)-1;
end
b(20-a(2),a(1))='0'

Usage:
go('T19')

Welcome to PPCG! Some suggestions for reducing bytes: use a function name with 1 char (or a script with a=input('');); remove newlines; change '*' to 42 and '0' to 48; replace end by 19; subtract the logical value directly instead of the if branch. In fact, you can replace the last fiive lines by b(20-a(2),a(1)-64-(a(1)>8))=48

Hi and welcome to PPCG. If I'm not mistaken, your code is 137 bytes long and not 135. (I guess it doesn't matter a lot, but I just wanted to let you know)

Ruby, 93 91 bytes
Takes input on the command line, e.g. $ ruby script.rb Q16.
19.downto(1){|c|puts ([*?A..?T]-[?I]).map{|d|d+c.to_s==$*[0]??O:"DKQ"[d]&&c%6==4??*:?.}*""}

Test it on repl.it (wrapped in a lambda there since repl.it doesn't take command line arguments: https://repl.it/CkvT/1
Ungolfed
19.downto(1) do |row|
  puts ([*?A..?T] - [?I]).map {|column|
    if column + row.to_s == ARGV[0]
      "O"
    elsif "DKQ"[column] && row % 6 == 4
      "*"
    else
      "."
    end
  }.join
}

I think you can save a byte by doing $><< instead of puts . Not sure, though.

@QPaysTaxes Alas, I'd have to append a newline somewhere, then.

Oh, yep. Never mind

Go, 319 286 bytes
import(."strconv"
."strings")
func g(c string)(s string){p:=SplitN(c,"",2)
n,_:=Atoi(p[1])
for i:=19;i>0;i--{
for j:= 'a';j<'t';j++{
if j=='i'{
}else if n==i&&ContainsRune(p[0],j){s+="o"
}else if((i==4||i==10||i==16)&&(j=='d'||j=='k'||j=='q')){s+="*"
}else{s+="."}}
s+="\n"}
return}

Probably golfable quit a bit, i'm a begginner

Could you save 9 characters by renaming part to p?

Tips for golfing in Go. I took the liberty of applying them to your answer myself.

Did you notice that the comment "+1 for choice of language" has more upvotes than the post itself ? (it happens that comments have more upvotes, but for such a comment, that's rather unexpected)

Ruby, 130 128 121 + 3 (-n flag) = 124 bytes
Switched -p to -n because puts b is one byte shorter than $_=b*$/
~/(.)(.+)/
b=(1..19).map{?.*19}
(a=3,9,15).map{|i|a.map{|j|b[i][j]=?*}}
b[19-$2.to_i][([*?A..?T]-[?I]).index$1]=?o
puts b

Can you save bytes by checking if the index mod 6 is 3 instead of hardcoding 3, 9 and 15?

@FryAmTheEggman It might, but I've yet to figure out a solution that does so.

Python, 148 145 136 130 121 119 116 Bytes
-3 Bytes thanks to @RootTwo
lambda x,r=range(19):[[".*o"[[i%6==j%6==3,2][j==ord(x[0])-(x>"I")-65and-~i==int(x[1:])]]for j in r]for i in r[::-1]]

anonymous lambda function, takes input of the form "A1" (big letters) and outputs a list of lists of chars (len==1 strings in Python)

Save 8 bytes by using ".*oo"[2*(j==ord(x[0])-(x[0]>"I")-65and int(x[1:])==i+1)+(i%6==j%6==3)] instead of the "o"if...else"*"if...else"."

Also, I think you can use (x>'I') instead of (x[0]>'I') to save 3 more bytes.

@RootTwo Thanks, the first suggestion is no longer useful, since I've since found a even shorter solution. The second one now seems obvious and makes me question why i haven't thought of this earlier.

F#, 241 237 225 216 214 211 bytes
let G(c:string)=for k=1 to 380 do printf(if k%20=0 then"\n"elif"_ABCDEFGHJKLMNOPQRST".IndexOf c.[0]=k%20&&19-k/20=int(c.Substring 1)then"o"elif(k%20=4||k%20=10||k%20=16)&&(k/20=3||k/20=9||k/20=15)then"*"else".")

Tricky one this one ... I wonder if it can be made shorter.
Edit: fixed a bug, added numbers some places removed numbers in others, somehow ended up with the same count. Might try shuffling numbers around later  Done.
Edit2: saved more bytes by spelling out one of the conditionals, counter intuitively.
Edit3: Fixed another bug: should work now for pieces on the last rank and managed to save two bytes while I am at it, somehow.
Try it online

Oh that was the problem. Funny, it is the one thing I didn't look at twice

><>, 98 96 bytes
'_U'i-:b)-0\
+*a$%cv?(0:i<
{*+{4*\+
+4gf-o>1-:?!;:{:}=3*&::aa+%::0=2*&+&6%1-}-aa+,6%{*9=&
=9^^

Note that there is an 0x14 in the first row after the first ', and an 0x19 between the 9 and the first ^ of the last line. Try it online!
The input is mapped so that A-T become 1-19 (with 0 denoting an imaginary "newline" column) and the integer row number is decremented by 1. The program does a loop from 379 down to 0, choosing a char from the bottom row as it goes (offset by 15, to account for the fact that you can't enter a literal newline in the codebox). Newlines are checked via i % 20 == 0, and star points are checked by ((i%20-1)%6)*((i/20)%6) == 9.

Batch, 322 310 308 bytes
@echo off
set/pi=
set/aa=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,j=8,k=9,l=10,m=11,n=12,o=13,p=14,q=15,r=16,s=17,t=18,x=%i:~1%-1,y=%i:~,1%,z=y+1
for /l %%r in (18,-1,0)do call:l %%r
exit/b
:l
set s=...*.....*.....*...
call set t=%%s:~%1,1%%
if %x%==%1 call set s=%%s:~,%y%%%o%%s:~%z%%%
call echo %%s:.*=.%t%%%

Explanation: Starts by prompting for the stone on stdin. Then, sets variables for each possible column, so that it can evaluate the first character of the stone as a variable to get the y coordinate. Subtracts 1 from the x coordinate because it's 1-indexed and we want 0-indexed and also computes z=y+1 as it will need that later. Then, loops r from 18 down to 0 for each row. Takes the string ...*.....*.....*... and extracts the character at the rth position for later. On the xth row, the yth character is replaced with an o. Finally, the .*s are replaced with a . plus the previously extracted character; this is a no-op on rows 4, 10 and 16 but this is the shortest way to achieve that. (I have to use .* because replacing * is apparently illegal in Batch.)

Perl, 132 bytes
-3 bytes thanks to @Dom Hastings
@v=eval"[('.')x19],"x19;@{$v[$_]}[@t]=("*")x3for@t=(3,9,15);pop=~/\d+/;$v[19-$&][($t=ord$`)-65-($t>73)]=O;map{say}map{join"",@$_}@v;

Takes command line input. Needs -M5.010 tu run. For instance :
$ cat go_board.pl
@v=eval"[('.')x19],"x19;@{$v[$_]}[@t]=("*")x3for@t=(3,9,15);pop=~/\d+/;$v[19-$&][($t=ord$`)-65-($t>73)]=O;map{say}map{join"",@$_}@v;
$ perl -M5.010 go_board.pl Q16

I think this could be shorter, but I couldn't figure out how... please let me know if you do!

Nice use of more magic variables again! I haven't tested this properly but I think you can save a few more with @v=([(".")x18])x18; to initialise the list... There might even be a better way than that, but I'm not at a terminal right now! I think you can replace the @{...} expansion with dereferencing arrows too: $v[$_]->[@t] again untested though! Also I hope you don't mind me suggesting code changes...

@DomHastings Of course I don't mind, on the contrary, I'd rather encourage you to suggest improvements! @v=([(".")x19])x19 doesn't work (I tried it before btw), because it create only one arrayref and it copy 19 times the ref, not the array (so in the end you only have 1 line duplicated 19 times). Replacing @{..} as you suggested doesn't seem to work either. I'm guessing that's because I'm working on a slice and not only one element. If you have any other suggestion, feel free to suggest! :)

Damn, of course it'd be the same... I've managed to use eval for -3 though: @v=eval"[('*')x19],"x19;. And you're 100% correct with the arrayref... Is is maybe possible to use a 1D array and work out the index in that though? Might play with this more later!

@DomHastings Thanks for the -3 bytes. Maybe something to try with a 1D array, indeed. I'll try it soon

Retina, 134 129 122 bytes
11 bytes thanks to Martin Ender, and for inspiration of 1 more.
S2=`
[K-S]
1$&
T`xL`d9d
.+
$*
$
aaab
a
bbbcbb
b|c
¶$0
c
ddd.
d
...*..
b
19$*.
1(1)*¶1(1)*¶((?<-2>.+¶)*(?<-1>.)*).
$3O
O^$`

Try it online!

Hey, congrats on your gold badge!

PowerShell v2+, 157 152 bytes
$x,$y=[char[]]$args[0];$a=,0*19;0..18|%{$a[$_]=,'.'*19};3,9,15|%{$i=$_;3,9,15|%{$a[$_][$i]='*'}};$a[-join$y-1][$x-65-($x-gt73)]='O';$a[18..0]|%{-join$_}

(I think I ran into some sort of weird glitch with the comma-operator, so the array construction is a bit longer than it should be)
Takes input as an uppercase string via $args[0], casts it as a char-array, stores the first letter into $x and the remaining letters into $y. This effectively splits the input into letter/number.
We then construct our multidimensional array $a. We pre-populate an array of size 19 with 0s using the comma-operator. We then loop 0..18 to make each element $a[$_] equal instead an array of periods, again using the comma operator. (NB - In theory, this should be able to be condensed to $a=,(,'.'*19)*19, but that doesn't seem to work right with the indexing assignment ... I wound up getting whole columns set to *)
Next, we loop twice over 3,9,15 to set the corresponding elements to *. We then index into it in the right spot to set the stone O. To do so, we subtract 65 from $x (i.e, ASCII "A" is 65, and we're zero-indexed), and subtracts an additional one using a Boolean-to-int cast if $x is bigger than 73 (i.e., ASCII "I").
Now, our output is reversed (i.e., the upper-left would be A1), so we need to reverse the array with $a[18..0]. Finally, we output each line -joined together to form a string.

><>, 124 bytes
Uses the exact same approach as my C answer. Input must be a capital letter followed by a decimal number.
88*i:&-&'I')+0 v
*a&-'0'v!?)0:i&<+
+**2a&~/*a'&'&
:;!?:-1<o'O'v!?=&:&
{*?!v'*'o63.>:6%4=}:a4*+'x'%aa*)
*2a:/  av?%
.37o<'.'<

Try it online!
Explanation:
88*i:&-&'I')+0 v         'Push 64-<first input char>+(<first input char> > 'I')
*a&-'0'v!?)0:i&<+        'Set register to 0, parse decimal integer into register.
+**2a&~/*a'&'&           'Pop the -1 (EOF) from stack, multiply register by 20.
                         'Add result of first line to register.
                         'Push 380 onto stack.
:;!?:-1<o'O'v!?=&:&      'Main loop, while top of stack is not 0.
                         'Subtract 1 from top of stack (loop counter)
                         'If current index is the playing piece index, print 'O'
{*?!v'*'o63.>:6%4=}:a4*+'x'%aa*)
                         'If (index%6)=4 and (index+40)%120>100, print '*'
*2a:/  av?%              'If (index%20)=0, print newline
.37o<'.'<                'Otherwise, print '.'

JavaScript, 138 bytes
s=>[...t="...*.....*.....*..."].map((c,i)=>t.replace(/\*/g,c).replace(/./g,(c,j)=>x-j|19-i-s.slice(1)?c:'o'),x=parseInt(s[0],36)*.944-9|0)

Returns an array of strings. Explanation:
s=>[...                         Parameter
 t="...*.....*.....*..."        Pattern of lines 4, 10 and 16
].map((c,i)=>                   Loop 19 times
 t.replace(/\*/g,c)             Change the `*` to `.` on other lines
  .replace(/./g,(c,j)=>         Loop over each character
   x-j|19-i-s.slice(1)?c:'o'),  Change to o at the appropriate position
 x=parseInt(s[0],36)*.944-9|0)  Compute the column number from the letter

An array of strings is not matching the required output, just join. Also it places the o in the wrong row and the wrong column for D5 (first test case).

@tomdemuyt An array of strings is allowed as a return value. However, it's possible that I got my rows and columns mixed up, so I'll double-check.

Hmm, indeed array of strings

R, 169 161 bytes
f=function(p){S=substr;N=rep(".",114);N[61+6*0:2]="*";M=matrix(N,19,19);M[(S(p,2,3):1)[1],which(LETTERS[-9]==S(p,1,1))]="O";for(i in 19:1)cat(M[i,],"\n",sep="")}

With indents and newlines:
f=function(p){
    S=substr
    N=rep(".",114) # 6 lines of dots
    N[61+6*0:2]="*" # Place the hoshis
    M=matrix(N,19,19) # Make the 19x19 board using vector recycling
    M[(S(p,2,3):1)[1],  #grab and force coerce the row number to integer
      which(LETTERS[-9]==S(p,1,1))]="O" #Place the first stone
    for(i in 19:1) cat(M[i,],"\n",sep="")
}

Usage:
> f("A19")
O..................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................
> f("D4")
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...O.....*.....*...
...................
...................
...................
> f("K10")
...................
...................
...................
...*.....*.....*...
...................
...................
...................
...................
...................
...*.....O.....*...
...................
...................
...................
...................
...................
...*.....*.....*...
...................
...................
...................

Lua, 187 Bytes
function g(i)i:gsub("(%a+)(%d+)",function(a,b)q=string.byte(a)-64 r=b+0 end)for x=1,19 do s=""for y=1,19 do s=s..(x+y*19==r+q*19 and"o"or(x-4)%6+(y-4)%6==0 and"*"or"-")end print(s)end end

I don't feel too bad about 187 for this particular project. Lua still comes out as very clunky for Golfing, but I'm pretty proud of how far I can go with it.

PHP, 280 268 263 261 255 218 216 bytes
<?php $a=ucfirst($argv[1]);$x=substr($a,0,1);$y=substr($a,1);$s=['DKQ',4,16,10];$i=85;while(64<$i--){$j=0;while($j++<20){echo($x==chr($i)&&$y==$j)?'O':((strpos($s[0],chr($i))>-1&&in_array($j,$s))?'*':'.');}echo"\n";}

My first golf.
Usage:
Save as a PHP file and call it by php filename.php coordinate e.g. php go.php k13


text:
Keep nonzeros and their neighbours
Taken from this question at Stack Overflow. Thanks also to @miles and @Dada for suggesting test inputs that address some corner cases.
The challenge
Given an array of integer values, remove all zeros that are not flanked by some nonzero value.
Equivalently, an entry should be kept either if it's a nonzero or if it's a zero that is immediately close to a nonzero value.
The entries that are kept should maintain in the output the order they had in the input.
Example
Given
[2 0 4 -3 0 0 0 3 0 0 2 0 0]

the values that should be removed are marked with an x:
[2 0 4 -3 0 x 0 3 0 0 2 0 x]

and so the output should be
[2 0 4 -3 0 0 3 0 0 2 0]

Rules
The input array may be empty (and then the output should be empty too).
Input and output formats are flexible as usual: array, list, string, or anything that is reasonable.
Code golf, fewest best.
Test cases
[2 0 4 -3 0 0 0 3 0 0 2 0 0] -> [2 0 4 -3 0 0 3 0 0 2 0]
[] -> []
[1] -> [1]
[4 3 8 5 -6] -> [4 3 8 5 -6]
[4 3 8 0 5 -6] -> [4 3 8 0 5 -6]
[0] -> []
[0 0] -> []
[0 0 0 0] -> []
[0 0 0 8 0 1 0 0] -> [0 8 0 1 0]
[-5 0 5] -> [-5 0 5]
[50 0] -> [50 0]

Can I use _2 instead of -2? Quite a few languages use that format.

Will we have -0?

@LeakyNun 1 Yes 2 No

Will numbers ever have leading zeros? Like [010 0 0 01 1]?

@FryAmTheEggman Nope

A question: In java, arrays are immutable. If input is [0,3,5,0,2,0,0,0] can output be [0,3,5,0,2,0,null,null]?

@OldBunny2800 No, sorry. The output should contain only the selected numbers

@OldBunny2800 :-)

thinks how he can do this in java now

MATL, 8 bytes
tg3:Z+g)

Output is a string with numbers separated by spaces. An empty array at the output is displayed as nothing (not even a newline).
Try it online! Or verify all test cases.
Explanation
The code converts the input to logical type, i.e. nonzero entries become true (or 1) and zero entries become false (or 0). This is then convolved with the kernel [1 2 3]. A nonzero value causes a nonzero result at that position and at its neighbouring positions. Converting to logical gives true for values that should be kept, so indexing the input with that produces the desired output.
t    % Input array implicitly. Duplicate
g    % Convert to logical: nonzero becomes true, zero becomes false
3:   % Push array [1 2 3]
Z+   % Convolution, keeping size of first input
g    % Convert to logical
)    % Index into original array. Implicitly display

JavaScript (ES6), 35 bytes
a=>a.filter((e,i)=>e|a[i-1]|a[i+1])

Works on floats too for two extra bytes.

Python, 50 bytes
f=lambda l,*p:l and l[:any(l[:2]+p)]+f(l[1:],l[0])

A recursive function that takes a tuple. Includes the first element if there's a nonzero value among either the first two elements or the previous value stored from last time. Then, removes the first element and recurses. The previous element is stored in the singleton-list p, which automatically packs to  list and starts as empty (thanks to Dennis for 3 bytes with this).

55 bytes:
lambda l:[t[1]for t in zip([0]+l,l,l[1:]+[0])if any(t)]

Generates all length-3 chunks of the list, first putting zeroes on the start and end, and takes the middles elements of those that are not all zero.
An iterative approach turned out longer (58 bytes)
a=0;b,*l=input()
for x in l+[0]:a|b|x and print(b);a,b=b,x

This doesn't exactly work because b,*l needs Python 3, but Python 3 input gives a string. The initialization is also ugly. Maybe a similar recursive approach would work.
Unfortunately, the indexing method of
lambda l:[x for i,x in enumerate(l)if any(l[i-1:i+2])]

doesn't work because l[-1:2] interprets -1 as the end of the list, not a point before its start.

Haskell, 55 48 bytes
h x=[b|a:b:c:_<-scanr(:)[0]$0:x,any(/=0)[a,b,c]]

Usage example: h [0,0,0,8,0,1,0,0] -> [0,8,0,1,0].
scanr rebuilds the input list x with an additional 0 at the start and end. In each step we pattern match 3 elements and keep the middle one if there's at least one non-zero element.
Thanks @xnor for 7 bytes by switching from zip3 to scanr.

It would be nice to just do h x=[snd t|t<-zip3(0:x)x$tail x++[0],(0,0,0)/=t], but I guess there's no short way to actually get the second-element of a 3-tuple.

Turns out shorter to get the triples out of a scan than a zip3: h x=[b|a:b:c:_<-scanr(:)[0]$0:x,any(/=0)[a,b,c]].

Matlab, 29 27 bytes
The input must consist of a 1*n matrix (where n=0 is possible). (It will throw an error for 0*0 matrices.)
@(a)a(conv(a.*a,1:3,'s')>0)

Convolution is the key to success.

's' instead of 'same' <-- :-D

That trick does work a lot of times with builtins=)

I've seen that trick, even for non-golfing questions, with the flag 'UniformOutpout' (understandably). But I didn't know about this one

@LuisMendo I just noticed you ninja'd me with this approach :D

But not nearly as golfy :-)

Could you use ~~a instead of a.*a?

@feersum Matlab unfortunately refuses to convolve logical arrays. This often is a problem for built-ins that are not written in Matlab itself. Otherwise logical arrays behave a lot like numberish ones. It might work in Octave thought, but I do not have it installed at the moment.

J, 17 14 bytes
#~0<3+/\0,~0,|

Saved 3 bytes with help from @Zgarb.
Usage
   f =: #~0<3+/\0,~0,|
   f 2 0 4 _3 0 0 0 3 0 0 2 0 0
2 0 4 _3 0 0 3 0 0 2 0
   f ''

   f 0 0 0 8 0 1 0 0
0 8 0 1 0

Explanation
#~0<3+/\0,~0,|  Input: array A
             |  Get the absolute value of each in A
           0,   Prepend a 0
        0,~     Append a 0
    3  \        For each subarray of size 3, left to right
     +/           Reduce it using addition to find the sum
  0<            Test if each sum is greater than one
                (Converts positive values to one with zero remaining zero)
#~              Select the values from A using the previous as a mask and return

Try it here.

Would 0< work in place of 0~:?

@Zgarb The infixes of size 3 can be either positive or negative after processed.

Ah, I forgot about the negative values.

Python 3, 55 bytes
lambda s:[t[1]for t in zip([0]+s,s,s[1:]+[0])if any(t)]

Wow. I don't know if you saw @xnor answer before this, but you have the exact same code, with the only difference being the name of the lambda. If you did use his code, give him credit, if not, what a crazy coincidence!

Did not look at anyone's code.

@T.Lukin It's actually not uncommon to come up with the same code. You can see this happen on Anarchy Golf, where code is hidden until the deadline, and multiple people converge on the same solution like this one.

Jolf, 14 bytes
Now that I think of it, Jolf is the Java of golfing languages. sighs Try it here.
ψxd||H.nwS.nhS

Explanation
ψxd||H.nwS.nhS
ψxd             filter input over this function
   ||           or with three args
     H           the element
      .nwS       the previous element
          .nhS   or the next element

Jelly, 9 bytes
0,0jo3\Tị

Try it online! or verify all test cases.
How it works
0,0jo3\Tị  Main link. Argument: A (array)

0,0        Yield [0, 0].
   j       Join, separating with A. This prepends and appends a 0 to A.
    o3\    Reduce each group of three adjacent integers by logical OR.
       T   Truth; get the indices of all truthy results.
        ị  At-index; retrieve the elements of A at those indices.

Perl, 34 + 1 (-p flag) = 35 bytes
s/([^1-9]0 |^)\K0 ?(?=0|$)//&&redo

Needs -p flag to run. Takes a list of number as imput. For instance :

perl -pe 's/([^1-9]0 |^)\K0 ?(?=0|$)//&&redo' <<< "0 0 0 8 0 1 0 0
0 0 0
-5 0 5"

I get 5 if I input 50 0.

@feersum fixed, thanks

Haskell, 48 bytes
p%(h:t)=[h|any(/=0)$p:h:take 1t]++h%t
p%e=e
(0%)

Looks at the previous element p, the first element h, and the element after (if any), and if any are nonzero, prepends the first element h.
The condition any(/=0)$p:h:take 1t is lengthy, in particular the take 1t. I'll look for a way to shorten it, perhaps by pattern matching.

Retina, 42 35 33 bytes
7 bytes thanks to Martin Ender.

(?<=^|\b0 )0(?=$| 0)

 +

^ | $

The last line is necessary.
Verify all testcases at once. (Slightly modified to run all testcases at once.)
Looks like the perfect language to do this in... still got defeated by most of the answers.

I'd just ditch the brackets from the I/O format.

Mathematica, 43 bytes
ArrayFilter[If[#.#>0,#[[2]],Nothing]&,#,1]&

C, 96 bytes
Call f() with a pointer to the list of integers, and a pointer to the size of the list. The list and size are modified in-place.
i,t,e,m;f(int*p,int*n){int*s=p;for(i=m=e=0;i++<*n;s+=t=m+*s||i<*n&&p[1],e+=t,m=*p++)*s=*p;*n=e;}

Try it on ideone.

K&R parameter style is often shorter, but not here - f(int*p,int*n) saves a byte. Or define s as a 3rd parameter (that's not passed. it''s kind-of OK).

Brachylog, 44 38 bytes
,0gL:?:Lc:1fzbh.
~c[A:.:B],[0:0:0]'.l3

Try it online!
This language is good as proving things, which is what we will use.
Predicate 0 (main predicate)
,0gL:?:Lc:1fzbh.
 0gL               [0] = L    (assignment works both ways)
   L:?:Lc          [L:input:L] = temp
         :1f       find all solutions of predicate 1 with temp as input
            zbh.   then transpose and take the middle row and assign to output

Predicate 1 (auxiliary predicate)
~c[A:.:B],[0:0:0]'.l3
~c[A:.:B]                 input is in the form of [A:output:B]
         ,                and
          [0:0:0]'.       output is not [0:0:0]
                  .l3     and length of output is 3

Matlab with Image Processing Toolbox, 27 bytes
@(a)a(~imerode(~a,~~(1:3)))

This is an anonymous function.
Example use:
>> @(a)a(~imerode(~a,~~(1:3)))
ans =
    @(a)a(~imerode(~a,~~(1:3)))
>> ans([0 0 0 8 0 1 0 0])
ans =
     0     8     0     1     0

I thought of imerode too, but my versions kept being longer than my current one, nice work=)

Bash + GNU utils, 25
grep -vC1 ^0|grep -v \\-$

Accepts input as a newline-separated list.
Ideone - with test driver code added to run all testcases together by converting to/from space-separated and newline-separated.

Cheddar, 78 bytes
a->([[]]+a.map((e,i)->e|(i?a[i-1]:0)|(i-a.len+1?a[i+1]:0)?[e]:[])).reduce((+))

Test suite.
Cheddar has no filter, so filtering is done by wrapping the elements we want and transforming the elements we don't want into empty arrays, and then concatenate everything.
For example, [0,0,0,8,0,1,0,0] becomes [[],[],[0],[8],[0],[1],[0],[]], and then the concatenated array would be [0,8,0,1,0].

.reduce((+)) -> .sum

@Downgoat When did you fix that?

oh, sorry nevermind. I thought you were summing the array. not joining the arrays

APL, 14 bytes
{⍵/⍨×3∨/0,⍵,0}

Test:
      {⍵/⍨×3∨/0,⍵,0}2 0 4 ¯3 0 0 0 3 0 0 2 0 0
2 0 4 ¯3 0 0 3 0 0 2 0

Explanation:

0,⍵,0: add a zero to the beginning and the end of ⍵
×3∨/: find the sign of the GCD of every group of three adjacent numbers (this will be 0 if they are all zero and 1 otherwise).
⍵/⍨: select all the items from ⍵ for which the result was 1.

Brain-Flak 142 bytes
Try it online!
(<()>)(()){{}([]<([]){{}({}<>)<>({}<>)<>({}<>)<>(<>({}<>)<>({}<>)<>({})<>){{}((<()>))}{}{}([][()])}{}{}<>{}([]){{}({}<>)<>([])}{}<>>[[]])}{}{}

Explanation
(<()>)                    #Pad the top with an extra zero
(()){{}([]<...>[[]])}{}   #Until the stack height remains the same
 ([]){{}...([][()])}{}    #Until the stack height is one
  ({}<>)<>                #Move the top three to the other stack
  ({}<>)<>
  ({}<>)<>
  (...)                   #Push the sum of the top three
   <>({}<>)               #Move the second and third back
   <>({}<>)
   <>({})<>               #Leave the top of the stack
  {{}...}{}               #If the sum is not zero
   ((<()>))               #Add a buffer to the top of the stack
  {}                      #Pop the buffer/middle value
 {}                       #Remove extra zero
 <>                       #Switch to the off stack
 {}                       #Remove extra zero
 ([]){{}({}<>)<>([])}{}<> #Move the entire off stack back

The link is empty. You can paste code and input, press "save" and use the resulting link

@LuisMendo Unfortunately I cannot use tryitonline so I just linked to the url.

Why can't you access tryitonline?

@DJMcMayhem I did not have javascript in my browser. I will fix it now. I see you have already done that thank you.

Ruby 2.x, 63 bytes
f=->(x){x.select.with_index{|y,i|x[i-1].to_i|y|x[i+1].to_i!=0}}

Credit where it is due, this is essentially a port of Neil's superior ES6 answer.
It's also my first pcg submission. yay.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Fraction to exact decimal
Write a program or function that given two integers a, b outputs a string containing a decimal number representing the fraction a/b exactly.
If a/b is integer, simply output the value, without a decimal dot or leading zeroes:
123562375921304812375087183597 / 2777 -> 44494913907563850333124661
81 / 3 -> 27
-6 / 2 -> -3

If a/b is not integer but has a finite representation in base 10, output the value without leading or trailing zeroes (except a single zero before the dot):
1 / 2 -> 0.5
3289323463 / -250000000 -> -13.157293852

Finally, if and only if (so no 0.999...) a/b is not integer and does not have a finite representation, output the finite part followed by the repeating part in parenthesis. The repeating part must be as small as possible, and start as early as possible.
-1 / 3 -> -0.(3)
235 / 14 -> 16.7(857142)
123 / 321 -> 0.(38317757009345794392523364485981308411214953271028037)
355 / 113 -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)

Your program must work for all above examples in under 10 seconds on a modern desktop PC. Smallest program in bytes wins.

@DestructibleWatermelon This is possible in pretty much all languages, including Turing tarpits. (Those might struggle with the time limit though.)

@DestructibleWatermelon I was under the impression that most languages are turing complete.

Can we safely assume the fraction won't be something like: 0.33333333333336333...?

@brianush1 Of course not. There is only one exact answer for a fraction, and your answer must correctly determine that one answer.

Is this possible on real tangible computers (limited memory)?

This seems like a long-winded way of asking for solutions to PE26 ;)

@ConorO'Brien The general case is a tad more complicated than the reciprocal case. To emphasize, there was one incorrect example in my initial post due to this, and I still haven't found the bug in my test program...

@DestructibleWatermelon It is possible with limited memory. You would only need memory up to the point where the decimal starts repeating. So assuming you do the worst and store a binary digit per byte, you'd still only use max 1KB

Can b be negative? (Edit: Never mind, just saw the test case where it is)

Generalisation of this question; also related.

Is the input format literally a pair of integers, or is it already in the form "a / b" with the "/" included?

@GregMartin Whatever you prefer.

Also very similar to this: http://codegolf.stackexchange.com/questions/22146/implement-arbitrary-precision-division

I recall this exact question from USACO's site (same output format as well)

Perl 6,  63 58  50 bytes
{->$a,$b {$a~"($b)"x?$b}(|($^a.FatRat/$^b).base-repeating(10))}

{->\a,$b {a~"($b)"x?$b}(|($^a.FatRat/$^b).base-repeating)}

{$/=($^a.FatRat/$^b).base-repeating;$0~"($1)"x?$1}

Test it
If you don't care that it will only work with denominators that fit into a 64 bit integer it can be shortened to just 43 bytes:
{$/=($^a/$^b).base-repeating;$0~"($1)"x?$1}

Expanded:
{
  # store in match variable so that we can
  # use ｢$0｣ and ｢$1｣
  $/ = (

    # turn the first value into a FatRat so that
    # it will continue to work for all Int inputs
    $^a.FatRat / $^b

  ).base-repeating;

  # ｢$0｣ is short for ｢$/[0]｣ which is the non-repeating part
  $0

  # string concatenated with
  ~

  # string repeat once if $1 is truthy (the repeating part)
  # otherwise it will be an empty Str
  "($1)" x ?$1
}

The way you formatted your answer is confusing. You should remove your old programs, because right now it looks like a multi-line program.

@mbomb007 The main reason I have for posting golfs is for marketing, and education of Perl 6. So I leave old versions in to show more of the language. That's also why I rarely post one until I have some sort of explanation in there. I have altered it so that the different examples are in different code blocks.

Old versions are always visible in the post's edit history.

@mbomb007 Not if I wait to post until after trying several different ways to write it.

Then just edit one in every 5 minutes.

Python 2, 174 bytes
x,y=input()
a=abs(x)
b=abs(y)
r=a%b*10
L=[]
M=''
while~-(r in L):L+=r,;M+=str(r/b);r=r%b*10
i=L.index(r)
t=M[:i]+"(%s)"%M[i:]*(M[i:]>'0')
print"-%d."[x*y>=0:(t>'')+3]%(a/b)+t

I'm not quite convinced about the validity of this answer, but it's worked for the test cases above and other test cases I've thrown at it. It looks like a right mess though, so I'm sure there's plenty of room for golfing.
The initial setup takes absolute values of both arguments to ensure that we're dealing with nonnegative numbers (saving the sign calculation for later), and delegates the quotient part of the result to Python's arbitrary precision arithmetic. The fractional part is done with the grade-school division algorithm until we get a repeat in the remainder. We then look up when we last saw this repeat in order to get the period, and construct the string accordingly.
Note that the algorithm's actually quite slow due to the O(n) in operation, but it's fast enough for the examples.

Batch, 349 344 bytes
@echo off
set/ad=%2,i=%1/d,r=%1%%d
if not %r%==0 set i=%i%.&if %r% leq 0 set/ar=-r&if %i%==0 set i=-0.
set d=%d:-=%
set/ae=d
:g
if %r%==0 echo %i%&exit/b
set/ag=-~!(e%%2)*(!(e%%5)*4+1)
if not %g%==1 set/ae/=g&call:d&goto g
set/as=r
set i=%i%(
:r
call:d
if %r%==%s% echo %i%)&exit/b
goto r
:d
set/ar*=10,n=r/d,r%%=d
set i=%i%%n%

Edit: Saved 5 bytes by removing unnecessary characters. "Ungolfed":
@echo off
set /a d = %2
set /a i = %1 / d
set /a r = %1 % d
if not %r%==0 (
    set i=%i%.                  Decimal point is required
    if %r% leq 0 (
        set /a r = -r           Get absolute value of remainder
        if %i%==0 set i=-0.     Fix edge case (-1/3 = 0 remainder -1)
    )
)
set d = %d:-=%                  Get absolute value of divisor
set /a e = d
:g
if %r%==0 echo %i% & exit /b    Finished if there's no remainder
set /a g = gcd(e, 10)           Loop through nonrecurring decimals
if not %g%==1 (
    set /a e /= g
    call :d
    goto g
)
set /a s = r                    Save remainder to know when loop ends
set i=%i%(
:r
call :d
if %r%==%s% echo %i%)&exit/b
goto r
:d                              Add the next decimal place
set /a r *= 10
set /a n = r / d
set /a r %= d
set i=%i%%n%

I have no idea how any of this works, but I commend you for doing it in batch lmao

I'm impressed with the capabilities of set /a.

Java, 625 605
Golfed code:
import static java.math.BigInteger.*;
String f(BigInteger a, BigInteger b){BigInteger[]r=a.divideAndRemainder(b);String s=r[0].toString();if(r[1].signum()<0)s="-"+s;if(!ZERO.equals(r[1])){s+='.';List<BigInteger>x=new ArrayList();List<BigInteger>y=new ArrayList();for(BigInteger d=TEN.multiply(r[1].abs());;){BigInteger[]z=d.divideAndRemainder(b.abs());int i=y.indexOf(z[1]);if(i>-1&&i==x.indexOf(z[0])){for(int j=0;j<i;++j)s+=x.get(j);s+='(';for(int j=i;j<x.size();++j)s+=x.get(j);s+=')';break;}x.add(z[0]);y.add(z[1]);if(ZERO.equals(z[1])){for(BigInteger j:x)s+=j;break;}d=TEN.multiply(z[1]);}}return s;}

Note: I count the static import as part of the function for golfing purposes.
This function starts out by getting the division result. It adds the integral portion and sign, if necessary. Then if there is a remainder, it performs base 10 long division. At each step, perform the division. Store the calculated digit and the remainder in two lists. If we encounter the same digit and remainder again, there is a repeated portion and we know what index it starts at. The code either adds the digits (no repeat) or the pre-repeat digits, then the repeated digits enclosed in parentheses.
This is a bit big mostly because of BigInteger. If the inputs did not overflow even a long then it could be a bit shorter. Still, I expect there are ways to improve this entry.
Ungolfed code with main method for testing:
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import static java.math.BigInteger.*;

public class FractionToExactDecimal {

  public static void main(String[] args) {
    // @formatter:off
    String[][] testData = new String[][] {
      { "123562375921304812375087183597", "2777", "44494913907563850333124661" },
      { "81", "3", "27" },
      { "-6", "2", "-3" },
      { "1", "2", "0.5" },
      { "3289323463", "-250000000", "-13.157293852" },
      { "-1", "3", "-0.(3)" },
      { "235", "14", "16.7(857142)" },
      { "123", "321", "0.(38317757009345794392523364485981308411214953271028037)" },
      { "355", "113", "3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)" }
    };
    // @formatter:on

    for (String[] data : testData) {
      System.out.println(data[0] + " / " + data[1]);
      System.out.println("  Expected -> " + data[2]);
      System.out.print("    Actual -> ");
      System.out.println(new FractionToExactDecimal().f(new BigInteger(data[0]), new BigInteger(data[1])));
      System.out.println();
    }
  }

  // Begin golf
  String f(BigInteger a, BigInteger b) {
    BigInteger[] r = a.divideAndRemainder(b);
    String s = r[0].toString();
    if (r[1].signum() < 0) s = "-" + s;
    if (!ZERO.equals(r[1])) {
      s += '.';
      List<BigInteger> x = new ArrayList();
      List<BigInteger> y = new ArrayList();
      for (BigInteger d = TEN.multiply(r[1].abs());;) {
        BigInteger[] z = d.divideAndRemainder(b.abs());
        int i = y.indexOf(z[1]);
        if (i > -1 && i == x.indexOf(z[0])) {
          for (int j = 0; j < i; ++j)
            s += x.get(j);
          s += '(';
          for (int j = i; j < x.size(); ++j)
            s += x.get(j);
          s += ')';
          break;
        }
        x.add(z[0]);
        y.add(z[1]);
        if (ZERO.equals(z[1])) {
          for (BigInteger j : x)
            s += j;
          break;
        }
        d = TEN.multiply(z[1]);
      }
    }
    return s;
  }
  // End golf
}

Program output:
123562375921304812375087183597 / 2777
  Expected -> 44494913907563850333124661
    Actual -> 44494913907563850333124661

81 / 3
  Expected -> 27
    Actual -> 27

-6 / 2
  Expected -> -3
    Actual -> -3

1 / 2
  Expected -> 0.5
    Actual -> 0.5

3289323463 / -250000000
  Expected -> -13.157293852
    Actual -> -13.157293852

-1 / 3
  Expected -> -0.(3)
    Actual -> -0.(3)

235 / 14
  Expected -> 16.7(857142)
    Actual -> 16.7(857142)

123 / 321
  Expected -> 0.(38317757009345794392523364485981308411214953271028037)
    Actual -> 0.(38317757009345794392523364485981308411214953271028037)

355 / 113
  Expected -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)
    Actual -> 3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)

Nice! I think you can save a few bytes by making this a function that returns a string, and by removing that one space in a, BigInteger. I also think you could alias BigInteger.TEN and BigInteger.ZERO.

@FryAmTheEggman thanks, I didn't realize the static import saved space over the more verbose references. It does. I also found a few other things I had missed, such as while (true) -> for (;;) which also allowed me to put stuff in the for initializer, saving another byte.

First, how about extending BigInteger? Second, a repeated remainder is enough to show it repeats; if you limit the input to int you can use an int[] with the remainder as index and the index as value, if that makes sense.

@JollyJoker extending BigInteger would require writing a whole class to try to save space, and I seriously doubt the tradeoff would work. Plus, I cannot restrict input. Anyway, there are eight instances of the text BigInteger in my code, and I don't see how adding more code to shrink them to a single character class name will pay off. And certainly adding code to deal with int[] (which BigInteger already does internally) will only bloat my answer.

@JollyJoker it is also worth mentioning that unless I override every BigInteger method I call to return an instance of the subclass, I will need to add several casts which further bloat the code. On top of the wasted bytes for a subclass's overhead, that would certainly increase the code size.

Yeah, I didn't think of the casts. Where in the question does it say the input can be arbitrarily long though? Wouldn't a method taking two ints and returning a String be a valid answer?

@JollyJoker integer length is unspecified, but consider "Your program must work for all above examples" and "123562375921304812375087183597". That number is 97 bits, which overflows all integer primitives in Java. Therefore, a Java program must use BigInteger or an equivalent class to handle those numbers. Since BigInteger is built into the JFC, it requires no extra code in a golf program. I will stick with that for golfing.

I'll try to find a spot on ...sunday? when I have more than 5 mins free in front of a computer to write down a solution :)

Does BigInteger a, BigInteger b=>BigInteger a,BigInteger b work?

@Zacharý yes, that works. However, short of some other trick to reduce byte count substantially, it is not worth changing it.

You can golf it to 555 bytes: import java.math.*;import java.util.*;String f(BigInteger a,BigInteger b){BigInteger r[]=a.divideAndRemainder(b),d,z[];String s=r[0]+"";if(r[1].signum()<0)s="-"+s;if(!a.ZERO.equals(r[1])){s+='.';List<BigInteger>x=new Stack(),y=new Stack();for(d=a.TEN.multiply(r[1].abs());;){z=d.divideAndRemainder(b.abs());int i=y.indexOf(z[1]),j;if(i>-1&i==x.indexOf(z[0])){for(j=0;j<i;)s+=x.get(j++);s+='(';for(j=i;j<x.size();)s+=x.get(j++);s+=')';break;}x.add(z[0]);y.add(z[1]);if(a.ZERO.equals(z[1])){for(BigInteger k:x)s+=k;break;}d=a.TEN.multiply(z[1]);}}return s;}.

Try it here. It does seem to fail for some tests that aren't part of the test cases, like 1/6 (expected 0.1(6)) or 1/7 (expected 0.(142857)). Not sure why, though..

PHP, 277 Bytes
list(,$n,$d)=$argv;$a[]=$n;$n-=$d*$r[]=$n/$d^0;!$n?:$r[]=".";while($n&&!$t){$n*=10;$n-=$d*$r[]=$n/$d^0;$t=in_array($n%=$d,$a);$a[]=$n;}if($t){$l=count($a)-($p=array_search(end($a),$a));echo join(array_slice($r,0,2+$p))."(".join(array_slice($r,2+$p,$l)).")";}else echo join($r);

Mathematica 198 bytes
i=Integer;t=ToString;a_~h~b_:=f[a/b];f@q_i:= t@q;
f@q_:=""<>{t@IntegerPart[q],".",RealDigits[FractionalPart[q]][[1]]//.{{x___,{k__i}}:> {x,"("<>(t/@{k})<>")"},{x__i,j___String}:>""<> {""<>t/@{x},j}}}

UnGolfed
(* hand over quotient of a, b to function f *)
h[a_, b_] := f[a/b];

(* if the quotient is an integer, return it as a string *)
f[q_Integer] := ToString@q;

(* otherwise, return the integer part, followed by a decimal point ...*)
f[q_] := "" <> {ToString@IntegerPart[q], ".",

   (* replacing the repeating part (if it exists) between parentheses *)
   RealDigits[FractionalPart[q]][[1]] //. {{x___, {i__Integer}} :> {x, "(" <>(ToString /@ {i}) <> ")"},

   (* and the non-repeating part (if it exists) without parentheses *)
   {x__Integer, i___String} :> "" <> {"" <> ToString /@ {x}, i}}}

Tests
h @@@ {{81, 3}, {-81, 3}, {1, 4}, {-13, 3}, {19, 7}, {3289323463, 25000}, {235, 14}, {1325, 14}}

{"27", "-27", "0.25", "-4.(3)", "2.(714285)", "131572.93852",
"16.7(857142)", "94.6(428571)"}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Tips for golfing in Common Lisp
What general tips do you have for golfing in Common Lisp? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Common Lisp (e.g. "remove comments" is not an answer).
Please post one tip per answer.

Narrower version of Tips for golfing in Lisp.

@zyabin101 right. I thought that since original topic didn't have too many answers, and Lisp itself is a huge family, I might as well ask for a specific language.

Use ' (quote) as synonym for "" for single words.
Quote stops evaluation of symbol, allowing you to e.g. print it. Note that the casing is dependant on *print-case* variable (most of the time it's in the upcase).
(print"yes")
(print'yes) ; saved a byte!

Use the best looping construct for the job
Use looping constructs that are as short as possible - loop for is rarely the way to go:

(dotimes(i <number>)) to loop a certain number of times
(mapcan lambda list) to map a list
(mapcar lambda list) to map and flatten a list
(do((var1 initialvalue1 nextvalue1)(var2 initialvalue2 nextvalue2)...)((endcondition)returnvalue)) for more complex loops
(map'string body list) to map string -> string
(map nil body list) to iterate over a list

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Be respectful in the restroom
Of course, the SE network is very knowledgeable about how to be respectful in the restroom, but for those of you who need a recap, being respectful means flushing the toilet, etc. Most importantly, though, it means using the stall as far away from others as possible.
The challenge
Given a blueprint of a set of stalls with indications of which ones are in use as a string, you must return or print from a function or program where the most respectful place to do your business is.
The input
 0 1 2 3 4 5    <- The stall number which is not actually visible in the input.
| | |-| |-|-|   <- the stalls

The stalls are numbered in ascending order from left to right. There will always be at least one empty stall. There can be up to 50 stalls in an input. You can also take the input as an array or string of 0s and 1s or booleans if you prefer to do so.
Stalls in use have - in them (in between the pipes).
The output
The most respectful stall to go to is the one that is on average farthest away from the ones in use. The distance between two stalls is the absolute value of the difference of the numbers above them.
Just to be clear: you are finding the average distance from all of the stalls—not just the neighboring ones.
You must output the lowest number of the most respectful stall to go to that is empty.
Examples
Input:
|-| |-| OR 101
Output:
1

Input:
| | |-| |-|-| OR 001011
Output:
0

Input:
|-| |-| | | | |-|-| OR 101000011
Output:
1

Input:
|-| | | | | |-|-| | | | | OR 100000110000
Output:
11

Input:
|-|-|-|-| | | | | | |-| OR 11110000001
Output:
9

Input:
|-| | OR 10
Output:
1

Input:
|-| | |-| OR 1001
Output:
1

This is code-golf, so shortest code in bytes wins!
You can use 0 or 1 based indexing in your answer — whichever you prefer; if you use 1 based indexing, then you must say so explicitly in your answer.

Related, but not a dupe

"Of course, the SE network is very knowledgeable about how to be respectful in the restroom" [citation needed]

Are ties broken to the left or to the right? Specifically, does 1001 return 1 or 2?

@AlexA.: Have a look at the toilet questions and answers on travel.stackexchange to assess the level of education of the SE network (or to educate yourself).

Can the numbers in the input by separated with spaces? (0 1 0 1 0 0 for instance)

But everyone knows that the respectfulness criterion is to maximize the minimun distance, not the average :-)

@Dada, I suppose so

I'm getting these results. Am I misunderstanding something?

@Dennis Are you maximizing the average distance? My first hunch was to maximize the minimum

@LuisMendo Yeah, that was indeed the problem. Thanks!

@Dopapp You should add [1,0,0,1] as a test case. None of the current test cases verifies if ties are broken correctly.

Why does 101000011 return 1 (instead of 4 or 5)?

@AmaniKilumanga, doing it on paper, 1 is correct. Are you calculating the maximum average distance or the maximum distance period?

Just a short note while browsing over random stackexchange questions, the average distance is indeed a strange criterion. The solution will always be either the first or the last free spot. (If there are more used stalls on my right than on the left, then moving left will always increase the distance and vice versa, with the minimum distance being somewhere in the middle) I'm no real code golfer, but maybe someone could use this for a shorter solution.

@Dopapp The expected output is the lowest stall number that is most respectful.  In the case of 101000011, outputting 1 would be the LEAST respectful stall, with an average distance of 1, whereas 4 and 5 both have an average distance of 2.5, and the lower of the two is 4, so 4 is the expected output.

@ewok, no. It is the average distance from all of the stalls--not just the neighboring ones.

@Dopapp Ok then. That's not really clear from the question. I'd recommend clarifying it.

@ewok, I have edited the question to be clearer

Being respectful in restrooms nowadays bring in complicated issues of gender identity.

Jelly, 10 9 bytes
JạþTS×¬MḢ

Uses 1-based indexing. Try it online! or verify all test cases.
How it works
JạþTS×¬MḢ  Main link. Argument: A (array of Booleans)

J          Yield all indices of A.
   T       Yield all truthy indices of A.
 ạþ        Compute the table of absolute differences.
    S      Compute the sums of all columns.
           For each index, this yields the sum of all distances to occupied stalls.
     ×¬    Multiply each sum by the logical NOT of the corresponding Boolean in A.
           This zeroes sums that correspond to occupied stalls.
       M   Maximal; yield an array of all indices of maximal sums.
        Ḣ  Head; extract the first index.

I believe that's 9 characters, not 9 bytes.

Jelly uses a custom code page that encodes the only characters it understands as a single byte each. The bytes link in the header points to it.

I was unaware of this... thanks for pointing it out.

@Dennis Did you make an auto-comment userscript so you can just click on "Jelly bytes comment" and it will post it?

@NoOneIsHere I do have that userscript (not mine), but I didn't add this one yet. I probably should though...

Swift, 158, 157, 128, 100 Bytes
Takes input from the Array<Bool> variable i, returns answer from the last expression.
let e=i.characters.map{$0>"0"}.enumerate()
e.flatMap{$1 ?nil:$0}.map{a in(a,e.flatMap{$1 ?$0:nil}.map{abs(a-$0)}.reduce(0){$0+$1})}.maxElement{$0.1 < $1.1}!.0

Edit 1:
Saved a byte by converting to bools via string comparison
let e=i.characters.map{$0=="1"}.enumerate()
e.flatMap{$1 ?nil:$0}.map{a in(a,e.flatMap{$1 ?$0:nil}.map{abs(a-$0)}.reduce(0){$0+$1})}.maxElement{$0.1 < $1.1}!.0

Edit 2:
Reworked my algorithm:
let e=i.characters.map{$0=="1"}.enumerate()
e.map{x in(x.0,x.1 ?0:e.reduce(0){$1.1 ?$0+abs(x.0-$1.0):$0})}.max{$0.1<$1.1}!.0

Edit 3:
Took advantage of new rule that allows taking input directly from a boolean array.
let e=i.enumerated()
e.map{x in(x.0,x.1 ?0:e.reduce(0){$1.1 ?$0+abs(x.0-$1.0):$0})}.max{$0.1<$1.1}!.0

Ungolfed:
// for the sake of easier copy/pasting of input, take it as string
let s = "100000110000"

// convert input to true for taken, false for free
// this is the input the golfed version actually uses
let input = s.characters.map{$0>"0"}

// Returns an array of tuples storing the array values (vacancy of the stall) and their index (their location)
let valueIndexPairs = bools.enumerated()

// Returns an array of pairs of locations and their avg distance to others
let locationDistancePairs = valueIndexPairs.map{(valueIndexPair: (Int, Bool)) -> (Int, Int) in

    let averageDistance = valueIndexPairs.reduce(0) {partialSum, otherStall in

        let otherStallIsTaken = otherStall.1

        if otherStallIsTaken {
            //don't let other stalls effect average if they're taken
            return partialSum
        }
        else {
            let thisStallLocation = valueIndexPair.0
            let otherStallLocation = otherStall.0
            let distanceToOtherStall = abs(thisStallLocation - otherStallLocation)
            return partialSum + distanceToOtherStall
        }
    }

    //if this stall is taken, treat its average distance to others as 0
    let thisStallsLocation = valueIndexPair.0
    let isThisStallTaken = valueIndexPair.1
    return (thisStallsLocation, isThisStallTaken ? 0 : averageDistance)
}

//find location where average distance is maxiumum
let bestLocationIndexPair = locationDistancePairs.max{$0.1 < $1.1}!

let bestLocation = bestLocationIndexPair.0

print(bestLocation)
```

I like swift answers

It's fun to learn :) Although it tends to be a pretty painful language for golfing. The standard library is truly minimal (you're intended to use Foundation most of the time), the language is meant to be very expressive, and it's statically typed. The closure syntax is REALLY good though

I should probably explain how this code works lol

@downrep_nation I added the ungolfed verison, in case you're interested

Perhaps save 3 bytes by removing "let" idk if you do need it or not, but from what I understand you do not need "let" which only serves as an indicator of a constant value

@RohanJhunjhunwala Unfortunately (for the sake of golfing, but fortunately for the sake of production code), Swift requires constants be declared with let, and variables with var. Either way it's a 4 byte hit

@ErikE From the question: "You can also take the input as am array of string of 0s and 1s or booleans if you prefer to do so."

Jelly, 13 bytes
1-indexed.
³Tạ⁸S
JUÇÞḟTṪ

Try it online!
Algorithm
Naive implementation of the question.

lol around 16 times shorter than my answer + 1! (1!==1)

@RohanJhunjhunwala What did you say?

Essentially Java can never compete with Jelly Seeing answers that are 12 bytes long (shorter than any possible java program)  is hilarious. So have an upgoat..

@LeakyNun lol missed the golf :D

1001 outputs 3 when it should return 2

I give up. This is hard.

Java "only" 270 200 196 187 196 138 148 146 bytes!
saved  4 13 countless bytes thanks to Leaky Nun! 1 byte thanks to Micheal
Golfed
int m(boolean[]b){int r=0,l=b.length,i,j,k=0,z=r;for(i=0;i<l;i++){if(b[i])for(j=0,k=0;j<l;j++)if(!b[j])k+=i>j?i-j:j-i;if(k>z){r=i;z=k;}}return r;}

Ungolfed
int m(int[] s) {
        int l=s.length,i,j=0,k=0;
    boolean[] b = new boolean[l];
    int[] a = new int[l];
    //see what stalls are open
    for (i = 0; i < s.length; i++) {
        if (s[i] == 0){
            b[i] = true;
        }
    }
    //assign the sum of distance to the a[]
    for (i = 0; i < l; i++) {
        if (b[i]) {
            for (j = 0; j < l; j++) {
                if (!b[j]) {
                    a[i]+= Math.abs(i - j);
                }
            }
        }
    }
    //find the stall the greatest distance away breaking ties based on the furthest left
    for (i = 0; i < l; i++) {
        if (b[i] && (a[i] > k || k == 0)) {
            k = a[i];
            j=i;
        }
    }
    //return the index
    return j;
}

input as an boolean array where true implies an open stall.

Comments are not for extended discussion; this conversation has been moved to chat.

You don't need the array a.

@LeakyNun how do I remove it?

By finding the minimum in one iteration (combine the outer for loops)

oh @LeakyNun will do when I get back today

forgot, but will do tomorrow, @LeakyNun (please do ping me if I forget so I do remember)

You can save a few bytes by changing the loops. for (j = 0; j < l; j++) to for (j = 0; j < l;) and then if (!b[++j])

@MichaelDibbets do u mean !b[j++]

mmh, just occurred, you need 0 index, so at the last occurrence/use of j, in loop you do j++ so the next iteration has it incremented. j = 0, i = ++j then i = 1. j = 0, i = j++ then i = 0

@MichaelDibbets take a look at how I have it now, for the first loop, is that good?

no, that doesn't compile. I'm looking at a way to reconstruct your code that it runs more smooth :-), one sec

@MichaelDibbets compiles for me,

Let us continue this discussion in chat.

You forgot the return statement.

@LeakyNun fixed :D I had it in my IDE just didn't pased all of it.

You don't need to initialize j and k in the beginning.

fixed @LeakyNun

k does need to be initialized

Ruby, 79 78 76 + n flag = 77 bytes
Output is 0-based indexing. Input is STDIN line of 0's and 1's.
p (r=0...~/$/).max_by{|i|k=0;$_[i]>?0?0:r.map{|j|k+=$_[j]<?1?0:(j-i).abs};k}

0...~/$/ is a nice trick.

Perl 84 + 3 (-alp flags) = 87 bytes
for$i(0..$#F){$t=0;map{$t+=abs($i-$_)*$F[$_]}0..$#F;($m,$_)=($t,$i)if$m<$t&&!$F[$i]}

Needs -alp flags to run. Takes a string of 1 and 0 separated by spaces as input. For instance :
perl -alpe '$m=0;for$i(0..$#F){$t=0;map{$t+=abs($i-$_)*$F[$_]}0..$#F;($m,$_)=($t,$i)if$m<$t&&!$F[$i]}' <<< "1 0 1
0 0 1 0 1 1
1 0 1 0 0 0 0 1 1
1 0 0 0 0 0 1 1 0 0 0 0
1 1 1 1 0 0 0 0 0 0 1
1 0"

Note that I added $m=0 at the begining, but that's only to test it on multiple entries.

I count +7: F'' alp. -s aren't counted.

@NoOneIsHere Hum, indeed, that would be my bad. Thanks

MATL, 14 bytes
~ftGf!-|Xs&X>)

Try it online!
Output is 1-based.
Explanation
~f     % Implicitly take input. Compute row vector with indices of zeros
t      % Duplicate that
Gf!    % Push input again. Compute column vector of indices of ones
-|     % Absolute differences with broadcast. Gives 2D array with all combinations
Xs     % Sum of each column
&X>    % Arg max. Gives the index of the first maximizer if there are several
)      % Index into row vector of indices of zeros. Implictly display

JavaScript (ES6), 87 86 82 75 bytes
a=>a.map((u,i)=>u||(a.map((v,j)=>u+=v*(i>j?i-j:j-i)),u>x&&(x=d,r=i)),x=0)|r

Takes a boolean array (true/false or 1/0). No point calculating the average distance since they're all using the same common factor, so just calculating the total distance for each stall and finding the first index of the highest one. Edit: Saved 1 byte by using * instead of &&. Saved 5 bytes by finding the highest distance manually based on a comment by @Dendrobium. Saved 7 bytes by reusing u as the pseudo-reduce accumulator based on a comment by @edc65.

79 bytes: a=>(x=0,a.map((o,i)=>x<(t=a.reduce((r,u,j)=>r+(b=i-j)*b*u*!o,0))&&(x=t,r=i)),r)

@Dendrobium The question asks for absolute distance; you seem to be calculating RMS distance.

Using an array as input - good idea. Calculating total instead of average - good idea. Using reduce instead of map - mmmm

75: s=>s.map((u,i)=>u||(s.map((w,j)=>u-=w*Math.abs(j-i)),u<x&&(x=u,r=i)),x=0)|r

@Neil Not quite RMS, just squared distances, which shouldn't effect the outcome of the solution unless there are ties in total distances of nonsymmetric inputs (for example 1100011101 ties at 2 and 8 when using absolute, 8 when using squared), not that it matters since it seems that the rules have been clarified and ties are now resolved with the left-most stall...

@Dendrobium By my calculations, when given an input of 1,0,1,1,1,1,0,0,0,1,1, squaring picks the leftmost zero but absolute value picks the rightmost zero.

@edc65 reduce made more sense in a previous version of the code; I admit it makes less sense now, particularly with your ingenious reuse of u.

Matlab, 87 bytes
n=input('');k=numel(n);[a b]=ndgrid(1:k);[x y]=max(sum(abs(a-b).*repmat(n,k,1)').*~n);y

Takes array of ones and zeros; uses 1-based indexing.
Like some other answers maximises total not average distance.
Probably there's some more golfing possible...

Ruby, 87 76 bytes
Threw this first draft quickly together, but in the meantime Value Ink had already posted an 80 byte Ruby answer...
edit: took off some bytes with help from Value Ink:
->a{(r=0...a.size).max_by{|i|a[i]?0:r.map{|j|a[j]?(i-j).abs: 0}.reduce(:+)}}

It's an anonymous function that takes an array of truthy/falsy values, like for instance so:
f=->->a{(r=0...a.size).max_by{|i|a[i]?0:r.map{|j|a[j]?(i-j).abs: 0}.reduce(:+)}}
# Test case number 5:
p f[[1, 1, 1, 1, nil, nil, nil, nil, nil, nil, 1]] # => 9

Assign the initial range to a variable (r=0...a.size) and then map on that instead of using with_index: r.map{|j|a[j]?(i-j).abs: 0}. This should get you 78 bytes.

@ValueInk Awesome, thanks! With only the function, no assignment, I get 76 bytes

J, 27 bytes
(#{:@-.~]/:[:+/]|@-/~#)i.@#

Online interpreter.

Mathematica, 53 bytes
MaximalBy[a=PositionIndex@#;a@0,Tr@Abs[#-a@1]&][[1]]&

Uses 1-based indexing and takes input as a list of 0s and 1s.

Javascript ES6 - 98 95 91 86 84 88 bytes
Edit: Seems that the leftmost-stall should be used in the case of a tie. Squared distances no longer work, reverted to absolute distance.
(r,x=0,f=g=>r.reduce(g,0))=>f((p,o,i)=>x<(o=f((p,c,j)=>p+c*!o*Math.abs(i-j)))?(x=o,i):p)

Ungolfed:
(r,                            // string input
 x=0,                          // current max distance
 f=g=>r.reduce(g,0))=>         // iterator function
   f((p,o,i)=>                 // for each stall
     x<(o=f((p,c,j)=>          // iterate through all stalls and
       p+c*!o*Math.abs(i-j)))? //   calculate sum of distances from current stall
     (x=o,i):                  // if total dist is greater than x, update x, return index
     p)                        //   else return previous max index

Test runs:
f=(r,x=0,f=g=>r.reduce(g,0))=>f((p,c,i)=>x<(c=+c?0:f((p,c,j)=>p+c*Math.abs(i-j)))?(x=c,i):p)
f([1,0,1])                   // 1
f([0,0,1,0,1,1])             // 0
f([1,0,1,0,0,0,0,1,1])       // 1
f([1,0,0,0,0,0,1,1,0,0,0,0]) // 11
f([1,1,1,1,0,0,0,0,0,0,1])   // 9
f([1,0])                     // 1

Lua, 165150 Byes
n=arg[1]n=n:gsub("%|%-","1"):gsub("%| ","0")i=0 for s in n:gmatch("0+")do i=(i<#s)and(#s)or(i)end n,l=n:find(("0"):rep(i))print(n+math.floor((l-n)/2))

This cheats a little using the fact that generally, lua passes a table called arg containing any command line inputs to it.
I'm a bit disappointed that I used a for in loop, but I couldn't think of a smaller way to pull it off.
Also, Because lua, 1 based indexing was used.
Edit
Snipped 15 bytes from a wasteful gsub.

C#, 127 bytes
public int G(char[]s){int i=0;var l=s.ToLookup(b=>b,b=>i++);return l['0'].OrderBy(j=>l['1'].Average(p=>Math.Abs(p-j))).Last();}

Test Bed
public static void Main() {
    var respectful = new Respectful();
    foreach (var kvp in testCases) {
        $"{kvp.Key}: Expected {kvp.Value} Actual {respectful.G(kvp.Key.ToCharArray())}".Dump();
    }
}

public static readonly List<KeyValuePair<string, int>> testCases = new List<KeyValuePair<string, int>> {
    new KeyValuePair<string, int>("101", 1),
    new KeyValuePair<string, int>("001011", 0),
    new KeyValuePair<string, int>("101000011", 1),
    new KeyValuePair<string, int>("100000110000", 11),
    new KeyValuePair<string, int>("11110000001", 9),
    new KeyValuePair<string, int>("10", 1),
    new KeyValuePair<string, int>("1001", 1),
};

public class Respectful {
    public int G(char[]s){int i=0;var l=s.ToLookup(b=>b,b=>i++);return l['0'].OrderBy(j=>l['1'].Average(p=>Math.Abs(p-j))).Last();}
}


text:
Slices of triangular alphabets
Given an input number n from 1 to 26 (or 0 to 25), output the alphabet reading left-to-right up to and including that corresponding letter, with a=1, b=2, c=3, .... The twist is the letters must also be repeated vertically corresponding to their position in the alphabet. Odd numbers (when 1-indexed) should be balanced across the horizontal line, while even numbers should alternate between favoring the top or bottom (you can choose which direction to go first). If you're 0-indexing, then swap odd/even in the previous sentence.
Worded another way -- if the alphabetical value of a letter ? is #, then there should be # copies of that letter in the output, all of them in the #th column. These letters should be evenly balanced above and below the horizontal line that has the a. If the letters cannot be balanced evenly, then alternate having the "extra" letter above and below that line.
Here are the first six outputs (n = 1,2,3,4,5,6, 1-indexed, choosing to alternate to the bottom first), separated by newlines, so you can see the pattern. Comments explaining the pattern start with #.
a         # On a line by itself

ab
 b        # The "extra" letter is below the horizontal

  c
abc       # The 'c' splits evenly
 bc

   d      # Because the 'b' was below, the extra 'd' must be above
  cd
abcd
 bcd

   de
  cde
abcde     # The 'e' balances
 bcde
    e

   def
  cdef
abcdef
 bcdef
    ef
     f    # Since the 'd' was above, the extra 'f' must be below

(skip a few to n=26)
                       xyz
                      wxyz
                   tuvwxyz
                  stuvwxyz
               pqrstuvwxyz
              opqrstuvwxyz
           lmnopqrstuvwxyz
          klmnopqrstuvwxyz
       hijklmnopqrstuvwxyz
      ghijklmnopqrstuvwxyz
   defghijklmnopqrstuvwxyz
  cdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
 bcdefghijklmnopqrstuvwxyz
    efghijklmnopqrstuvwxyz
     fghijklmnopqrstuvwxyz
        ijklmnopqrstuvwxyz
         jklmnopqrstuvwxyz
            mnopqrstuvwxyz
             nopqrstuvwxyz
                qrstuvwxyz
                 rstuvwxyz
                    uvwxyz
                     vwxyz
                        yz
                         z

Rules

You can choose to output in uppercase or lowercase, but it must be consistent.
The output cannot have extraneous whitespace, except for an optional trailing newline.
Either a full program or a function are acceptable.
The input number can be taken via any suitable format.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Jelly, 20 18 bytes
Ḷ&2’×ḶỤØaḣ⁸¤ṫW€UGU

Port of my Python answer. Try it online.
EDIT: Dennis saved two bytes by using Ụ (grade up) instead of Þ (sort by)!

Python 2, 101 99 bytes
r=range(input())
for x in sorted(r,key=lambda x:x*-(x&2)):print bytearray([97+i,32][i<x]for i in r)

xsot saved two bytes by realizing x*-(x&2) suffices as a sorting key — the bottom half of the resulting image is unaffected due to sorted guaranteeing a stable sort.

Can you not drop a - to output the lines in reverse order, which I believe is allowable?

I think x*-(x&2) works.

Pyth, 26 bytes
A perfect score for a challenge about alphabet.
j_C.e<u_G/k2.[.|1Q*hkbdQ<G

Try it online!

Jelly, 25 bytes
RØaxŒgz⁶W€;ṚL‘$¡¥/Ṛ⁸H¤¡j⁷

Try it online! or verify all test cases.

JavaScript (ES6), 127 126 bytes
n=>[...Array(n).keys()].sort((a,b)=>a*~-(a&2)-b*~-(b&2)).map(i=>` `.repeat(i)+`abcdefghijklmnopqrstuvwxyz`.slice(i,n)).join`\n`

Uses @Lynn's sort trick. Writing out the whole alphabet was two bytes cheaper than calculating it. Edit: Saved 1 byte thanks to @ETHproductions because I forgot to note that \n actually represents the literal newline character. (I don't like putting literal newlines in my answer when the line is so long.)

Save two bytes on the alphabet: btoa`...`  where ... is replaced with the result of atob`abcdefghijklmnopqrstuvwxyzz` . (Also, you can replace \n with a literal newline.)

@ETHproductions I take it that would be using ISO encoding, rather than UTF?

Yes it would. Are we allowed to use ISO-8859-1 rather than UTF-8 in JS?

@ETHproductions Probably but I can't seem to get it to work, so I won't show it.


text:
I've been alphabet hunting for a while
Y'know, we've had a lot of "alphabet" challenges recently. (one two three four five.) While I love a good challenge, and those challenges were very fun, I think it's time for a change of pace. We need to exclude such challenges in the future. It's time for automation!
You're going to find some alphabets for me, and for automation (and for glory!) Alphabets are tricky and like to disguise themselves.[citation-needed] You'll need to account for the following factors:

Alphabets can be uppercase or lowercase (but not both). So, you need to look for ABCDEFGHIJKLMNOPQRSTUVWXYZ and abcdefghijklmnopqrstuvwxyz, but not AbCdeFGhIJkLmNOpQRsTuvwxyZ. That is, only look for alphabets that are composed of entirely one case.
Alphabets can shift around. they may not always start with A, but instead may start with G or U. So you'll have to look for things like OPQRSTUVWXYZABCDEFGHIJKLMN.
Alphabets may not always read forwards. They can also read backwards, up, and down. E.g., ZYXWVUTSRQPONMLKJIHGFEDCBAis also a valid alphabet.

Here's an example of a string that has an alphabet:
JIHGFEDCBAZYXWVUTSRQPONMLK

This is a backwards-oriented, shifted alphabet:
JIHGFEDCBAZYXWVUTSRQPONMLK
<--------|<---------------

This also contains an alphabet:
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E

it's a down-oriented alphabet:
F |
G |
H |
I |
J |
K |
L |
M |
N |
O |
P |
Q |
R |
S |
T |
U |
V |
W |
X |
Y |
Z V
A===
B |
C |
D |
E V

Your challenge is to write a program, function, etc. that, given a string, outputs/returns a truthy value if the string contains at least one alphabet, or a falsey value otherwise. This is a code-golf, so the shortest program in bytes wins.
Test cases
Truthy
ABCDEFGHIJKLMNOPQRSTUVWXYZ

abcdefghijklmnopqrstuvwxyz

ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz

ZABCDEFGHIJKLMNOPQRSTUVWXYghijklmnopqrstuvwxyzabcdef

ZBCDEFGHIJghijklmnopqrstuvwxyzabcdef

AAAAAAAA
BBBBBBBB
CCCCCCCC
DDDDDDDD
EEEEEEEE
FFFFFFFF
GGGGGGGG
HHHHHHHH
IIIIIIII
JJJJJJJJ
KKKKKKKK
LLLLLLLL
MMMMMMMM
NNNNNNNN
OOOOOOOO
PPPPPPPP
QQQQQQQQ
RRRRRRRR
SSSSSSSS
TTTTTTTT
UUUUUUUU
VVVVVVVV
WWWWWWWW
XXXXXXXX
YYYYYYYY
ZZZZZZZZ

 J54
 Igeh
 H
 G
 Fzx6
 E
 Dv
 Cvzxc
 Bs
 Adf
 Z
@Yascvf
 Xsf
 W
 Vfas
 Uw
 Te
~S
 R
 Qasdfasdf
 P
 O
 N
 M
 LMNOPQR
 K

Falsey
Hello, World!

KLMNOPQRSTUVWXYZABCDEF

K        ZYXW
 L         V
  M       U
   N     T
    O   S
     P R
      Q

A
 BCDEFGHIJKLMNOPQRSTUVWXYZ

ABCDEFGHIJKLmnopqrstuvwxyz

"I'm sick of alphabet challenges. Here's an alphabet challenge." lol +1

Can we have the input be padded with spaces to form a rectangle? :3

@Downgoat Yes, you can.

Another challenge to add to your collection.

Can we take a 2D array of strings? Each row would be a line, right-padded with spaces to form a rectangle

@LuisMendo Sure.

Jelly, 28 23 22 bytes
1 byte thanks to Dennis.
26RØAṙ;U$;Œl$
;Zẇ@þ¢FS

Try it online!
Takes an array of strings.

wat how is jelly always so short .___.

@Downgoat are you Jelly?

@PatrickRoberts yes no i am goat

Cheddar, 148 bytes
(s,b=65@"90,c?)->(|>27).map(->s has(b=b.slice(1)+b[0])||s has b.lower||(1|>3).map(j->(c=s.lines.turn(j).vfuse)has b||c has b.lower?1:0).sum?1:0).sum

Try it online!
Non-copmeting, 146 132 bytes
This is the exact same as above except map(...?1:0).sum has become any(...).
(s,b=65@"90,c?)->(|>27).any(->s has(b=b.slice(1)+b[0])||s has b.lower||(1|>3).any(j->(c=s.lines.turn(j).vfuse)has b||c has b.lower))

Rather slow but it works ¯\_(ツ)_/¯ . added any function after challenge release date.
The input does not need to be padded with whitespaces. But if an input doesn't work, pad it with whitespaces to make rectangle. The turn function is really finicky and I'm not sure when it works and when it doesn't
Explanation
Loops through all possible cycles of alphabet. On each iteration check if the current cycle of alphabet exists in the string, if not, check if any of the possible rotations of the string have the alphabet.
Ungolfed
(str, a = 65@"90)->
  (|>27).any(->
    str has (a = a.slice(1) + a[0]) ||
    str has a.lower                 ||
    (1|>3).any(j ->
      (c = str.lines.turn(j).vfuse) has a ||
      c has a.lower
    )
  )

What does c? mean?

@ConorO'Brien c? means optional argument. basically the same as c=nil

Make a competing version, then put this non-competing version at the bottom.

@LeakyNun working on it, can't figure out how to without {} though

any(...) is just map(...?1:0).sum

@LeakyNun oh, yeah! of course

@LeakyNun done!

.sum?1:0 is just .sum

Why do you use b above but a below?

@LeakyNun I'm doing bool||ar.sum meaning I'll need to convert the first bool into a number if that's the one that's true. I use a below because a for alphabet makes more sense than b

Your TIO link is very updated

By the way, it would not work for ABCDEFGHIJKLmnopqrstuvwxyz

@LeakyNun :( that means my golf won't work... oh well back to 148 bytes

I think it would save some bytes if you map the unturned together with the turned.

05AB1E, 43 bytes
AÂ‚Duìvy26FÀD}})U|Dø€J)˜vXDgs`rFysk>ˆ}}¯O__

Explanation in short
Get different variations of alphabet (caps, no-caps, reversed, normal) and store in X.
AÂ‚Duìvy26FÀD}})U

Get each row and column of input as a list of strings.
                 |Dø€J)˜

Check each such string if it contains a variation of the alphabet.
                        vXDgs`rFysk>ˆ}}

Sum and double negate, giving 1 for true and 0 for false.
                                       ¯O__

Try it online

Python, 182 bytes
Doesn't feel very 'golfed', but ...
import re
a='abcdefghijklmnopqrstuvwxyz'
P,N='|\n'
p=P.join(a[i:]+a[:i] for i in range(26))
p+=P+p[::-1]
p+=P+p.upper()
lambda s:re.search(p,s+N+N.join(map(''.join,zip(*s.split(N)))))

Theory of operation:
First, build a regex pattern combining all the possible alphabets:
p=P.join(a[i:]+a[:i] for i in range(26)) builds a string of all rotations of 'a' joined with '|'.  e.g. "abc...z|bcd...za|..."
p+=P+p[::-1] appends a reversed version of itself.
p+=P+p.upper() appends an uppercase version.
Then create a long string combining the original s and a version of s with the columns turned into rows:
N.join(map(''.join,zip(*s.split(N)))) flips the rows and columns, so 'a\nb\nc' becomes 'abc'
return true if the pattern is in the long string.

Pretty sure you don't need regex to do this; specifically, in checks for substring.

@LeakyNun, I was trying to avoid lots of loops over the possible alphabets (rotations, reversals, case).  The regex pattern has all the possibilities--using just one loop.  Also, the string to search includes the input string in both normal and row-flipped versions, so no looping there either.