# 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 ;-) – Digital Trauma Sep 9 '16 at 21:19
• Aww I was hoping to count some goats, not the other way round – Beta Decay Sep 9 '16 at 21:45
• I think I know who counts goats to sleep – Luis Mendo Sep 9 '16 at 21:57
• I don't think you can count goat to sleep unless "bleeeeeeet" makes you feel sleepy :P +1 great challenge – Downgoat Sep 9 '16 at 22:19
• Psychopaths fall asleep by counting screaming goats. – mbomb007 Sep 12 '16 at 16:36

# 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

1. Generate an awake goat N times, working with code points increased by 1.
2. Transform the last goat into a sleeping goat.
3. 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 ;) – Conor O'Brien Sep 9 '16 at 23:05

# Python 3.6, 102 bytes

lambda n:f'''{'      \ '*n}
{'  ___/o>'*~-n}  ___/->
{'-(___)" '*~-n},(___)"
{" '' ''  "*~-n}  '''


Yaay, f-strings!

            __________________________
/                          \
\   /___________________________/
___/o> '
-(___)"
'' ''


## Javascript, 122 bytes

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 Sep 9 '16 at 22:47 • @Mego What's wrong with showing how much more golfable it would have been? – Neil Sep 9 '16 at 22:54 • @Neil Because it's entirely tangential to the challenge. – Mego Sep 9 '16 at 22:54 • @Mego I think it's interesting to note. – Conor O'Brien Sep 9 '16 at 23:06 • @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. – Hedi Sep 10 '16 at 8:42 ## 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 ._. – Conor O'Brien Sep 9 '16 at 23:07 • The ^ escapes characters. – Krii Sep 14 '16 at 14:03 • @Krii Doesn't work when I need it to. – Neil Sep 14 '16 at 14:50 ## 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 Sep 10 '16 at 9:35
• @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. – Neil Sep 10 '16 at 10:22
• You can remove the semicolon – howderek Sep 12 '16 at 1:07
• @howderek I didn't include it or the f= in my byte count, it's just there for completeness. – Neil Sep 12 '16 at 7:52

# 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
"-(___)\" "b*  # Idem
",(___)\""n    #
" '' ''  "b*   # Idem
"  "n      #


Try it online!

• Nearly misread as GoatScript – Calvin's Hobbies Sep 10 '16 at 19:03

# 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

¢            - last link (make a goat)
“-,o-'”    - characters to remap
yÐ€ - map for each (change "-" into ",", "o" into "-", and "-" into ""

’        - 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


# 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? – Titus Sep 10 '16 at 16:31
• Thanks I want only to solve this challenge in any way. Sometimes is clean better then a wrong solution. You can paste your way. – Jörg Hülsermann Sep 10 '16 at 17:05
• I took a different approach; but if you want tips for yours, just ask. 24 bytes in the first 5 steps. – Titus Sep 10 '16 at 19:33
• @JörgHülsermann Modifying other people's answers seems to be heavily frowned upon in this site. – Carcigenicate Sep 10 '16 at 21:57
• @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 – Jörg Hülsermann Sep 10 '16 at 23:18

## 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 Ender Sep 10 '16 at 18:21
• Martin, thanks for the link. I originally measured the size by file size and now I fix it. – Yurii Blok Sep 10 '16 at 18:40
• 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. – Martin Ender Sep 10 '16 at 18:46
• Okay, I wrote the size by file size. About how this code works - there is no difference between readable and one line version. – Yurii Blok Sep 10 '16 at 19:01
• 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. – hvd Sep 11 '16 at 12:42

## 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.)

# 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


# Python 2.7, 101 113 bytes

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?). – Jonathan Allan Sep 11 '16 at 3:40
• 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? – tigr Sep 11 '16 at 10:55
• Ah, ok. It needs to be either a program or a function. Will update with worse solution, for now :( – tigr Sep 11 '16 at 10:56
• 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. – Jonathan Allan Sep 11 '16 at 15:28

# 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


# 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. ## 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>  ___/->
-(___)" -(___)" -(___)" ,(___)"
'' ''   '' ''   '' ''    


## 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

# IBM/Lotus Notes Formula, 187174 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. – mbomb007 Sep 12 '16 at 19:04
• 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 ☺ – ElPedro Sep 12 '16 at 19:45
• To be honest, I bet there won't be too many Lotus Notes golfers. – ElPedro Sep 12 '16 at 20:26

## 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.

# Java 8, 236222218 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


## Canvas, 58 bytes

>o/___¶ ")___(-∙ \；∔± ''２×∔╶╷×>-/___¶ ")___(,∙ \；∔± ２×∔＋


Try it online!

Pretty boring answer, really... builds the awake goat, repeats it horizontally n-1` times, builds and adds the sleeping goat, prints the result.