text:
Counting Goats to Sleep
Some people count sheep to get to sleep. Others count goats.
Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.
Awake goats look like this:
      \
  ___/o>
-(___)"
 '' ''

Sleeping goats look like this:
      \
  ___/->
,(___)"
 `` ``

They are chained together with a single space between beard and tail of adjacent goats:
      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``

The output is allowed to have trailing spaces and a single trailing newline.
The shortest code in bytes wins.
Examples
N = 1:
      \
  ___/->
,(___)"
 `` ``

N = 2:
      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``

N = 3:
      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``

N = 4:
      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``

Larger N should work just as well.

I think your "goats" look more like 4-footed angry birds ;-)

Aww I was hoping to count some goats, not the other way round

I think I know who counts goats to sleep

I don't think you can count goat to sleep unless "bleeeeeeet" makes you feel sleepy :P +1 great challenge

I keep reading this as "counting goats to sheep"... There's gotta be a challenge in that somewhere

Psychopaths fall asleep by counting screaming goats.

Why is the sleeping one leading the others? Shouldn't it be last?

@msh210 If an awake one leads, you will be awake forever.

MATL, 56 53 bytes
:"'!!((!((!!#*```).?p0```!!!]'8eP!P]'p(.' '.a-'XE&hqc

Try it online!
Explanation
Awake goat
The awake goat can be packed into the string
  '' ''  ")___(->o/___   \

and unpacked as will be explained shortly. However, the single-quote symbols would need to be duplicated in order to escape them, so the string literal would have to be defined as (note the enclosing single-quote symbols and the duplication of the original ones):
'  '''' ''''  ")___(->o/___   \'

To save bytes, we define the string using characters one code point above that, thus avoiding duplication. The string literal becomes
'!!((!((!!#*```).?p0```!!!]'

At the end of the code we will subtract 1 and convert to char. (We could do it now, right after the string literal; but leaving it for the end will save another single-quote duplication, as we will see).
To explain how the string is unpacked, we will work with the original characters (that are produced at the end of the code by subtacting 1), so the explanation is easier to follow. We first reshape the string
  '' ''  ")___(->o/___   \

into an 8-row 2D char array, in column-major order (down, then across). This automatically pads the last column with char 0 (at the end of the code, subtracting 1 will transform it into number −1, which converted to char gives again char 0). Char 0 is displayed as a space. So effectively we are padding with spaces. The result of reshaping is
  >
 "o\
')/
'__
 __
'__
'(
 -

We now flip vertically:
 -
'(
'__
 __
'__
')/
 "o\
  >

and then transpose and flip vertically again to produce the awake goat:
      \
  ___/o>
-(___)"
 '' ''

The two flip operations are needed because the original packed string is "in reverse". This is to exploit the fact that the actual 2D char array representing the goat has 6 initial spaces in its first row, which get automatically filled by padding when the string is reshaped into an 8-row 2D array. But the padding is done at the end (not beginning) of the last column (not row), hence the flips and transpose.
Sleeping goat
A sleeping goat is generated from an awake goat by transliterating chars o, ', - into -, `, , respectively. Actually, because of the one-code-point-above transformation, we transliterate chars p, (, ' into ., a, -, which again saves us from having to duplicate the single-quote symbol. This is why the subtract-one operation was left for the end of the program.
Code structure

Generate an awake goat N times, working with code points increased by 1.
Transform the last goat into a sleeping goat.
Concatenate all goats horizontally. Subtract 1 to code points and cast to char.

Commented code
:                              % (Step 1) Implicitly input N. Push range [1 2 ... N]
"                              % For each (i.e. repeat N times)
  '!!((!((!!#*```).?p0```!!!]' %   Push this string. Quotes are escaped by duplicating
  8e                           %   Reshape into an 8-row 2D array of char, in
                               %   column-major order, padding last column with
                               %   char 0
  P                            %   Flip vertically
  !P                           %   Transpose and flip vertically
]                              % End
'p(.'                          % (Step 2) Push this string: source for transliteration
'.a-'                          % Push this string: target for transliteration
XE                             % Transliterate. Transforms last goat into sleeping
&h                             % (Step 3) Horizontally concat all 2D char arrays
qc                             % Subtract 1 and convert to char. 0 becomes −1, which
                               % is converted to char 0, which is displayed as a space
                               % Implicitly display

This is some serious goat theory ;)

Javascript, 122 bytes
Answer
f=(n,r='repeat')=>'      \\ '[r](n--)+`
${'  ___/o>'[r](n)}  ___/->
${'-(___)" '[r](n)},(___)"
`+` '' ''  `[r](n)+' `` ``'

Side note
In the following code (91 bytes) the goats are aligned verticaly.
It does not comply with the output format but i though it could be interesting to note that the horizontal alignment required in the output format needs more bytes:
f=n=>`
      \\
  ___/${--n?'o':'-'}>
${n?'-':','}(___)"
 ${n?'`` ``':`'' ''`}`+(n?f(n):'')

Why include the vertical submission? The challenge asks for horizontal alignment.

@Mego What's wrong with showing how much more golfable it would have been?

@Neil Because it's entirely tangential to the challenge.

@Mego I think it's interesting to note.

It's not. It's completely irrelevant to the challenge at hand, and doesn't need to be there any more than a primality test program.

@Mego And a goat with a speech bubble is OK because?

@Neil You have completely missed the point of what I am saying. The second version that outputs in an entirely incorrect manner is just as irrelevant as a primality testing program for this challenge. Neither should be present.

@Mego I thought it could be interesting. I edited the post to make it more obvious that the vertical alignment is not a valid answer.

Batch, 234 bytes
@echo off
set/pn=
call:l "      \ " "      \"
call:l "  ___/o]" "  ___/-]"
call:l "-(___)@ " ",(___)@"
call:l " '' ''  " " `` ``"
exit/b
:l
set s=%~2
for /l %%i in (2,1,%n%)do call set s=%~1%%s%%
set s=%s:@="%
echo %s:]=^>%

Takes input from stdin. Batch has trouble with " and > for various reasons so I have to use placeholders and then switch them at the end.

I had no idea set/pn works ._.

The ^ escapes characters.

@Krii Doesn't work when I need it to.

Pyke, 56 54 bytes
Fhqd6*"\
  ___/o>
-(___)
 '' ''"+23\":RI"-o'"",-`".:(P

Try it here!
4 bytes too many because Pyke doesn't allow double quotes in strings :(

JavaScript (ES6), 110 109 bytes

f=
n=>`      \\       \\
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `.replace(/^.{8}/gm,"$&".repeat(n-1))+"`` ``"
;
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

Having to support all three kinds of quote characters was annoying, but fortunately @pinkfloydx33's comment gave me the flash of inspiration that I could add the backquotes at the end thus saving me 1 byte.

Can you save a byte by switching the quote type in the middle and concatenating two strings '+"'' ''" (assume single quotes are back ticks since I've no idea how to get a backtick into a code block in comments)

@pinkfloydx33 I thought I'd already tried that but then I realised that I could add those back ticks at the end which does save me a byte. Also to get a back tick in a comment code block just prefix it with a backslash.

You can remove the semicolon

@howderek I didn't include it or the f= in my byte count, it's just there for completeness.

Jelly, 62 56 bytes
⁶ẋ6;“\   ___/o>-(___)"  '' ''  ”s8
¢“-,o-'`”yÐ€
’1£ẋ€ż¢Y

Test it at TryItOnline
How?
⁶ẋ6;“\   ___/o>-(___)"  '' ''  ”s8 - Link 1: make a goat, niladic
⁶ẋ6                                - space character, ⁶, repeated 6 times
    “\   ___/o>-(___)"  '' ''  ”   - rest of the awake goat text
   ;                               - concatenate
                                s8 - split into length 8 parts

