Считать коз, чтобы спать

36

Некоторые люди считают овец, чтобы заснуть. Другие считают коз.

Напишите программу или функцию, которая принимает положительное целое число N и выдает N-1 бодрствующих коз, за ​​которыми следует одна спящая коза, как если бы кто-то считал N коз, и в самом последнем случае они засыпали.

Бодрствующие козы выглядят так:

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

Спящие козы выглядят так:

      \
  ___/->
,(___)"
 `` ``

Они связаны между собой одним пространством между бородой и хвостом соседних коз:

      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``

Выходные данные могут иметь конечные пробелы и один завершающий символ новой строки.

Самый короткий код в байтах побеждает.

Примеры

N = 1:

      \
  ___/->
,(___)"
 `` ``

N = 2:

      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``

N = 3:

      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``

N = 4:

      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``

Больший N должен работать так же хорошо.

Кальвин Хобби
источник
9
Я думаю, что ваши "козы" больше похожи на злых птиц с 4 ногами ;-)
Digital Trauma
4
Я надеялся посчитать несколько коз, а не наоборот
Beta Decay
1
Я думаю, что я знаю, кто считает, что козы спят
Луис Мендо
7
Я не думаю, что вы можете считать козу спящим, если только "bleeeeeeet" не заставит вас чувствовать себя сонным: P +1 большой вызов
Downgoat
1
Психопаты засыпают, считая кричащих козлов.
mbomb007

Ответы:

30

MATL , 56 53 байта

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

Попробуйте онлайн!

объяснение

Бодрствующий козел

Бодрствующий козел может быть упакован в строку

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

и распаковывается, как будет объяснено в ближайшее время. Однако символы одинарных кавычек должны быть продублированы , чтобы избежать их, поэтому строковый литерал должен быть определен как (обратите внимание на символы в одинарных кавычках и дублирование исходных символов):

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

Чтобы сохранить байты, мы определяем строку, используя символы на одну кодовую точку выше, что позволяет избежать дублирования. Строковый литерал становится

'!!((!((!!#*```).?p0```!!!]'

В конце кода мы вычтем 1 и преобразуем в char. (Мы могли бы сделать это сейчас, сразу после строкового литерала; но оставив его на конец, мы увидим еще одно дублирование в одинарных кавычках).

Чтобы объяснить, как распаковывается строка, мы будем работать с оригинальными символами (которые создаются в конце кода с помощью подтактинга 1), поэтому объяснение легче следовать. Сначала мы изменим строку

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

в 8-рядный двумерный массив символов, в главном порядке столбцов (вниз, затем поперек). Это автоматически дополняет последний столбец символом 0 (в конце кода вычитание 1 преобразует его в число -1, что при преобразовании в символ снова возвращает символ 0). Char 0 отображается как пробел. Так эффективно мы дополняем пробелы. Результатом изменения формы является

  > 
 "o\
')/ 
'__ 
 __ 
'__ 
'(  
 -  

Теперь мы перевернем вертикально:

 -  
'(  
'__ 
 __ 
'__ 
')/ 
 "o\
  > 

а затем переставить и перевернуть вертикально снова, чтобы получить бодрствующего козла:

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

Две операции переворота необходимы, потому что оригинальная упакованная строка «в обратном порядке». Это делается для того, чтобы использовать тот факт, что фактический двумерный массив символов, представляющий козу, имеет 6 начальных пробелов в первой строке, которые автоматически заполняются заполнением, когда строка преобразуется в 8-рядный двумерный массив. Но заполнение выполняется в конце (не в начале) последнего столбца (не в строке), поэтому происходит переворот и транспонирование.

Спящая коза

Спящий козел генерируется из активного козла с помощью транслитерации символов o, ', -в -, `, ,соответственно. На самом деле, из - за один-код-точечным выше преобразования в, мы транслитерации символов p, (, 'в ., a, -, что опять избавляет нас от необходимости дублировать символ одинарной кавычки. Именно поэтому операция вычитания-1 была оставлена ​​на конец программы.

Структура кода

  1. Создайте время активного козла N, работая с кодовыми точками, увеличенными на 1.
  2. Превратите последнего козла в спящего козла.
  3. Объединить всех коз горизонтально. Вычтите 1 из кодовых точек и приведите к символу.

Код комментария

:                              % (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 
Луис Мендо
источник
8
This is some serious goat theory ;)
Conor O'Brien
17

Python 3.6, 102 bytes

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

Yaay, f-strings!

            __________________________
           /                          \
          |  This answer is baaaaaaad. |
      \   /___________________________/
  ___/o> '  
-(___)" 
 '' ''  
Lynn
источник
13

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):'')
Hedi
источник
3
Why include the vertical submission? The challenge asks for horizontal alignment.
Mego
5
@Mego What's wrong with showing how much more golfable it would have been?
Neil
2
@Neil Because it's entirely tangential to the challenge.
Mego
9
@Mego I think it's interesting to note.
Conor O'Brien
3
@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
4

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.

Neil
источник
I had no idea set/pn works ._.
Conor O'Brien
The ^ escapes characters.
Krii
@Krii Doesn't work when I need it to.
Neil
4

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 :(

Blue
источник
3

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.

Neil
источник
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
@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
You can remove the semicolon
howderek
1
@howderek I didn't include it or the f= in my byte count, it's just there for completeness.
Neil
3

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!

FedeWar
источник
5
Nearly misread as GoatScript
Calvin's Hobbies
3

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
Jonathan Allan
источник
1

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");
Jörg Hülsermann
источник
1
You are coding way too clean, Jörg. I could golf off 32 bytes from that in 11 steps. Want hints?
Titus
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
I took a different approach; but if you want tips for yours, just ask. 24 bytes in the first 5 steps.
Titus
@JörgHülsermann Modifying other people's answers seems to be heavily frowned upon in this site.
Carcigenicate
@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
1

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;
}
Yurii Blok
источник
2
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
Martin, thanks for the link. I originally measured the size by file size and now I fix it.
Yurii Blok
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
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
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
1

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

DLosc
источник
1

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
Business Cat
источник
1

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.

tigr
источник
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
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
Ah, ok. It needs to be either a program or a function. Will update with worse solution, for now :(
tigr
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
1

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
kalsowerus
источник
0

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.

andlrc
источник
0

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.

Titus
источник
0

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>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
AdmBorkBork
источник
0

Ruby, 102 bytes

m=-1+n=gets.to_i
puts'      \ '*n,'  ___/o>'*m+'  ___/->',(?-+a='(___)" ')*m+?,+a," '' ''  "*m+" ``"*2
cia_rana
источник
0

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

Jeffrey04
источник
0

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:

enter image description here

enter image description here

enter image description here

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.

enter image description here

ElPedro
источник
Why is it non-competing? Every answer is like that. That's called wrapping.
mbomb007
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
To be honest, I bet there won't be too many Lotus Notes golfers.
ElPedro
0

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.

Lord Yuuma
источник
0

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
Kevin Cruijssen
источник
0

Canvas, 58 bytes

>o/___¶ ")___(-∙ \;∔± ''2×∔╶╷×>-/___¶ ")___(,∙ \;∔± ``2×∔+

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.

hakr14
источник