¢“-,o-'`”yÐ€ - Link 2: put a goat to sleep, niladic
¢            - last link (make a goat)
 “-,o-'`”    - characters to remap
         yÐ€ - map for each (change "-" into ",", "o" into "-", and "-" into "`"

’1£ẋ€ż¢Y - Main link: n
’        - decrement (nAwakeGoats)
 1£      - call link 1 as a nilad (make an awake goat)
   ẋ€    - repeat nAwakeGoats times
      ¢  - last link (make a sleeping goat)
     ż   - zip
       Y - join with line feeds
         - implicit print

GolfScript, 91 bytes
~:a 1-:b;"      \\ "a*n"  ___/o>"b*"  ___/->"n"-(___)\" "b*",(___)\""n" '' ''  "b*" `` ``"n

Input: 3
Output:
      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``

Explanation
~:a 1-:b;      # Parse and save the input
"      \\ "a*n # Repeat the first line 'a' times
"  ___/o>"b*   # Repeat the head 'b' times
"  ___/->"n    # Then add the sleeping goat's head
"-(___)\" "b*  # Idem
",(___)\""n    #
" '' ''  "b*   # Idem
" `` ``"n      #

Try it online!

Nearly misread as GoatScript

Knight, 96 bytes
;O*"      \ "=n+0P;O+*+=t'  ___/''->'=l-nT+t'o>';O+*+','=t'(___)" 'l+'-'tO+*' `` ``  'l" '' ''"

Pretty simple, nothing super fancy—You just print out n-1 versions of the sleeping goat and then the woke goat. Repeatable elements are saved in t so they aren't typed out again.
Expanded:
# Print out the ears. They're the same for both goat types.
; OUTPUT (* "      \ " (= n (+ 0 PROMPT)))
; OUTPUT
    (+
        (* (+ (= tmp '  ___/')'->') (= m - n TRUE))
        (+ tmp 'o>'))
; OUTPUT
    (+
        (* (+ ',' (= tmp '(___)" ')) m)
        (+ '-' tmp))
OUTPUT (+ (* ' `` ``  ' m) (" '' ''"))

-2 bytes: *" ''"2

PHP , 200 Bytes
$a=["      \ ","  ___/o>",'-(___)" '," '' ''  "," `` ``  "];$z=8*$n=$argv[1];for($i=0;$i<4;)$o.=str_repeat($a[$i],$i++==3?$n-1:$n);$o[$z*2-2]="-";$o[$z*3-8]=",";$o.=$a[4];echo chunk_split($o,$z,"\n");

You are coding way too clean, Jörg. I could golf off 32 bytes from that in 11 steps. Want hints?

Thanks I want only to solve this challenge in any way. Sometimes is clean better then a wrong solution. You can paste your way.

I took a different approach; but if you want tips for yours, just ask. 24 bytes in the first 5 steps.

@JörgHülsermann Modifying other people's answers seems to be heavily frowned upon in this site.

@Carcigenicate Did You mean I should modifying answers from other People or viceversa? I tend more to solve a problem clean if I am only interesting like in this case. Ascii Art is normally not my priority

C++, 180 bytes
auto f(int n)
{
string a,b,c,d;
while(n--)
{
a+="      \\ ";
b+="  ___/";b+=n?"o>":"->\n";
c+=n?"-(___)\" ":",(___)\" \n";
d+=n?R"( '' ''  )":" `` ``  \n";
}
return a+'\n'+b+c+d;
}

Welcome to PPCG! Please include the one line version so that you can actually count it. You can always include a readable version separately so people don't have to read the one-liner. :)

Martin, thanks for the link. I originally measured the size by file size and now I fix it.

Answers should indeed be measured by file size. My point was that your code does work without the linefeeds, so the answer should include that version.

Okay, I wrote the size by file size. About how this code works - there is no difference between readable and one line version.

I don't think it's valid to not include the #include <string> and either using namespace std; or using std::string; in your byte count if your function cannot be compiled without them.

Pip, 60 + 1 = 61 bytes
One byte added for the n flag.
YsX6.\"\   ___/o>-(___)"  '' ''  \"<>8yXa-1.YyR^"-o'"Y^",-`"

Constructs an awake goat as a list of lines and yanks it into y. String-multiplies to get a-1 awake goats. Replaces -o' with ,-` in y and concatenates it to the end. Prints, newline-separated.
Try it online!
(I think this is my first time using Pip's escaped-string syntax \"...\", which allows for literal double quotes in the string.)

Python 2.7, 101 113 bytes
Edit: Added function definition
def f(n):
 m=n-1
 print "      \ "*n+"\n"+"  ___/o>"*m+"  ___/->\n"+'-(___)" '*n+"\n"+" '' ''  "*m+" ``"*2

de-golfified:
m=n-1              # Replacement variable. Saves 6 bytes
"      \ "*n+"\n"+ # Print ears, same for all goats!
"  ___/o>"*m+      # Print eyes of n-1 awake goat
"  ___/->\n"+      # Print eye of sleeping goat
'-(___)" '*m+      # Print body of n-1 awake goat
',(___)"\n'+       # Print body of sleeping goat
+" '' ''  "*m+     # Print the legs of n-1 awake goat
" ``"*2            # Print legs of sleeping goat using *2 operator to save 1 byte

Note Python2.7 is one byte shorter than Python3 due to that it doesn't need parentesis when printing.

Needs to receive input n, and you've missed the tail change for the sleeping goat (also did you see the Py 3.6 answer?).

Hi! The tail change is there, wasn't sure about if you needed to handle input. Had a look a the Python3.6 answer after writing my own. Does it that recieve input though?

Ah, ok. It needs to be either a program or a function. Will update with worse solution, for now :(

Yep, function or program, you got it! You can remove the space in print "..., and place everything on one line, using 1 ; to separate the two statements. The tail still not in the golfed code shown, but looks like you've counted it, all in that should make it 112 bytes.

IBM/Lotus Notes Formula, 187 174 188 bytes (not competing)
EDIT Found a space that shouldn't have been there and removed an unneeded @Implode
188 as I had missed the fact that the tail of the sleeping goat is different :-(
B:=@Repeat("      \\  ";a);C:=@Repeat("     /o> ";a-1)+"     /->";D:=@Repeat("  ---    ";a);E:=@Repeat(",(___)\"  ";a);F:=@Repeat(" `` ``   ";a);@Implode(B:C:D:E:F;@NewLine)

Ungolfed:
B:=@Repeat("      \\  ";a);
C:=@Repeat("     /o> ";a-1)+"     /->";
D:=@Repeat("  ---    ";a);
E:=@Repeat("`(___)\"  ";a-1)+",(___)\"  ";
F:=@Repeat(" `` ``   ";a);
@Implode(B:C:D:E:F;@NewLine)

Usage:
Create a Notes form with two fields named a and g.
a=editable, number, g=computed, text.
Paste the above formula into g and give a a default value of 0.
Set the form font to Terminal.
Create a new document with the form, enter a number in a and press F9 to update the goats.
Samples:

Not competing as the format messes up when the number of goats reaches the width of the page.
Given an infinitely wide screen it should will work for any number of goats though. This is what it looks like when the page is not wide enough.

Why is it non-competing? Every answer is like that. That's called wrapping.

Thanks for the clarification @mbomb007. Was trying to be honest and not disrespect better golfers than me. I'm new to this. Ok it competes. It won't win but I bet there won't be too many Lotus Notes golfers to beat me with formula language ☺

To be honest, I bet there won't be too many Lotus Notes golfers.

CJam, 58 bytes
ri{S6*"\   ___/o>,(___)\"  '' ''  "+\{'o`"`-"er}|8/}%W%zN*

Try it online!
Explanation
ri                               e# Read an integer from input
{                                e# Map the following block to the range 0..input-1
 S6*                             e#  Push 6 space characters
 "\   ___/o>,(___)\"  '' ''  "+  e#  Push this string and concatenate with the spaces
 \                               e#  Bring the number being mapped to the top
 {                               e#  If it's 0, execute this block:
  'o`                            e#   Push the string "'o"
  "`-"                           e#   Push the string "`-"
  er                             e#   Transliterate the large string by replacing characters
                                 e#    from "'o" with respective characters from "`-"; this
                                 e#    makes the sleeping goat.
 }|                              e#  (end if)
 8/                              e#  Split the string into chunks of length 8
}%                               e# (end map)
W%                               e# Reverse the array, since the sleeping goat was made at
                                 e#  the beginning
z                                e# Transpose
N*                               e# Join with newlines

05AB1E, 66 bytes
’      \ 0  ___/1>02(___)" 0 33 33  ’0¡v123SDys…o-'S:I<×?ys…-,`S:,

Try it online!
Explanation
’      \ 0  ___/1>02(___)" 0 33 33  ’0¡v123SDys…o-'S:I<×?ys…-,`S:,   Argument n
’      \ 0  ___/1>02(___)" 0 33 33  ’   The goat, newline replaced by 0 and the eye replaced by 1
0¡                              Split on 0
  v                             For each y in array, do:
   123SD                          Push the array [1,2,3] twice
        ys…o-'S:                  Replace [1,2,3] with ['o','-','\'']
                I<×?              Print that n-1 times without newline
                    ys…-,`S:,     Replace [1,2,3] with ['-',',','`'] and print

Perl 5 -n, 105 bytes
say for'      \\ 'x(--$_+1),
'  ___/o>'x$_.'  ___/->',
'-(___)" 'x$_.',(___)" ',
" '' ''  "x$_.' `` ``  '

Try it online!

Bash + GNU Coreutils, 165 155 bytes
a=" \
>o/___
 \")___(-
  '' '' "
eval paste -d \'\' $(seq $1|while read;do
printf '<(echo "$a") '
done) | sed "s/-/,/;s/o/-/;s/'' ''/"'`` ``/'|rev

Run with:
bash my_pgm.bash N

Basically the program prints N times of the same goat (reversed), and substitutes the first -, for ,, the first o for - and the first '' '' for the backticks. Then reverses the lines.

PHP, 133 131 bytes
for(;$y<32;$y+=8)for($x=$argv[1];$x--;)echo substr("      \   ___/".($x?"o>-(___)\"  '' ''  ":"->,(___)\"  `` ``  "),$y,8),"
"[$x];

I found two bytes to golf away from one of the version without curlys.

Ruby, 102 bytes
m=-1+n=gets.to_i
puts'      \ '*n,'  ___/o>'*m+'  ___/->',(?-+a='(___)" ')*m+?,+a," '' ''  "*m+" ``"*2

Python 3. 170 bytes
lambda n:'\n'.join(map(lambda*l:''.join(l),*map(lambda w:(' '*6+'\ ','  ___/'+(w and'o'or'-')+'>',(w and'-'or',')+'(___)" ',w and" '' ''  "or' `` ``  '),range(n)[::-1])))

hmm, apparently constructing the string without doing list manipulation yield shorter code

Java 8, 236 222 218 173 bytes
n->{String x="\n",a="",b=a,c=a,d=a;for(;n-->0;a+="      \\ ",b+="  ___/"+(n<1?"-":"o")+">",c+=(n<1?",":"-")+"(   )\" ")d+=(n<1?" `` ``":" '' ''")+"  ";return a+x+b+x+c+x+d;}

Explanation:
Try it online.
n->{                                // Method with integer parameter and String return-type
  String x="\n",                    //  New-line String to reduce bytes
         a="",                      //  Row 1 String, starting empty
         b=a,                       //  Row 2 String, starting empty
         c=a,                       //  Row 3 String, starting empty
         d=a;                       //  Row 4 String, starting empty
  for(;n-->0;                       //  Loop `n` times:
    a+="      \\ ",                 //   Append the horns to row 1
    b+="  ___/"+(n<1?"-":"o")+">",  //   Append the back and head to row 2
    c+=(n<1?",":"-")+"(   )\" ")    //   Append the tail, body, and beard to row 3
    d+=(n<1?" `` ``":" '' ''")+"  ";//   Append the legs to row 4
  return a+x+b+x+c+x+d;}            //  Return the four rows, separated by new-lines

PowerShell v2+, 96 bytes
param($n)'      \ '*$n--
'  ___/o>'*$n+'  ___/->'
'-(___)" '*$n+',(___)"'
" '' ''  "*$n+' `` ``'

(ab)uses the default Write-Output formatting to include a newline between elements. Leverages string concatenation and multiplication to construct the goats line by line. The only real trick is the first line $n-- to output the correct number of ears and then post-decrement $n so it's correct for the rest of the lines.
PS C:\Tools\Scripts\golfing>  1..4|%{.\counting-goats-to-sleep.ps1 $_}
      \
  ___/->
,(___)"
 `` ``
      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``

Emacs Lisp, 241 bytes
(defvar s'("     \\""  ___/->"",(___)\""" `` ``"))(defun a()(dotimes(n 4 g)(setf(nth n g)(format"%s%s"(nth n'("     \\  ""  ___/o>""-(___)\" "" '' ''  "))(nth n g)))))(defun g(n)(let((g(copy-seq s)))(mapcar'message(dotimes(i(- n 1)g)(a)))))

"Slightly ungolfed"
(defvar s'("     \\""  ___/->"",(___)\""" `` ``"))
(defun a()(dotimes(n 4 g)(setf(nth n g)(format"%s%s"(nth n'("     \\  ""  ___/o>""-(___)\" "" '' ''  "))(nth n g)))))
(defun g(n)(let((g(copy-seq s)))(mapcar'message(dotimes(i(- n 1)g)(a)))))

where s is one sleeping goat, a adds an awake goat and g(n) is the counting function.

Canvas, 58 39 bytes
！－≥９A²］]ｋ１｛｛K４ｅdｒ↙FX‟×-２２╋,８３╋`` ``３４╋↔

Try it here!
Constructs the awake goat facing left from a compressed string, repeats it \$n\$ times horizontally, modifies the left-most goat to the sleeping goat, then flips the whole string horizontally.

Brainfuck 420 bytes
Its not very golfed yet... but it works... whit numbers from 0 to 255 :)
>+[[-]>,[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<[->+>+>+>+<<<<]>>>>>>++++[<++++++++>-]>-[<+>---]<+++++++>>-[<+>-----]<---->>-[<-->-------]<+>>----[<+>----]<-><<<<<<[>......>.<.<-]++++++++++.>>+++<<<-[>>..>...>.>.>.<<<<<<-]>>..>...>.--.>>.[<]>.<<-[>>>>>.-----.<...>+.++++<<++.--.<<<-]>>>>>-.----.<...>+.<<++.--.>>[-<<<<+>>>>]<[<]>-->.<<<-[>>>>.<<..>>.<<..>>..<<<<-]>>>>>+<.>..<.>..<..

Try it online
Explained version:
Read number from 0 to 255 "thanks to esolangs ;)"
>+[[-]>,[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<

Its a little bit hard explain this part because it is creating letters and printing lines
at the same time
[->+>+>+>+<<<<]                              Make 4 copies of the number (one for every line)
>>>>>>++++[<++++++++>-]>-[<+>---]<+++++++>   Make space and '\'
>-[<+>-----]<----                            Make '/'
>>-[<-->-------]<+                           Make 'o'
>>----[<+>----]<->                           Make mayor sign
<<<<<<[>......>.<.<-]                        Print first line
++++++++++.>>+++<<                           Make line jump and '_'
<-[>>..>...>.>.>.<<<<<<-]                    Print second line
>>..>...>.--.>>.[<]                          Make minus sign and print the line of last sheep
>.<<-[>>>>>.-----.<...>+.++++<<++.--.<<<-]   Print thirth line
>>>>>-.----.<...>+.<<++.--.>>[-<<<<+>>>>]    Print the line of last sheep
<[<]>-->.<<<-[>>>>.<<..>>.<<..>>..<<<<-]     Print fourth line
>>>>>+<.>..<.>..<..                          Print the line of last sheep

Zsh, 97 bytes
$1()O+=${s/o/-}
for s ('      \ '
"  ___/o>"
'-(___)" '
" '' ''  ")(eval {1..$1}'||O+=$s;';<<<$O)

Try it online!
Feels way too long.

05AB1E, 63 61 bytes
•D:¨Mß²нĀùÜ<3¹º•“\
_/o>-()"'“ÅвJ.B×»R"-, o-"#vy`.;2F„'``.;]R

Try it online!
•...•“...“ÅвJ.B×»R"..."#vy`.;2F„'``.;]R  # trimmed program
                                      R  # push reversed...
             .B                          # list of lines in...
            J                            # joined...
          Åв                             # list of characters in...
     “...“                               # literal...
          Åв                             # with indices in base-10 values of base length of...
     “...“                               # literal...
          Åв                             # digits of...
•...•                                    # 258955905826915235144641900393055...
             .B                          # with length of longest line minus length of each line spaces appended to each line...
                                         # (implicit) with each element...
               ×                         # repeated...
                                         # implicit input...
               ×                         # times...
                »                        # joined by newlines...
                 R                       # reversed...
                           .;            # with first occurence of...
                          `              # second character of...
                         y               # variable...
                           .;            # replaced by...
                          `              # first character of...
                         y               # variable...
                        v                # for y in...
                  "..."                  # literal...
                       #                 # split by spaces...
                                   .;    # with first occurence of...
                                  `      # second character of...
                               „'`       # literal...
                                   .;    # replaced by...
                                  `      # first character of...
                               „'`       # literal...
                              F          # for n in [0, 1, 2, ...,
                             2           # ..., literal...
                              F          # ]
                                     ]   # exit loop
                                     ]   # exit loop
                                         # implicit output


text:
Sum or difference of two powers of two
Your challenge, should you choose to accept it, is, given an integer K >= 1, find non-negative integers A and B  such that at least one of the two conditions following hold:

K = 2^A + 2^B
K = 2^A - 2^B

If there does not exist such A and B, your program may behave in any fashion. (To clarify, A and B can be equal.)
Test cases
There are often multiple solutions to a number, but here are a few:
K => A, B
1 => 1, 0
15 => 4, 0                      ; 16 - 1 = 15
16 => 5, 4                      ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16
40 => 5, 3                      ; 2^5 + 2^3 = 40
264 => 8, 3
17179867136 => 34, 11           ; 17179869184 - 2048 = 17179867136

The last test case, 17179867136, must run in under 10 seconds on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function.

Can A equal B?

@Dennis I don't see why not.

... and for 16, both 5,4 and 3,3 are valid.

Actually now that I think about it, can A, B be negative? (e.g. -1, -1 for 1)

@Sp3000 No, good point.

Jelly, 11 10 bytes
;0+N&$BL€’

Applying the bit twiddling trick from the Python answer by @xnor
Test it at TryItOnline
All test cases are also at TryItOnline
How?
;0+N&$BL€’ - main link takes an argument, k, e.g 15
;0         - concatenate k with 0, e.g. [15, 0]
     $     - last two links as a monad
   N       - negate, e.g. -15
    &      - bitwise and, e.g. -15&15=1 since these two are called as a monad (one input)
  +        - add, vectorises, e.g. [16,1]
      B    - convert to binary, vectorises, e.g. [[1,0,0,0,0],[1]]
       L€  - length for each, e.g. [5,1]
         ’ - decrement, vectorises, e.g. [4,0]

Python 2, 43 bytes
lambda n:[len(bin((n&-n)+k))-3for k in n,0]

Say that n==2^a ± 2^b with a>b. Then, the greatest power-of-2 factor of n is 2^b, and we can find it using the bit-trick 2^b = n&-n. That lets us compute 2^b + n, which equals either 2^a + 2 * 2^b or just 2^a. Either one has the same-length bit-length as a*. So, we output the bit-lengths of n&-n and (n&-n)+n, computed from the lengths of their binary representations. Python 3 is one byte longer for parens in for k in(n,0)].
*Except that 2^a + 2^b with a==b+1 has one longer bit-length, but that's fine because we can interpret that as 2^(a+1)-2^b.

Wonderful - I looked for a bit fiddle, but couldn't work it out, just ported to Jelly.

Try n=4 or 8 or 16 please.

@Titus f(2**n) returns (n+1,n) and 2**(n+1)-2**n=2**n so there is no problem.

ah ... What´s the format of bin() in Python?

@Titus it's a string with a leading 0b, hence the -3.

JavaScript (ES6), 73 bytes
(n,[s,f,z]=/^1+(.*1)?(0*)$/.exec(n.toString(2)))=>[s.length-!!f,z.length]

For the subtraction case, the first number is the number of digits in the binary representation and the second number is the number of trailing zeroes. For the addition case, we subtract 1 from the first number. If the binary representation is all 1s followed by some 0s then the addition case is assumed otherwise the subtraction case is assumed. 36-byte port of @xnor's version that only works for B≤30 in JavaScript:
n=>[(l=Math.log2)(n+(n&=-n))|0,l(n)]

@ETHproductions Sure, but I golfed it down to 36.

My bad, I thought that the 36-byte version didn't work for the 17 billion test case.

@ETHproductions It doesn't, but then neither did your port, as I recall (comment since deleted, sigh), since it used bitwise operations.

Sorry, here it is again: n=>[n,0].map(k=>((n&-n)+k).toString(2).length-1) And both versions return [34,11] on the last test case (I'm using FF 48).

@ETHproductions Aha, so more accurately they work when the second result is 30 or less.

Perl, 52 49 32 bytes
Old solution (49 bytes)
Includes +1 for -p
Give input on STDIN:
pow2.pl <<< 17179867136

pow2.pl
#!/usr/bin/perl -p
$_=reverse sprintf"%b",$_;/()1(?:1+|0*)/;$_="@+"

However, using xnor's algorithm and adding a twist gives 32 bytes:
perl -nE 'say 13/9*log|0for$;=$_&-$_,$_+$'

Just the code:
say 13/9*log|0for$;=$_&-$_,$_+$

This suffers from severe rounding error because 13/9 = 1.444... is quite a bit above 1/log 2 = 1.44269... (log itself also has a rounding error but that is so much smaller that we can wrap it up in the analysis of 13/9). But since any 2**big - 2** small gets corrected to 2** big before the log this doesn't mater and the calculation for 2**big + 2 * 2**small gets truncated  down so is also safe..
And at the other side of the range 2**n+2**(n-1) doesn't get increased enough in the range [0,64] (I can't properly support more than the integer range anyways due to the use of &) to lead to a wrong result (multiplicator 1.5 however would be too far off for large numbers).

Brachylog, 23 bytes
,A:B#+.:2rz:^a{+|-}?,.=

Try it online!
This is much faster than required, e.g. this is still under 10 seconds on TIO.
Explanation
This is basically a direct transcription of the formula with no optimization:
,A:B     The list [A, B]
#+       Both A and B are greater than or equal to 0
.        Output = [A, B]
:2rz     The list [[2, A], [2, B]]
:^a      The list [2^A, 2^B]
{+|-}?   2^A + 2^B = Input OR 2^A - 2^B = Input
,.=      Assign a value to A and B which satisfy those constraints

It looks like this challenge was made for the language :D

Mathematica, 57 54 bytes
Saved 3 bytes thanks to LegionMammal978!
Do[Abs[2^a-#]==2^b&&Print@{a,b},{a,2Log@#+1},{b,0,a}]&

Actually prints out all1 appropriate pairs {a,b}. 2Log@#+1 is an upper bound for the largest a that can possibly appear when representing the input # (the tight upper bound is Log[2#]/Log[2] = 1.44... Log[#] + 1). Runs almost instantaneously on the test input, and in less than a quarter second (on my new but off-the-shelf computer) on 100-digit inputs.
1 Letting a start at the default value of 1 instead of 0 saves two bytes; it causes the output {0,0} to be missed when the input is 2, but finds the output {2,1} in that case, which is good enough.

All* appropriate pairs? (Also, If[Abs[2^a-#]==2^b,Print@{a,b}] can be replaced with Abs[2^a-#]==2^b&&Print@{a,b} to save 3 bytes.)

Nice observation, I get it! "All*" was a footnote, but it's clearer now.

Python, 69 bytes
def f(k):b=bin(k)[::-1];return len(b)-2-(b.count('1')==2),b.find('1')

Tests are on ideone
Since non-valid input can do anything, we know that if the input has exactly 2 bits set it is the sum of those 2 powers of 2, and otherwise (if valid) it will be be a run of some number of bits (including the possibility of just 1 bit) and will be the difference between the next highest power of 2 than the MSB and the LSB set.

JAVA 7 ,142 ,140, 134 BYTES
This is my first post on PPCG!I would really appreciate for feedback on golfing tips

Thanks to frozen for saving 2 bytes
void f(long n){for(int i=-1,j;i++<31;)for(j=0;j++<34;){long a=1,x=a<<i,y=a<<j;if(x+y==n|y-x==n){System.out.println(j+" "+i);return;}}}

UNGOLF
void f(long n){
    for(int i=-1,j;i++<31;)
         for(j=0;j++<34;){
          long a=1,x=a<<i,y=a<<j;
            if(x+y==n|y-x==n){
            System.out.println(j+" "+i);
        return;
        }
            }
    }

ideone

Hi numberknot! Another wanderer from puzzling I see. It does not seem to work for 40=2**3+2**5, for example. Looking at it, I can't see why not, maybe I made a transcription error...

@JonathanAllan Now it works fine.Actually the brackets were missing in this line if((a<<i)+(a<<j)==n|(a<<j)-(a<<i)==n) and thanks.

Can´t you use a literal 1 instead of declaring a variable for it?

@TItus if I use literal 1 then this testcase(17179867136 ) would not be possible because if you use literal 1 then java automatically assigned it an INT memory space.

You can declare j together with i: for(int i=-1,j;[...]

+1 You can golf it some more, though. a=1, can be removed and both as can be replaced with 1L. You can return a String instead of printing directly. And you can remove the second long and add ,x,y in the for-loop, and assign them directly in the if-check so you can remove the for-loop brackets. So total becomes this: (119 bytes) String f(long n){for(long i=-1,j,x,y;i++<31;)for(j=0;j++<34;)if((x=1L<<i)+(y=1L<<j)==n|y-x==n)return j+" "+i;return"";}

MATL, 23 22 bytes
BnQ:qWtG-|ym)1)tG-|hZl

Try it online! Or verify all test cases.
Explanation
B      % Implicit input. Convert to binary. Gives n digits
nQ:q   % Range [1 ... n+1]
W      % 2 raised to that, element-wise: gives [1 2 4 ... 2^(n+1)] (*)
tG-|   % Duplicate. Absolute difference with input, element-wise (**)
y      % Push a copy of (*)
m      % True for elements of (**) that are members of (*)
)      % Use as logical index to select elements from (*)
1)     % Take the first element. Gives power of the first result
tG-|   % Duplicate. Absolute difference with input. Gives power of the second result
hZl    % Concatenate. Take binary logarithm. Implicit display

Perl 6, 41 bytes
{.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}

( Algorithm shamelessly copied from the Perl 5 answer )
Explanation:
# bare block lambda with implicit parameter ｢$_｣
{
  # turn into binary
  # ( implicit method call on ｢$_｣ )
  .base(2)

  # flip the binary representation
  .flip

  ~~ # smartmatch that against:

  /
    1      # a ｢1｣
    [
      | 1+ # at least one ｢1｣
      | 0* # or any number of ｢0｣
    ]
  /;

  # returns a list comprised of

  # the position of the end of the match (larger of the two)
  $/.to,
  # the position of the beginning of the match
  $/.from
}

Usage:
# give it a lexical name for clarity
my &bin-sum-diff = {.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}

say bin-sum-diff 15; # (4 0)
say bin-sum-diff 16; # (5 4)

say bin-sum-diff 20; # (4 2)
# 2**4==16, 2**2==4; 16+4 == 20

say bin-sum-diff 40; # (5 3)
say bin-sum-diff 264; # (8 3)
say bin-sum-diff 17179867136; # (34 11)

PHP, 73 bytes
I could have copied Jonathan´s Pyhton 2 solution for 54 bytes (+13 overhead),
but wanted to come up with something different.
save to file, then execute with php or php-cgi.
<?=strlen($n=decbin($argv[1]))-!!strpos($n,'01')._.strpos(strrev($n),49);

prints a and b separated by an underscore, anything for no solution.
distinctive solution, 96 bytes
<?=preg_match('#^(10*1|(1+))(0*)$#',decbin($argv[1]),$m)?strlen($m[0])-!$m[2]._.strlen($m[3]):_;

prints a and b separated by an underscore; a sole underscore for no solution.
It even tells you the operation for 11 more bytes:
Just replace the first underscore in the code with '-+'[!$m[2]].

If I try 67 in echo strlen($n=decbin($argv[1]))-!!strpos($n,'01').'-+'[!$n[2]].strpos(strrev($n),49); it gives me back 6+0 which is 65

@JörgHülsermann: 67 has no solution; behaviour for no solution is undefined; so it does not matter what it prints for 67.

PHP ,117 Bytes
if(preg_match("#^(1+|(10*1))0*$#",$b=decbin($k=$argv[1]),$t))echo($l=strlen($b))-($t[2]?1:0).",",$l+~strrpos($b,"1");

Extended version 4 Cases
$l=strlen($b=decbin($k=$argv[1]));
// Case 1: n=2(n-1)=n+n or n=n*(2-1)=2n-n
if(preg_match('#^100*$#',$b))echo($l-2).'a+'.($l-2).':'.$l.'a-'.($l-1);
// Case 2: n-m
elseif(preg_match('#^1+0*$#',$b)){echo $l.'b-',strpos($b,"0")?$l-strpos($b,"0"):0;}
// Case 3: n+m
elseif(preg_match('#^10*10*$#',$b))echo ($l-1).'c+',$l-strrpos($b,"1")-1;
else echo "Nothing";

the short version union Case 1 and 3 and makes a Difference to Case 3 and in both versions Case 4 gives no output.

source: Stack Exchange

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

sort: votes


text:
Phonemic Abugida
Characters
Let’s call these Unicode characters English IPA consonants:
bdfhjklmnprstvwzðŋɡʃʒθ

And let’s call these Unicode characters  English IPA vowels:
aeiouæɑɔəɛɜɪʊʌː

(Yes, ː is just the long vowel mark, but treat it as a vowel for the purpose of this challenge.)
Finally, these are primary and secondary stress marks:
ˈˌ

Note that ɡ (U+0261) is not a lowercase g, and the primary stress marker ˈ (U+02C8) is not an apostrophe, and ː (U+02D0) is not a colon.

Your task
Given a word, stack the vowels on top of the consonants they follow, and place the stress markers beneath the consonants they precede. (As the question title hints, such a writing system, where consonant-vowel sequences are packed together as a unit, is called an abugida.) Given the input ˈbætəlʃɪp, produce the output:
æə ɪ
btlʃp
ˈ

A word is guaranteed to be a string of consonants, vowels, and stress marks, as defined above. There will never be consecutive stress marks, and they will always be placed at the start of the word and/or before a consonant.

Test cases
There may be consecutive vowels. For example, kənˌɡrætjʊˈleɪʃən becomes
      ɪ
ə  æ ʊeə
knɡrtjlʃn
  ˌ   ˈ

If a word starts with a vowel, print it on the “baseline” with the consonants: əˈpiːl becomes
 ː
 i
əpl
 ˈ

A test case with an initial, stressed vowel: ˈælbəˌtrɔs becomes
  ə ɔ
ælbtrs
ˈ  ˌ

A long word: ˌsuːpərˌkaləˌfrædʒəˌlɪstɪˌkɛkspiːæləˈdoʊʃəs becomes
               æ
ː              ː ʊ
uə aə æ əɪ ɪɛ  iəoə
sprklfrdʒlstkkspldʃs
ˌ  ˌ ˌ   ˌ  ˌ    ˈ

A nonsense example with an initial diphthong, lots of vowel stacking, and no stress markers: eɪbaeioubaabaaa becomes
 u
 o
 i a
 eaa
ɪaaa
ebbb

Reference implementation
Your program should produce the same output as this Python script:
consonants = 'bdfhjklmnprstvwzðŋɡʃʒθ'
vowels = 'aeiouæɑɔəɛɜɪʊʌː'
stress_marks = 'ˈˌ'

def abugidafy(word):
    tiles = dict()
    x = y = 0

    is_first = True
    for c in word:
        if c in stress_marks:
            tiles[x + 1, 1] = c
        elif c in consonants or is_first:
            y = 0
            x += 1
            tiles[x, y] = c
            is_first = False
        elif c in vowels:
            y -= 1
            tiles[x, y] = c
            is_first = False
        else:
            raise ValueError('Not an IPA character: ' + c)

    xs = [x for (x, y) in tiles.keys()]
    ys = [y for (x, y) in tiles.keys()]
    xmin, xmax = min(xs), max(xs)
    ymin, ymax = min(ys), max(ys)

    lines = []
    for y in range(ymin, ymax + 1):
        line = [tiles.get((x, y), ' ') for x in range(xmin, xmax + 1)]
        lines.append(''.join(line))
    return '\n'.join(lines)

print(abugidafy(input()))

Try it on Ideone.
Rules

You may write a function or a full program.
If your program has a Unicode character/string type, you can assume inputs and outputs use those. If not, or you read/write from STDIN, use the UTF-8 encoding.
You may produce a string containing newlines, or a list of strings representing rows, or an array of Unicode characters.
Each row of output may contain any amount of trailing spaces. If you produce a string, it may have a single trailing newline.
Your program should produce the correct output for arbitrarily long words with arbitrarily long vowel chains, but may assume that the input word is always valid.
If there are no stress markers, your output may optionally include a final empty row (containing nothing, or spaces).
The shortest answer (in bytes) wins.

Poor ɜ,  you left it out :-) And British will complain about their ɒ

Oops, I did! I added ɜ, so this should be a full General American vowel set now.

Are occurrences of any of these characters to only count as one byte in whichever language is used regardless of their code base in order to strike balance between competing golfing languages or is part of the challenge, in your opinion, to find which language may actually perform it in least bytes, period?

Is there a maximum number of vowels after a consonant that our program should recognize? If not add a test case like biiiiiiiiiiiʒ (As in "not the bees")

Are functions allowed?

@JonathanAllan The latter; Unicode I/O is part of the challenge. I'll add a note about that.

Also, I'm guessing "oodles" would have the second "o" placed above the first?

That’s exactly right. I’ll add a case for that.

NARS2000 APL, 138 bytes
⍉⌽⊃E,⍨¨↓∘' '¨∨/¨∊∘M¨E←(1+(W∊M←'ˌˈ')++\W∊'bdfhjklmnprstvwzðŋɡʃʒθ')⊂W←⍞

You can remove the initial ⍞← as output is implied. Also, byte count should be exactly twice the character count, as per this. So this should be 138 bytes.

Python, 222 bytes
(202 characters)
import re
def f(s):y=[w[0]in'ˈˌ'and w or' '+w for w in re.split('([ˈˌ]?[bdfhjklmnprstvwzðŋɡʃʒθ]?[aeiouæɑɔəɛɜɪʊʌː]*)',s)[1::2]];return[[x[i-1:i]or' 'for x in y]for i in range(max(len(w)for w in y),0,-1)]

Returns an array of unicode characters with an array for each row (containing single spaces for each space required)
Not sure where one can get decent output online yet (and I haven't even got the tools to test it properly here either).
I have loaded a version to ideone that just uses English consonants and vowels with , and . as stress marks, where I have fudged the test cases to conform.

JavaScript (ES6), 181 bytes

f=
s=>(a=s.match(/[ˈˌ]?.[aeiouæɑɔəɛɜɪʊʌː]*/g).map(s=>/[ˈˌ]/.test(s)?s:` `+s)).map(s=>(l=s.length)>m&&(t=s,m=l),m=0)&&[...t].map(_=>a.map(s=>s[m]||` `,--m).join``).join`
`
;
<input oninput=o.textContent=f(this.value)><pre id=o>

Go, 609 bytes
import."strings"
type P struct{x,y int}
func M(s[]int)(m,n int){for _,e:=range s{if e<=m{m=e};if e>=n{n=e}};return}
func f(s string)(L string){T,x,y,F,R:=make(map[P]rune),0,0,1>0,ContainsRune
for _,r:=range s{if R("ˈˌ",r){T[P{x+1,1}]=r}else if R("bdfhjklmnprstvwzðŋɡʃʒθ",r)||F{y=0;x++;T[P{x,y}],F=r,1<0}else if R("aeiouæɑɔəɛɜɪʊʌː",r){y--;T[P{x,y}],F=r,1<0}}
var u,v[]int
for k:=range T{u,v=append(u,k.x),append(v,k.y)}
for y,Y:=M(v);y<Y+1;y++{o:=[]string{}
for x,X:=M(u);x<X+1;x++{if r,ok:=T[P{x,y}];ok{o=append(o,string(r))}else{o=append(o," ")}}
L+=TrimPrefix(Join(o,"")," ")+"\n"}
return}

Attempt This Online!
A direct port of the reference implementation.
Ungolfed Explanation
// map of x-y coords to a character
type tile map[P]rune

func (t tile) Xs() (o []int) {
	for k := range t {
		o = append(o, k.x)
	}
	return
}
func (t tile) Ys() (o []int) {
	for k := range t {
		o = append(o, k.y)
	}
	return
}

// coordinate pair
type P struct{ x, y int }

func min[T int](s []T) T {
	var m T
	for _, e := range s {
		if e <= m {
			m = e
		}
	}
	return m
}
func max[T int](s []T) T {
	var m T
	for _, e := range s {
		if e >= m {
			m = e
		}
	}
	return m
}

func f(s string) string {
	C, V, S := "bdfhjklmnprstvwzðŋɡʃʒθ", "aeiouæɑɔəɛɜɪʊʌː", "ˈˌ" // constant strs
	tiles := make(tile)                                          // the actual map
	x, y := 0, 0                                                 // (x0,y0) is the leftmost center
	isFirst := true                                              // is this character the first of a line?
	for _, r := range s {                                        // for each char...
		if strings.ContainsRune(S, r) {                          // if it's stress...
			tiles[P{x + 1, 1}] = r                               // put it underneath the next syllable
		} else if strings.ContainsRune(C, r) || isFirst {        // if it's a consonant or the first letter...
			y = 0
			x++
			tiles[P{x, y}] = r                                   // place on the baseline
			isFirst = false
		} else if strings.ContainsRune(V, r) {                   // if's a vowel...
			y--
			tiles[P{x, y}] = r                                   // place 1 above the baseline at the current x
			isFirst = false
		}
	}

	// get the ranges for outputting into a string
	xs, ys := tiles.Xs(), tiles.Ys()
	xmin, xmax := min(xs), max(xs)
	ymin, ymax := min(ys), max(ys)

	lines := []string{}
	for y := ymin; y < ymax+1; y++ {             // for each vowel at height y...
		line := func() (o []string) {
			for x := xmin; x < xmax+1; x++ {     // for each syllable on that vowel height...
				if r, ok := tiles[P{x, y}]; ok { // get the char
					o = append(o, string(r))
				} else {
					o = append(o, " ")           // use a space if there is no vowel there
				}
			}
			return
		}()
		lines = append(lines, strings.TrimPrefix(strings.Join(line, ""), " ")) // add to the output
	}
	return strings.Join(lines, "\n") // return the string
}

Attempt This Online!

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

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


text:
Distance to four
This challenge is based on this video. I recommend that you watch it before trying this challenge.
First we define a function.  This function (OEIS) takes a integer n as input and outputs the number of letters in the English representation of n (without spaces or hyphens).  For example "three" has 5 letters so 3 maps to 5.
As demonstrated in the video starting with any number repeating this process will eventually result in a four, which will map to itself forever.
Here is a crude directed graph showing the orbits of the numbers less than 16:
  12 11
    \|
15 2 6 1 10 14 13
  \ \|/ /  /  /
   7 3-/  8--/
    \|   /
 9 0 5--/
  \ \|
   \-4

Your challenge is to determine the number of steps that a number will take (or the number of times this function must be applied to a number) before reaching four (i.e. the level on the directed graph pictured).
Forming english numbers
Here is a brief explanation of how one should form english words for this challenge:
The numbers one through nineteen are:
one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen
For numbers greater than nineteen the process is as follows:
If the number has a hundreds place begin with the name of digit in the hundreds place and "hundred".
e.g.
100 -> "onehundred"

If the remainder is less than twenty append the remainder's English representation.
e.g.
714 -> "sevenhundredfourteen"

Otherwise if the tens digit is not zero append the proper representation:
2-> twenty
3-> thirty
4-> forty
5-> fifty
6-> sixty
7-> seventy
8-> eighty
9-> ninety

e.g.
470 -> "fourhundredseventy"

Finally if there is a one's digit append its representation
e.g.
681 -> "sixhundredeightyone"

Further Stipulations

For numbers greater than one hundred you should leave out the "and" when counting the number of letters. For instance 577 is "fivehundredseventyseven" which has 23 letters.
Your program must accept all integers greater than 0 and less than 1,000 as input via standard methods.
Your program must output the number of steps required to standard output methods.
This is codegolf so the solution with the fewest bytes wins.

Test cases
1 -> 3
4 -> 0
7 -> 2
23 -> 5
577 -> 6
600 -> 4

Related I thought this was a dupe, but I can't find it.

What happened to "and"? Or rather, why leave out and?!

@JonathanAllan cuz 'Murica

JavaScript (ES6), 106 bytes
f=(n,a="03354435543668877998")=>n-4&&1+f(7*(n>99)-(-a[n/100|0]-(a[n%=100]||a[n%10])-"0066555766"[n/10|0]))

Strings seem to be the best way to encode the length, despite the numeric conversion overhead.

Gosh, that's almost exactly what my (nearly-posted) answer looked like, only 11 bytes shorter.

@ETHproductions Good thing I golfed 16 bytes off before posting it then!

Python, with num2words, 97 113 115 94 93 92 bytes
+16 bytes (forgot the hyphenation that num2words applies which does not actually change the results of any of the test cases, even though 23 and 577 each have a hyphen)
+2 bytes (forgot to include f= although recursive)
-20 bytes (use re)
-8 bytes thanks to @Wheat Wizard (use ~, replace n!=4 with n-4, and ...one line import >_<)
-1 byte thanks to @Cyoce (space from 4 and)

import re,num2words as w
f=lambda n:n-4and-~f(len(re.sub('\W|and','',w.num2words(n))))

Just counts up the number of steps; works for huge and negative integers too (\W finds the spaces, commas and hyphens in the num2words result):
>>> for test in (1,4,7,23,577,600,-1*2**96,3**96):
...     print('test: {0}  ->  {1}'.format(test, f(test)))
...
test: 1  ->  3
test: 4  ->  0
test: 7  ->  2
test: 23  ->  5
test: 577  ->  6
test: 600  ->  4
test: -79228162514264337593543950336  ->  4
test: 6362685441135942358474828762538534230890216321  ->  5

Here is that last case, step by step:
sixquattuordecillionthreehundredsixtytwotredecillionsixhundredeightyfiveduodecillionfourhundredfortyoneundecilliononehundredthirtyfivedecillionninehundredfortytwononillionthreehundredfiftyeightoctillionfourhundredseventyfourseptillioneighthundredtwentyeightsextillionsevenhundredsixtytwoquintillionfivehundredthirtyeightquadrillionfivehundredthirtyfourtrilliontwohundredthirtybillioneighthundredninetymilliontwohundredsixteenthousthreehundredtwentyone
fourhundredfiftyone
nineteen
eight
five

Don't you need a f= before your lambda function

@WheatWizard I do indeed, and I've done that before!

If you import re and use re.sub("and|-| ","",num2words(n)) instead of num2words(n).replace('and','').replace(' ','').replace('-','') you can save a couple of bytes.

@WheatWizard I was already doing that :)

Try import re,num2words as r instead of the two different statements.

n-4 is the same thing as n!=4

@WheatWizard num2words is w, re is still re - note that both the module and function are called num2words

Ok last one, and 1+ can be replaced with and-~ to save one byte

I'm glad I'm not the only one who forgets the f= for their recursive lambdas.

n-4 and can become n-4and

Pyth - 54 bytes
Will try to refactor.
KjC"Y©åláóê¤"Ttl.u?<NyT@KNs+V@LKJ_jNT[Z@jC"Ckg"ThtJ7

Test Suite.

Java, 556 295 bytes
Thanks to @KevinCruijssen for saving 261 bytes
  void int(n) {int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6};int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1;while(n>0){if(n/100>0)c+=(s[n/100]+7);else {if(n>0&n<25){c+=s[n];break;}else{c+=s[(n/10)+22];}}n=n%t;t=t/10;}while(c!=4){v++;c=s[c];}System.out.print(v);}

Ungolfed:
  void int(n) {

    int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6};
     int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1;
         while(n>0){
            if(n/100>0)
                c+=(s[n/100]+7);
            else {if(n>0&n<25){
                c+=s[n];
            break;
            }
            else{
                c+=s[(n/10)+22];

            }
            }
            n=n%t;
            t=t/10;
        }

        while(c!=4)
        {
            v++;
        c=s[c];
        }
System.out.print(v);
}

I think you have a mistake in your code, because s++ isn't possible on a String-array.. :S

@KevinCruijssen I declare S(counter) as a INT and STRING too....java automatically decide it is an INT.

Well, if I run your code in ideone or my Eclipse IDE it fails because you have two s.. Btw, you can golf your code by quite a large amount like this: int c(int n){int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,8,8,6,9,9,11,10,6,5,5,5,7,6,6},c=0,t=(int)Math.pow(10,(int)Math.log10(n)),x=1;while(n>0)if(n/100>0)c+=s[n/100]+7;else{if(n>0&n<25){c+=s[n];break;}else c+=s[(n/10)+22];}n%=t;t/=10;}for(;c!=4;x++,c=s[c]);return x;}

I am shocked......what happen to my code and thanks @KevinCruijssen..and i am correcting it...Thanks again.

Np :) I think it might be golfed some more somehow without using the if-else and break in there (but I'll leave that to someone else), but your initial code was a great base for tackling the challenge, so +1 from me.

Mathematica, 89 bytes
Length@FixedPointList[StringLength@StringReplace[IntegerName@#,{" "->"","-"->""}]&,#]-2&

Typical Mathematica: built-in functions good, long function names bad. FixedPointList applies its first argument (a function) to the second argument repeatedly until the answer doesn't change, listing all results; the results include the original input and two copies of the repeated output, hence the -2 at the end. Mathematica's built-in IntegerName contains spaces and hyphens, so we need to get rid of those by hand.
Annoyingly, IntegerName's output contains the character "‐" (Unicode #8208) rather than normal hyphens; that's why this submission is 89 bytes rather than 88. (And I couldn't precede the code above with four spaces and have it accept the Unicode character—any help?—so the above code won't work exactly right if cut and pasted.)

Python 2.7, 344 216 208 bytes:
x=`input()`;c=0;y=lambda v:dict(zip(range(0,10),[0]+v));l=[3,3,5,4,4,3,5,5,4];d=y(l);e=y([3,6,6,6,5,5,7,7,6]);f=y([i+7for i in l])
while x!='4':x=`sum([q[int(r)]for q,r in zip([d,e,f],x[::-1])])`;c+=1
print c

Does not use any external libraries unlike other Python answer. Takes input through stdin and outputs to stdout.
Repl.it with All Test Cases!
Explanation
First creates 3 dictionaries with each one pairing the length of the English word representations of each number to the number it represents in the closed interval [1,9] in the ones, tens, and hundreds place, respectively. For example, the first entry in dictionary d is 1:3 as 1 is spelled one in English and has 3 letters.
Then, each digits place in some string input x is assigned to its corresponding dictionary, after which each number in each place is matched up with its value in the corresponding dictionary. For instance, suppose the input number was 23. The 20 in the tens place would be paired with dictionary e, in which it is matched with 6, and the 3 in the ones place would be paired with dictionary d, in which it is matched with 5. These matched digits are then added together to represent the length of the English representation of the number, which is assigned to x as a string and, as long as x!='4', the while loop goes on, incrementing c by 1 each time to represent the number of steps taken thus far. Therefore, 23 would correspond to 11, which would in turn correspond to 6 which would turn to 3 and then to 5 and finally to 4, resulting in 5 total steps.
Finally, once the loop finishes, c is output to stdout to represent the "Distance to Four", which in this case would be 5.


text:
Solve Grid-Tangram
The Tangram is a dissection puzzle made from seven shapes: Five differently sized triangles, a parallelogram and a square. Given a shape, the goal is recreating the shape using all the pieces and without overlapping. There are obviously infinitely many ways to arrange this set of pieces in the plane. An interesting subset are the
Grid Tangrams
We can draw the "standard" Tangram square into a bigger square which is subdivided by a grid into 16 smaller squares.  Grid tangrams are just shapes made up of the tangram pieces, such that all vertices of the pieces are on the grid points.

These are the kinds of Tangram puzzles we want to consider in this challenge, as they are probably easier to handle than the more general ones.
As a side note: The Chinese mathematicians Chuan-Chin Hsiung and Fu Traing Wang proved in 1942 that there are only 13 convex tangrams. They first showed that the problem can be reduced to grid tangrams, and then used some combinatorial and geometric arguments. These are all of those 13:

Challenge
Given a solvable grid tangram, output a dissection of the grid tangram into the seven tangram pieces.
IO
A tangram is given as a black and white image (the shape is in black, background in white), with both sides multiples of 50px. The grid has a width of exactly 50px. The grid lines are parallel to the sides of the image.
EDIT: The image can be accepted as input and returned as output in any convenient raster image format like PNG,TIFF,PBM etc. but a representation as a binary 2d array or string or matrix is acceptable.
The output should again have the same size and should have again the same shape, but with each piece a different colour, or alternatively with white lines separating all the pieces. It is worth noting that the non rectangular quadrangle can be flipped.
The pixels on the border of the pieces do not exactly have to match the one on the shape, also if there are aliasing effects or other fuzz this is still ok.
Example Input and Output:

Examples:

Possible solutions:

image processing is an entirely unnecessary hurdle in this challenge. I'd find it much more appealing if you just specified the input as a small binary array.

I did consider that when the challenge was in the sandbox, but the majority thought that an input and output that is "human readable" is more appealing. But you have enough room to sample the images yourself.

I would've been more interested if, as flawr said, there was a more  flexible input format.

What do you consider as the big hurdle here? I think you can easily read, e.g. every 25th pixel, with an offset of 12 pixels to get e.g. a binary image with one pixel per "section". As I see it, reading the input is the smallest of all the problems, as the input is strictly defined. The real challenge is the computation itself.

I think that's the very objection: If reading the image isn't part of "the real challenge," why is it part of the task at all? It's tedious and adds a lot of bytes—and that's assuming someone's language of choice can even read images.

As I said, that was discussed when it was in the sandbox. But I doubt that it does add a lot of bytes, as the task itself is a lot more difficult.

I was one of the people who recommended that the input and output be the way they are, and I made that recommendation because this is, in my opinion, the most natural and fitting way to present a Tangram challenge. Any form of input/output would take a significant number of bytes, so I don't think that's really an issue here.

I agree with Elendia. The only problem with graphical I/O is that it could limit languages that don't have graphics facilities. That said, PBM and PGM are so close to ASCII art that there is no real problem, IF it is the case that people are aware of such formats. https://en.wikipedia.org/wiki/Netpbm_format

@LevelRiverSt That is a good point, I think it would be totally accepptable to use those formats or even e.g. a 2d array/string of zeros and ones.

BBC BASIC, 570 514 490 bytes ASCII
Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html
435 bytes tokenised
Full program displays an input from L.bmp on the screen, then modifies it to find a solution.
*DISPLAY L
t=PI/8q=FNa(1)
DEFFNa(n)IFn=7END
LOCALz,j,p,i,c,s,x,y,m,u,v
F.z=0TO99u=z MOD10*100v=z DIV10*100ORIGINu,v
F.j=0TO12S.4p=0F.i=j+3TOj+9S.2c=9*COS(i*t)s=9*SIN(i*t)p=p*4-(POINT(c,s)<>0)*2-(POINT(9*c,9*s)<>0)N.
m=n:IFn=5A.(43A.p)=0p=0m=7
IF(ASCM."??O|(C",n)-64A.p)=0THEN
F.i=-1TO0GCOL0,-i*n:c=99*COS(j*t)s=99*SIN(j*t)y=402/3^m MOD3-1MOVE-c-s*y,c*y-s:x=n<3MOVEc*x-s*x,s*x+c*x:x=2778/3^m MOD3-1y=5775/3^m MOD3-1PLOT85-32*(n MOD6>3),c*x-s*y,s*x+c*y:IFi q=FNa(n+1)ORIGINu,v
N.
ENDIF
N.N.=0

Explanation
Note that in BBC basic a distance of 1 pixel = 2 units, so the 50x50 pixel grid becomes a 100x100 grid.
We use a recursive function to place the 2 large triangles, medium triangle, square and parallelogram into the shape. The earlier shape in the list is drawn before the next recursive call is made. if a recursive call returns without finding a solution, the earlier shape is overdrawn in black and a new position of the earlier shape is tried.
Once these five shapes are drawn, placing the two small triangles is just a formality. It is necessary to draw one of them though, in order to distiguish them if they share a common edge. We only colour one of the two small triangles. The other is left in natural black.
Placing of each shape is attempted at different x,y coordinates and in 4 different rotations. To test if there is free space to draw a shape we use the template below, with 45 degree angles. The rotations are made about the * and the 8 pixels tested are in 2 semicircles of radius 9 and 81 units and fall on radiating lines at odd multiples of 22.5 degrees to the x and y axes.
For a large triangle all 8 spaces are required to be clear. For other shapes only some of the cells must be clear so a mask is applied.
+----+----   Shape             Mask HGFEDCBA Mask decimal
|\ E/|\G /
| \/F|H\/    1,2. Large triangle    11111111    -1
|C/\ | /     3. Med triangle        00001111    15
|/ D\|/      4. Square              00111100    60
+----*       5. Parallelogram       11101000   -24
|\ B/        6. Small triangle      00000011     3
|A\/         7. Parallogr reversed  00101011    43
| /          Note: reversed parallelogram is checked/drawn at recursion depth n=5
|/           with a special check, but the coordinates are encoded as m=7.

Once it is established that a shape will fit, it must be drawn. If it is a triangle it is plotted with PLOT 85, if it is a parallelogram, the number is 32 higher (note that for PLOT purposes we consider a square a special parallelogram). In either case 3 consecutive vertices must be given. The second vertex is the origin of the shape (marked * in the above table) except in the case of the large triangle, where (prior to rotation) it is -1,-1. The other 2 vertices can have x and y coordinates of -1,0 or 1 which are extracted from base 3 encoded numbers, then scaled by 99 and rotated as necessary by transformation with c and s.
Ungolfed code
  *DISPLAY L
  t=PI/8                                          :REM Constant 22.5 degrees.
  q=FNa(1)                                        :REM Call function, return dummy value to q
  END                                             :REM End the program gracefully if no solution. Absent in golfed version.

  DEFFNa(n)                                       :REM Recursive function to place shapes.
  IFn=7END                                        :REM If n=7 solution found, end program.
  LOCALk,z,j,p,i,c,s,x,y,m,u,v                    :REM declare local variables for function.
  k=ASCMID$("??O|(C",n)-64                        :REM Bitmasks for big tri, big tri, med tri, sq, normal paralellogram, small tri.
  FORz=0TO99                                      :REM For each point on the grid
    u=z MOD10*100:v=z DIV10*100                   :REM calculate its x and y coordinates relative to bottom left of screen
    ORIGINu,v                                     :REM and set the origin to this point.
    FORj=0TO12STEP4                               :REM For each rotation 0,90,180,270deg
      p=0                                         :REM assume no non-black pixels found
      FORi=j+3TOj+9STEP2                          :REM test angles of 3,5,7,9 times 22.5 deg anticlockwise from right x axis.
        c=9*COS(i*t)                             :REM Coords of test points at radius ll
        s=9*SIN(i*t)
        p*=4                                      :REM Leftshift any existing data in p
        p-=(POINT(c,s)<>0)*2+(POINT(9*c,9*s)<>0)  :REM and check pixels at radius 11 and 99.
      NEXT
      m=n                                         :REM The index of the shape to plot normally corresponds with recursion depth n.
      IF n=5 AND (43ANDp)=0 p=0:m=7               :REM If n=5 check if a reverse parallelogram is possible (mask 43). If so, clear p and change m to 7.
      REM                                         :REM Check p against mask k, if the shape fits then...
      IF (k ANDp)=0 THEN
        FOR i=-1 TO 0                               :REM draw the shape in colour, and if deeper recursions prove unsuccesful, redraw it in black.
          GCOL0,-i*n                                :REM Colour is equal to n.
          c=99*COS(j*t)                             :REM Set parameters c and s for scaling by 99
          s=99*SIN(j*t)                             :REM and rotation by 0,90,180 or 270 as appropriate.
          x=-1                                      :REM For vertex 1, x=-1 always.
          y=402/3^m MOD3-1                          :REM Lookup y value for vertex 1.
          MOVEc*x-s*y,s*x+c*y                       :REM Use c and s to transform the vertex and move to it.
          x=n<3                                     :REM For vertex 2, coords are 0,0 except for large triangle where they are -1,-1
          y=x                                       :REM in BBC BASIC, TRUE=-1
          MOVEc*x-s*y,s*x+c*y                       :REM Use c and s to transform the vertex and move to it.
          x=2778/3^m MOD3-1                         :REM Lookup x and y value for vertex 3.
          y=5775/3^m MOD3-1                         :REM PLOT85 uses last 2 points + specified point to make triangle, PLOT85+32 makes paralelogram (or square.)
          PLOT85-32*(n MOD6>3),c*x-s*y,s*x+c*y      :REM Use c and s to transform the vertex and draw shape.
          IFi q=FNa(n+1):ORIGINu,v                  :REM If i=-1 recurse to next level. If it fails, reset the origin before replotting this level's shape in black.
        NEXT
      ENDIF
    NEXT
  NEXT
  =0                                                :REM Dummy value to return from function

Output
This is a montage of the solutions found by the program for the test cases. Use of 99 instead of 100 for golfing reasons leaves some small black gaps. As the shapes are redrawn during the searches, it can take a few seconds to run for some cases, and is quite fascinating to watch.

Wow, I'm impressed. Now I'd love to see a video of it in action! =)


text:
Where can the cannon go?
Introduction
The game of xiangqi, also known as Chinese chess, is a chess-like game
popular in China, Vietnam, Taiwan, and other East Asian countries. The colours
of the two sides in xiangqi are red and black. There are seven pieces in
xiangqi: the general (G), advisor (A), elephant (E), horse (H), chariot
(R), cannon (C), and soldier (S). For the purposes of this challenge,
uppercase pieces are considered red and lowercase pieces black. Most of these
pieces have a rough equivalent in Western chess, but there is one completely unique piece: the cannon.
The cannon moves like a rook in chess or a chariot in xiangqi (moving any
number of spaces on either the X or Y axes), but cannot attack this way.
Instead, it attacks by jumping along the X or Y axes (the same way it moves)
over one piece of any colour (friend or foe) and landing on the
opposite-coloured piece, which it then captures. Note that like all chess and
xiangqi pieces, cannons cannot capture pieces of their own colour.
For example, in the following diagram, the spaces to which the cannon (C)
can move are marked with *, and those to which it can jump and capture
are marked with X, assuming that there is a black/lowercase piece there.
....X....
.........
.........
....h....
....*....
****C**aX
....E....
....X....
....g....
....R....

Challenge
Write a program or function that, given a xiangqi board and the coordinates of
a cannon on that board as input, outputs a list of coordinates to which the
cannon can move or jump.
The format for all I/O is flexible.
Acceptable formats for the xiangqi board include a newline-separated string, a
list of strings, or a string with any other separator not in aceghrsACEGHRS..
You may assume the board will always be 9x10, the size of a xiangqi board.
The contents of the board itself will consist of a number of periods (.),
representing empty points on the board, and characters representing pieces. The
piece-to-character mapping is as follows:
A -> advisor
C -> cannon
E -> elephant
G -> general
H -> horse
R -> chariot
S -> soldier

Uppercase letters represent red pieces, and lowercase letters represent black pieces. Characters not listed here (i.e. not in aceghrsACEGHRS.) will not appear in the board.
The format of the input coordinate is flexible, and is not required to match
the format of the output coordinates. It can be a list of two integer elements,
a 2-tuple, two numbers with any separator, or two characters, for example. It
may also be either 0-indexed or 1-indexed. You may assume that the coordinate
on the board will always resolve to a cannon (C or c).
The coordinates to which the cannon can jump and move must appear in the same
list in output; distinction between the two is not necessary. Acceptable
formats for any individual output coordinates are the same as those for the
input coord. The coordinates may be newline-separated, output as a list, or any
other representation. No particular order is necessary; the order does not even
have to be deterministic.
Note that jumps onto a piece of the same colour (case) of the cannon are not
legal, and thus cannot appear in the output.
Test cases
Note that not all of the test cases are possible xiangqi positions.
Input board
Input coordinate (0-indexed)
List of output coordinates

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

.........
.....G...
.........
.........
.....e...
.........
.........
h..R.c..S
.....a...
.........
(5, 7)
[(4, 7), (6, 7), (7, 7), (5, 6), (5, 5), (5, 1)]

..s......
..A...e..
.........
EACCcsh.H
..r......
.....S...
......s..
....C....
..g......
(2, 3)
[(2, 0), (2, 2), (4, 3), (2, 8)]

rheagaehr
.........
.c.....c.
s.s.s.s.s
.........
.........
S.S.S.S.S
.C.....C.
.........
RHEAGAEHR
(7, 7)
[(2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (8, 7), (7, 0), (7, 3), (7, 4), (7, 5), (7, 6), (7, 8)]

Scoring
This is code-golf, so the shortest answer (in bytes) wins. Happy golfing!

+1 for Xiangqi. It is an awesome game, that I had the opportunity to learn from my colleagues when I worked for a Chinese company. The general feel is just like playing chess (keep a sharp eye for defense but play aggressively) but the tactics are different (it's good to bring the chariots out early, whereas it's bad to bring the rooks out early in chess.) https://en.wikipedia.org/wiki/Xiangqi

@LevelRiverSt it's much less technical than chess and feels like a videogame with a different strategic feel. I like it!

Seems there may be no king, but can there be more than possible piece?

Pip, 112 + 1 = 113 bytes
Takes input as command-line arguments: the two coordinates, followed by the 10 lines of the board. Coordinates are 0-based. Outputs coordinates like 67 77, with a newline between the same-row list and the same-column list. One byte added for the -s flag.
g@>:2P(f:{Ya@bQ'C?X^z;X^AZa@b:'@aR`\.*@\.*`{aR'.s}Ry.`\.*\w *@`s._@>1R`@ *\w\.*`.y_@<v.s@*s}g@ba).ba.(f;J(Zga)b)

Try it online!
Explanation of somewhat ungolfed version
g@>:2
f:{
 Y a@bQ'C ? `[a-z]` `[A-Z]`
 a@b:'@
 aR:`\.*@\.*` {aR'.s}
 aR:y.`\.*\w *@` s._@>1
 aR:`@ *\w\.*`.y _@<v.s
 a@*s
}
P (f g@b a).b
a.(f; J(Zg)@a b)

By default, Pip reads command-line args into the list g. It also stores the first five arguments in the variables a through e. Our first two arguments, a and b, are the coordinates of the cannon; g contains the coordinates followed by the rows of the board. To get just the board in g, we slice it from index 2 onward and assign back to g (g@>:2).
Now we define a function f. This function takes two arguments: a string representing a row or column of the board, and the index of the cannon in that string. These arguments are available inside the function as a and b. The function will return a list of all indices that represent spots the cannon can move to or capture.
First, we test whether a@b is C or c. If it's C, we're going to want the regex [a-z] to match the pieces it can capture. If it's c, the regex is [A-Z]. (The golfed code generates these regexes from the builtin variables for lower- and uppercase alphabet.) We Yank the appropriate regex into the y variable.
We change the cannon's character in the string to @ (to distinguish it from other cannons in the same row/column).
Next comes a series of regex replacements, which will change every place the cannon can go to a space character. The first regex \.*@\.* matches @ surrounded by any number of periods, all of which represent empty spots to which the cannon can move. The replacement uses a callback function {aR'.s} to change all the periods to spaces.
The next regex matches a piece the cannon can capture: either [a-z] or [A-Z] (depending on which one was yanked into y earlier) followed by \.*\w *@ (any number of periods, one letter, any number of spaces, and @). This will match a string like h..R @ (provided the cannon was C). The callback function s._@>1 slices the first character off and prepends a space.
The third regex is similar, but matches a capturable piece after the cannon rather than before it.
Finally, the function returns a@*s, using the find-all operator to get a list of the indices of all spaces.
We now call f on the cannon's row and again on the cannon's column. The row's string is g@b, with the cannon's index inside the string being a. The function returns a list of column numbers, to each of which we append the row number b. When the list is printed, the -s flag puts a space between the coordinate pairs.
To get the column, we use the Zip operator to transpose g, select index a, and Join the resulting list of characters into a string. The cannon's index within this string is b. The function returns a list of row numbers, to each of which we prepend the column number a. This list, being the last expression in the program, is autoprinted.
(In case anyone was wondering, the expression separator ; is there to force J to parse as a unary operator rather than binary.)

Python3, 309 bytes:
def f(t,b):
 q=[(*t,0,b[t[0]][t[1]],*i)for i in[(0,1),(0,-1),(1,0),(-1,0)]]
 while q:
  x,y,d,c,X,Y=q.pop(0)
  if 0<=(j:=x+X)<len(b)and 0<=(k:=y+Y)<len(b[0])and d<2:
   if'.'==(S:=b[j][k])and d==0:yield(j,k)
   if'.'!=S and S.isupper()!=c.isupper()and d:yield(j,k);d=2
   q+=[(j,k,[d,1][d<2 and'.'!=S],c,X,Y)]

Try it online!

Python 2, 238 bytes
def f(b,r,c,R=range):
 for K in[[(i,c)for i in I]for I in R(r+1,10),R(r)[::-1]]+[[(r,j)for j in J]for J in R(c+1,9),R(c)[::-1]]:
  p=0
  for i,j in K:
	B=b[i][j];Z='.'<B*p;p+='.'<B
	if(p<1)+Z*((b[r][c]<'c')!=('a'>B)):print i,j
	if Z:break

Try it online!
Ungolfed (301 bytes)
def g(a,b,I):
 p=0
 for i,j in I:
  B=b[i][j]
  if p:
   if'A'>B:continue
   if('a'>B)!=a:print(i,j)
   break
  p='.'<B
  if p<1:print(i,j)
def f(b,r,c):
 a=b[r][c]<'c'
 for I in[range(r+1,10),range(r-1,-1,-1)]:g(a,b,[(i,c)for i in I])
 for J in[range(c+1,9),range(c-1,-1,-1)]:g(a,b,[(r,j)for j in J])

Try it online!

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


text:
Print a number in it's text format
This is a classic one.
You get a number from the keyboard from 0 to 1000(including) and must print it in text form.
Examples:
Input:5
Output:five

Input:23
Output:twenty three

Input:999
Output:nine hundred ninety nine


text:
Decipher Neurotic Frogs
Decipher Neurotic Frogs
Now that Puzzling.SE has finally cracked my amphibian-obsessed cipher, let's write a program or function to decrypt it!
(If you want to look at the puzzle before having it spoiled for you, click the above link now.)

How the cipher works
In Neurotic Frogs Ought To Relax In Mud Baths ("Neurotic Frogs" for short), every letter is encrypted as one or two words:

The length of a non-italicized word represents a letter.

neurotic => 8 letters => H
frogs => 5 letters => E
perpendicular => 13 letters = M

A word that contains italics modifies the following word, adding 10 if the italicized word was odd in length or 20 if the italicized word was even in length. Any or all of the word may be italicized. An italicized word is always followed by a non-italicized word.

*o*ught to => odd, 2 => 12 => L
lo*u*nging calms => even, 5 => 25 => Y

Every word of plaintext corresponds to a sentence of ciphertext, and every sentence of plaintext corresponds to a paragraph of ciphertext.
Input format
Your program or function shall input a message in Neurotic Frogs, formatted in Markdown. The input will consist only of printable ASCII and newlines.

Words are runs of characters that match the regex [A-Za-z0-9'].

Numbers and letters both count toward the length of a word. QB64 represents D.
NOTE: Apostrophes do not count toward the length of a word. Isn't represents D, not E.

Italicized letters are wrapped in a pair of asterisks (*letters*).

One or more consecutive letters may be italicized, up to an entire word (masseus*es*, *all*); multiple non-consecutive letters in a word may also be italicized (g*e*n*e*rates).
Italics never span multiple words, never include punctuation, and never include apostrophes.
Unpaired asterisks and multiple adjacent asterisks will never occur.

Punctuation is any of the following characters: .,?!:;-()".

Words within a sentence are separated by one or more punctuation characters and/or a single space. Examples: *all* welcomed, toad*s*, newts, Ever*y*one--frogs, cap... bliss, they're (I
Sentences end with one or more punctuation characters and are separated by a double space: Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!
Paragraphs are separated by a single newline. (The last sentence of a paragraph still has one or more punctuation characters at the end.)

Other characters will not appear in input and do not need to be handled.
Your code may, at your discretion, expect input to have a single trailing newline.
Output format
The result of decrypting the input will be one or more sentences. Letters of plaintext may be any combination of upper- and lowercase. Words within a sentence must be separated by single spaces. Sentences must end with a period (.) and be separated by a single space. You may output a trailing space after the last sentence. Your output will all be on one line, but you may output a trailing newline.
Miscellaneous details
Your code may use any of the standard input and output methods. It must receive input as a multiline string, not a list or other data structure, and it must output a string.
The shortest code in bytes wins!
Test cases
-->
Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths!
<--
HELLO.

-->
Business standards all*o*w only *adult* amphibians.
<--
HINT.

-->
Rejoice, *a*ll frogs an*d* toads also!  Montgomery Sal*o*n opens up!  Ha*pp*y throng fill*s* street ecstatically!
<--
GOOD JOB PPL.

-->
I like 3.1415926535897.
IM*O*, it's a *b*la*st*, yeah!
<--
ADAM. MAN.

-->
*I*, happily, *th*anks 2 u *e*ditin*g* specific wor*ding*--clarifying a *bit*--betterment :D!
<--
QUARTATA.

-->
Perpendicular l*ou*nging calms.  *A* frog, a m*u*d cap... bliss!  Wallowing g*e*n*e*rates happiness.  Amphibian sp*a* isn't expensive--seventy d*o*llars--cheap!  That'*s* not *a* large e*x*pens*e* from an*y* discerning fr*o*g's money, unlik*e* Super 8.
Ever*y*one--frogs, toad*s*, newts, *a*nd salamanders!  G*e*t a wonderful shiat*s*u, or recei*v*e an other kind.  Masseus*es* are her*e* today!  Invite a fianc*e*e, supervisor, roommate, niece: *all* welcomed!
Y*o*u simply ne*v*er believed these p*o*ssibilitie*s*; they're (I *swear*) absolute truth!  Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!
<--
MY NAME IS INIGO MONTOYA. YOU KILLED MY FATHER. PREPARE TO DIE.

+1 for the princess bride input. Oh, and for your skill, that too.

Is a word containing italics guaranteed to be followed by one not containing italics?

@R.Kap Correct. I've edited the question to clarify that.

Perl, 72 bytes
#!perl -n
$x=/\*/?2-y/'//c%2:!print/ /?$':chr$x.0+y/'//c+64for/[\w*']+|  /g,' . '

Counting the shebang as one, input is taken from stdin.
Sample Usage
$ more in.dat
Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths!
Perpendicular l*ou*nging calms.  *A* frog, a m*u*d cap... bliss!  Wallowing g*e*n*e*rates happiness.  Amphibian sp*a* isn't expensive--seventy d*o*llars--cheap!  That'*s* not *a* large e*x*pens*e* from an*y* discerning fr*o*g's money, unlik*e* Super 8.
Ever*y*one--frogs, toad*s*, newts, *a*nd salamanders!  G*e*t a wonderful shiat*s*u, or recei*v*e an other kind.  Masseus*es* are her*e* today!  Invite a fianc*e*e, supervisor, roommate, niece: *all* welcomed!
Y*o*u simply ne*v*er believed these p*o*ssibilitie*s*; they're (I *swear*) absolute truth!  Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!

$ perl neurotic-frogs.pl < in.dat
HELLO. MY NAME IS INIGO MONTOYA. YOU KILLED MY FATHER. PREPARE TO DIE.

I'm awarding the bounty to this answer, since it's the shortest one at the end of the bounty period besides my own (indeed, the only one that came anywhere close).

JavaScript (ES6), 172 169 157 150 bytes
Saved 10 bytes thanks to @Neil
x=>x.match(/[\w'*]+|\s+/g).map(y=>y[0]==" "?y[1]:y==`
`?". ":/\*/.test(y,l+=y.match(/\w/g).length)?(l=l%2*10+19,""):l.toString(36,l=9),l=9).join``+"."

Can probably be further improved. Outputs in all lowercase.

Save 2 bytes by moving the i=0 into the toString.

Out of interest, I had a go at fixing those bugs and came up with this: x=>x.replace(/([\w*']+)[^\w\n*' ]* ?( ?)/g,(_,y,z)=>/\*/.test(y,l=y.replace(/'/g ,"").length)?(i=l%2||2,""):l+i*10+9).toString(36,i=0)+z,i=0).replace(/\n|$/g,". ")

Seems to work in it's current form.

@Neil Thanks. That saves 12 bytes, but it doesn't work on the last test case. Fixing that adds 9 for a net shortening of 3 bytes.

@Neil Getting rid of .replace and just using .match saved another 12 bytes.

Forgot about moving the i=0; /\*/.test(y,l+=y.match(/\w/g).length)?(l=l%2*10+19,""):l.toString(36,l=9),l=9) saves 7 bytes.

Pip, 65 64 bytes
The score is 62 bytes of code + 2 for the -rs flags.
Flg{O{{(zy*t+#a-1)X!Y'*Na&2-#a%2}MJa@`[\w*]+`}MlRM''^sX2O". "}

Try it online!
Explanation
The -r flag reads all lines of stdin and stores a list of them in g. The -s flag sets the output format of lists to space-separated.
The easiest way to read this code is from the outside in:
Flg{...}                   For each line l in g, do:

O{...}MlRM''^sX2O". "      Translate a paragraph into a sentence of plaintext:
       lRM''               Remove apostrophe characters
            ^sX2           Split on "  " into sentences
 {...}M                    Map the below function to each sentence
O                          Output the result list, space-separated, without newline
                O". "      Output that string, without newline

{...}MJa@`[\w*]+`          Translate a sentence into a word of plaintext:
       a@`[\w*]+`          Find all matches of regex (runs of alphanumeric and *)
{...}MJ                    Map the below function to each word and join into string

(zy*t+#a-1)X!Y'*Na&2-#a%2  Translate a word into a letter of plaintext:
      #a-1                 Length of word minus 1
  y*t+                     Add 10 or 20 if y is set (see below)
(z        )                Use that number to index into lowercase alphabet
              '*Na&        Count * characters in word, logical AND with...
                   2-#a%2  2 if word is even length, 1 if odd
             Y             Yank that value into y, to modify the following word
           X!              String multiply the character by not(y)
                           If y is truthy, the word had italics, and we get ""
                           If y is falsy, the word had no italics, and we get a letter

Seems unbeatable.

Python 2, 238 221 218 214 207 205 bytes
from re import*
def f(x):
 d='';m=0
 for w in split(r"[^\w\d*'~\n]+",sub('  ','~',x))[:-1]:l=len(sub("[*'~\n]",'',w));q='*'in w;d+='. '[w[0]>'}':]*(w[0]in'~\n')+chr(64+l+m)[q:];m=(2-l%2)*10*q
 print d+'.'

Uses lots of regex to do the processing. We transform the double-space into ~ and use that to process it. ~ and \n are handled specially.
The biggest character gain comes from the preprocessing of the input in the for line; this can definitely be golfed further.
Ideone it! (all test cases)
Saved 7 bytes thanks to DLosc!

PHP, 231 226 228 bytes
for a start
<?preg_match_all("#([\w\*']+)([^\w\*']*)#",$argv[1],$m,2);foreach($m as list(,$a,$b)){$e=strlen(strtr($a,["'"=>""]))+$d;if(!$d=strstr($a,'*')?$e%2*10:0)echo chr($e+64),strpos(".$b","
")?". ":(strpos(".$b","  ")?" ":"");}echo".";

Save to file, rund php <scriptpath> <text>. Escape newlines in the text to make it work in shell.

Can you give some instructions on running this? It looks like it reads input from $argv[1], but I don't know how that approach will work when input contains newlines. I tried "Neurotic Frogs *O*ught To Re*a*x In *M*ud Baths!" as a command-line argument and got IFHCHCFF. for output (as well as an Undefined variable: d warning).

@DLosc: That notice (not a warning) should not be there with default settings. The easiest way is to prepend <?, save it to a file and call that with php <filename> <string>. I may have to add 2 to the byte count.

@Titus If you begin with <?, you can also end with ?>., for a net gain for 1. FWIW, I get IFHCMFF. for the first test case (using PHP 5.5.21 64-bit, VC14). Using $argn with -F may also be an option.

What I mean is, I don't see how php <filename> <string> is possible when <string> can contain newlines.

@DLosc: fixed the bug. For the newlines: escape them.

Python 2.7, 390 342 341 339 335 bytes:
from re import*
def F(i):
 W=X="";S,s=split,sub;D='[^\w\s*]';Q=lambda c,t:len(s(D,X,c.group()).split()[t])
 for m in S('\W\n',s(D+"*\w*\*\w+\*.*?(?=\s) \w+",lambda v:"a"*([20,10][Q(v,0)%2]+Q(v,1)),s("'",X,s("--"," ",i)))):
  for g in S('\W  ',m):
   for q in S('\W',g):
    W+=chr(64+len(q))
   W+=" "
  W=W[:-1]+". "
 print s("@",X,W)

Takes input in the format:
F('''Multi or Single-lined String''')
Can be golfed down a lot more, which I will do whenever I get the chance.
Repl.it with All Test Cases!
Explanation:
Uses the immense power of Python's regular expression built-ins to decipher the input. This is the fundamental process the function goes through for each input:

Firstly, all -- are replaced with a single space, and every apostrophe is removed. Then, all words containing italicized components and the word proceeding it are both matched in one string and replaced with 10 + len(second word) number of consecutive as if the length of the first word is odd, and 20 + len(second word) consecutive as otherwise. This makes use of the following regular expression:
[^\w\s*]*\w*\*\w+\*.*?(?=\s) \w+
For example, if we have the sentence Perpendicular l*ou*nging calms., l*ou*nging calms will be replaced with aaaaaaaaaaaaaaaaaaaaaaaaa, or 25 as, since l*ou*nging has an even number of characters and calms has 5. 20+5=25.
Now, the newly modified input is split at each punctuation mark followed by a newline (\n) to get the paragraphs, then each paragraph is split at each punctuation followed by 2 spaces to get the sentences, and finally, each sentence is split into words along any punctuation including a space. Then, for each word (including the runs of consecutive as), we add on to a string W the letter corresponding to the unicode code point 64 (the unicode code point of the character before A, which is @) plus len(word). We then add a single space to W once all the words of a sentence have been exhausted, and when all the sentences in a paragraph are exhausted, we add a . followed by a single space.
Finally, after the entire input has been gone through, W is output to stdout as the deciphered message.

Minor nitpick: spec says output sentences are separated by single space, not double (this change also saves a byte). Initial golfing suggestion: since you're importing everything from re, use sub instead of str.replace. More general golfing suggestion: it's probably more efficient to treat everything that's not a word or * as punctuation. Saves on big huge character classes.

@DLosc Oh, my bad. I thought the spec was to separate sentences in the output by 2 spaces. I'll fix that. Also, thanks for the golfing suggestions! I'll see what I can do with those.

PHP, 196 Bytes
<?preg_match_all("#[\w*']+|  |$#m",$_GET[s],$m);foreach($m[0]as$s){if(!$s||$s=="  ")echo!$s?". ":" ";else{$l=$p+64+strlen(str_replace("'","",$s));if(!$p=strstr($s,"*")?20-$l%2*10:0)echo chr($l);}}

If I could assume that there is only one Apostrophe in the middle of a word 194 Bytes
<?preg_match_all("#[\w*]+(<?=')[\w*]+|[\w*]+|  |$#m",$_GET[s],$m);foreach($m[0]as$s){if(!$s||$s=="  ")echo!$s?". ":" ";else{$l=$p+64+strlen($s);if(!$p=strstr($s,"*")?20-$l%2*10:0)echo chr($l);}}

@DLosc It was urlencoded %0A  as a function rawurlencode("\n"). I prefer in this case a form with a textarea for the input and so my html site makes it automatically to encode the string

@DLosc I suspect that error_reporting in the php.ini is on. try 'error_reporting(0);' after the <?.  One error belongs to $_GET[s] it works but correct is $_GET["s"] and it's better to declareand initialize the variable $p=0; before the loop. Now my question at you is: Can I ssume that in one Word is only one Apostrophe in the middle of the Word?

@DLosc for multiple Apostrophes I must use my first answer. The second - 2 Bytes works only with one Apostroph in the middle if the word.

I figured out what my problem was--my server doesn't have short opening tags enabled. Changing to <?php worked.

@Dlosc I have never use <? in reality. I use the short tag only in my post here. Now I know that it can resut in a blank page.