Я люблю сардини


33

Я люблю сардини, я не можу їх достати, як і мій комп'ютер Omnilang 5000, який є агностиком.

Щоб доставити моєму комп’ютеру радість від випробовування сардин, я вирішив нагодувати його низкою програм, здатних відображати на екрані бляшані сардини в різних напрямках і показувати до десяти сардин.

У цьому виклику ви несете відповідальність за створення програм на основі цих параметрів:

Вхід

Цифра (від 0 до 10) та літера від одного з наступних "LR" (що представляє відповідно ліворуч або праворуч) Наприклад: 3Lабо 5R; як ви входите в програму, залежить від вас.

Вихідні дані

Відкрита жердина сардин із сардинами, що виходять на вказаний напрямок, з ключем (представленим %символом " ") та очищеною кришкою (згорнута олова в кінці, представленою @символом " "), розташована у верхній частині олова.

  • Всі сардини повинні відповідати напрямку, вказаному вхідними даними.
  • Усі сардини матимуть тіла із п’ятьма символами між зябрами (або " )" або " (") та хвостом ">< "
  • Ключ і очищений рулон кришки завжди будуть спрямовані протилежно до сардин.
  • Олово повинно мати 3-D вигляд, як показано нижче в прикладах.
  • Мінімальна висота олова - 3 сардини у висоту. Отже, якщо число менше 3, має бути олово з 3 сардин у висоту, із введеною кількістю сардин у ньому. В іншому випадку в олові повинно бути кількість сардин, вказане на вводі. Тож вхід 0Rабо 0Lпокаже порожню салону олова.
  • Будь-який інший вхід, який неможливо перевірити, нічого не покаже.

Наприклад, для " 3L"

 __________
(__________@%
|<*)_____><||
|<*)_____><||
|<*)_____><||
'==========''

Для " 7R"

   __________
 %@__________)
 ||><_____(*>|
 ||><_____(*>|
 ||><_____(*>|
 ||><_____(*>|
 ||><_____(*>|
 ||><_____(*>|
 ||><_____(*>|
 ''=========='  

Для " 2L"

 __________
(__________@%
|<*)_____><||
|<*)_____><||
|          ||
'==========''

Для " 0R"

   __________
 %@__________)
 ||          |
 ||          |
 ||          |
 ''=========='

" 0L"

 __________
(__________@%
|          ||
|          ||
|          ||
'==========''

Неправильний вхід нічого не поверне ...

  • Це кодовий гольф, тому найменша кількість символів переможе в цьому виклику.
  • Без лазівки, як зазвичай.

Відповіді:


39

> <> , 250 235 + 3 = 238 байт

</~?{"  __________"a:="L"i&
o/?=1l
:/}rv?{~$?{"()__________@%":
l< o/?=1
:&oa/&~$?(3$@0-3:
/!?:</"||><_____(*>|"av?@:$-1
 /=?/v"|<*)_____><||"a/
 \2lo/
\~&
\>:?!\1+$::{a"|"{?:"          ||"{?~
<\?=2 lo
"'":~/~?{"''==========":?{
;!?lo<

Спробуйте в Інтернеті або подивіться це на рибному майданчику ! Читає "L" або "R" від STDIN і припускає, що кількість сардин вже є на стеку (потрібен -vпрапор на +3 байт).

Тому що, звичайно, мені довелося це писати в> <>.


3
Написання цього рішення на рибі натхненно ...
— WallyWest

Як працює рибний майданчик? Я не можу змусити його працювати. Де я розміщую вхід?
— JAD

@JarkoDubbeldam, скопіювавши код у вікно та подавши його, потрібно поставити кількість сардин, де на ньому написано "початковий стек" (імітуючи -vпрапор), і напрям ("L" або "R") під "дай вхід до програми ", потім натисніть" дати ". (Я відредагував відповідь, щоб, сподіваюся, зробити це зрозумілішим.)
— Не дерево

1
Дивовижно: D Має бути приємним і під час налагодження
— JAD

15

Emojicode , 456 448 байт

🐋🚂🍇🐖🐟d🚂🍇🍦a😛0d🍊a🍇😀🔤 __________❌n(__________@%🔤🍉🍓🍇😀🔤  __________❌n%@__________)🔤🍉🔂i⏩0🐕🍇🍊a🍇😀🔤|<*)_____><||🔤🍉🍓🍇😀🔤||><_____(*>|🔤🍉🍉🍊▶️4🐕🍇🔂i⏩0➖3🐕🍇🍊a🍇😀🔤|          ||🔤🍉🍓🍇😀🔤||          |🔤🍉🍉🍉🍊a🍇😀🔤'==========''🔤🍉🍓🍇😀🔤''=========='🔤🍉🍉🍉

Бере 2 аргументи: перший - це рядки, другий - напрямок (0 або 1).

Спробуйте в Інтернеті!

"Читається" версія, що не перебуває під загоном, та версія псевдокоду:

🐋 🚂 🍇
  🐖 🐟  d 🚂  🍇
    🍦 a  😛 0 d

    🍊 a 🍇
      😀 🔤 __________❌n(__________@%🔤
    🍉
    🍓 🍇
      😀 🔤  __________❌n%@__________)🔤
    🍉

    🔂 i ⏩ 0 🐕 🍇
      🍊 a 🍇
        😀 🔤|<*)_____><||🔤
      🍉
      🍓 🍇
        😀 🔤||><_____(*>|🔤
      🍉
    🍉

    🍊 ▶️ 4 🐕 🍇
      🔂 i ⏩ 0  ➖ 3 🐕  🍇
        🍊 a 🍇
          😀 🔤|          ||🔤
        🍉
        🍓 🍇
          😀 🔤||          |🔤
        🍉
      🍉
    🍉

    🍊 a 🍇
      😀 🔤'==========''🔤
    🍉
    🍓 🍇
      😀 🔤''=========='🔤
    🍉
  🍉
🍉

👵
extendclass int { // this makes the first argument be an int without declaring it
  func 🐟(int d) {
    const a = 0 == d // a bool

    if a {
      print " __________\n(__________@%"
    }
    else {
      print "  __________\n%@__________)"
    }

    for i in range(1, arg) {
      if a {
        print "|<*)_____><||"
      }
      else {
        print "||><_____(*>|"
      }
    }

    if 4 > arg {
      for i in range(0, arg - 3) {
        if a {
          print "|          ||"
        }
        else {
          print "||          |"
        {
      }
    }

    if a {
      print "'==========''"
    }
    else {
      print "''=========='"
    {
  }
}
👵

2
Ніколи не натрапляйте на Емоджикоде раніше, але це розум f ** k з половиною ... Божевільний! Любіть це!
— WallyWest

... чому ця мова взагалі існує? Я маю на увазі, мені це подобається, але чому? і скільки часу знадобилося тобі, щоб це вивчити?
— Тейлор Скотт

1
@TaylorScott 1) ​​не знаю, я не створив його. 2) дійсно кілька годин
— betseg

6

Python 2 , 155 байт

lambda x,y,t='_'*10:'\n'.join(x[::1-2*y]for x in[' %s  '%t,'()'[y]+t+'@%']+['|'+('<>**)(%s><<>'%t)[y::2]+'||']*x+['|'+' '*10+'||']*(3-x)+["'"+'='*10+"''"])

Спробуйте в Інтернеті!

Вхід складається з кортежу довжиною 2. Перший елемент вказує кількість сардин. Другий елемент вказує напрямок; 0для лівого, 1для правого.

-84 байт з використанням лямбда магії завдяки нежагану та офіціаламму


1
174 байти (сорт отримав ніндзя від @officialaimm там).
— неджаган

1
Знизив її далі на 161 байт!
— notjagan


1
@officialaimm досить цікаво, якщо він має негативне значення, він збільшує розмір олова, але не додає сардин.
— Павло,

3
@Phoenix Так. Однак це не має значення, оскільки OP вказав дальність 0 to 10. PS` -10` надрукував би порожню олово, тому що це означає, що там були 10сардини, але ви вже їх з'їли. : D
— officialaimm

5

Риболовля , 1311 байт

v+CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC?CCCDCC[CCCCCCCCCCCCCCCCCCCCC?CCCCCCCCCCCCCCCCCCCC[CCC[CCCCC?CCCC?DDDDD[CCCCCCCCCCCCCCCCCCC?CCCCCCCCCCCCCCCCC[?CCCCCCCCCCCCCCCC_
  `3`n{n{In{I{`L`{`  __________ `}}!{{rD}}D{{NE`%@__________)`}}!{{E`(__________@%`}}D{{NDE}}}}={d}}!  d  D{{{{{`><_____(*>`}}!{{E`<*)_____><`}}D!{{{E`|`P}PE`||`ND
                                   [DDDDDD|                     [DDDDDDDDDDDDDDDDDDDD|   D     [C?CDDDDDDDDCCCCCCCCCCCCCCCCCCC[DDDDDDDDDDDDDDDDD|[CCCCCCCCCCCCCCCC_
                                                                                         D      }=d [^+Cv-|{{{{{`          `}}                    {{{E`||`P}PE`|`ND
                                                                                         D       [CCCCCCCCCCCCCCCCCCC?DDDDDDDDD+CCCC                              D
                                                                                         D        E`''=========='`{{{= }}}r{{{ [CCCC                              D
                                                                                         D                           [^CCCCCCCv|}}}N                              D
                                                                                         |DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD]

Вводиться з stdinформи:

5
R

Риболовля не на " Спробуйте в Інтернеті" , але в Ruby на її пов'язаній сторінці esolangs є перекладач.

Це перша програма, яку я зробив у риболовлі - насправді це перша програма, яку я зробив на будь-якій 2D мові - тому, ймовірно, вона може бути набагато коротшою. Поради щодо гольфу вітаються (хоча я б не здивувався, якби ніхто не дав жодних, враховуючи, що навіть я не знаю, що за чорт я щойно написав).

Ось GIF шляху, який програма вводить для введення 1R(вибачте за низьку якість):

GIF

(Це було створено за допомогою перекладача, який я створив; немає публічно доступних програм, які "візуалізують" Риболовлю, наскільки я знаю)


The C and D syntax looks like it's contributing to the bloat... Is there any shorthand available to reduce that?
— WallyWest

Actually scratch that, looks like they're integral to the code... Interesting choice of language! :)
— WallyWest

4

Charcoal, 49 bytes

A⌈⟦Iθ³⟧ζBχ²_←↓(↓ζ'×=χ''↖P↑ζ←↑ζ@%FN“#∨‹VB“«ji”FN‖T

Try it online! Link is to verbose version of code. First argument is number of sardines, second is direction (0 = left, 1 = right).


Great work, Neil. Thanks for supplying a compiler link!
— WallyWest

2
Don't thank me, thank @Dennis for creating TIO which generates all of the boilerplate for you.
— Neil

3

SOGL V0.12, 51 48 bytes

!gX⁴‘gj⁰%!⁵‘b⌡"κN╥█*≤⌡║)‘3b-"÷AZ⁴‘∙_"Χccσ«‘⁰e?±↔

Try it Here!
Expects input as the 1st one being the count and the 2nd one - left or right represented by 1 or 0.

Explanation:

..‘..‘                          push 2 compressed strings - the 1st two lines of the box - "  __________ " and "%@__________)"
      b⌡                        input times do
        "..‘                      push a line with a sardine - "||><_____(*>|"
            3b-                 push 3-input
               "..‘∙            get an array of that many "||          |"
                    _           put all the arrays contents on the stack
                     "..‘       push "''=========='" - the last line
                         ⁰      wrap all of that in an array
                          e?    if the 2nd input [is not 0]
                            ±↔    reverse the array horizontally

2

R, 334 bytes 311 bytes

s=function(n,d){
a="__________"
b="'=========='"
if(d == "L"){cat(paste(c(" ",a,"\n(",a,"@%\n",rep("|<*)_____><||\n",n),rep("|          ||\n",max(c(3-n,0))),b,"'\n"),collapse=""))} else {cat(paste(c("  ",a,"\n%@",a,")\n",rep("||><_____(*>|\n",n),rep("||          |\n",max(c(3-n,0))),"'",b,"\n"),collapse=""))}}

Function takes a numeric value for n and a string for the direction.

This is my first time posting, so I'll admit I'm not sure how to count bytes of code.


1
You can paste your code into TIO, where people can also test your code :) it also displays your byte count, which is 310 in this case.
— Ian H.

2

C++, 307 296 292 bytes

#include<string>
auto z(int n,char c){std::string r=c-82?" __________\n(__________@%\n":"  __________\n%@__________)\n";int l=0;for(;l<n;++l)r+=c-82?"|<*)_____><||\n":"||><_____(*>|\n";for(;l<3;++l)r+=c-82?"|          ||\n":"||          |\n";r+=c-82?"'==========''":"''=========='";return r;}

Usage :

z(<number of sardines>,<'L' or 'R'>);

-11 bytes saved thanks to user ThePirateBay -4 bytes thanks to Zacharý


1
Can you remove the parentheses in #define directive? I didn't test it but it seems that there's no need for them.

1
Can c!=82 be c-82 in every case where you use it?
— Zacharý

1

Python 2, 287 bytes

n,d=input()
t,a,b,c,e,k=' __________   ','(__________@% ','|<*)_____><|| ','|          || ',"'=========='' ",'\n'
print[t+k+a+k+k.join([b]*n)+k+k.join([c]*(3-n))+k*(n<3)+e,t[::-1]+k+a[::-1].replace(*'()')+k+k.join([b[::-1].replace(*')(')]*n)+k+k.join([c[::-1]]*(3-n))+k*(n<3)+e[::-1]][d]

Try it online!

Input is a comma separated tuple of numbers of this format: 2, 1. The first number is the amount of fish and the second is is 0 for left and 1 for right.

This started out as an attempt to out-golf the other answer (I totally thought I could), but it sucks. :P If anybody can make head and tail of it and help golf it (I blame it on it being 12 am right now), I'd be glad.


Great attempt nonetheless!
— WallyWest

1

C# (.NET Core), 289 bytes

(h,d)=>{var l=d=='L';string r=(l?" ":"  ")+"__________\n"+(l?"(":"%@")+"__________"+(l?"@%":")")+"\n";for(int i=0;i<(h>3?h:3);i++){r+=(l?"|":"||")+(i<h?(d=='L'?"<*)_____><":(d=='R'?"><_____(*>":"")):"          ")+(l?"||":"|")+'\n';}var b=(l?"'":"''")+"=========="+(l?"''":"'");return r+b;}

Try it online!

Takes an integer and a char (L, R) as parameters and outputs the resulting string.

Ugh. Had to deal with some annoying string constants, sadly you cant just do string * length in C#. And the method with new string(char, length) wouldn't have been worth the byte cost.


The algorithm works as follows:

  1. At the start we determine if the sardines face right or left, since we will then format our strings accordingly. We create a string for the top, with some conditional operators to switch between the L and R perspective.
  2. Then we create a loop that runs 3 times at minimum and the left input times at maximum. That way we can create empty spaces if we have less than 3 sardines in our box.
  3. Inside this loop we format a string, depending on the perspective and also, if h > i, we put a sardine inside of it. If i >= h, there will be an empty space where a sardine would normally be.
  4. At the end we create the bottom of the box, again formatted according to perspective.

1

Perl 5, 167 + 1 (-n) = 168 bytes

($n,$d)=/(\d+)([LR])/ or die;say('R'eq$d?(reverse$_)=~y/()></)(<>/r:$_)for" __________  ","(__________@%",("|<*)_____><||")x$n,("|          ||")x(3-$n),"'==========''"

Try it online!


1

JavaScript (ES6), 283 273 269 251 bytes

Saved 10 bytes thanks to @WallyWest

Saved 4 bytes removing extra parens

Saved 18 bytes thanks to @ThePirateBay

Suffers from lack of string reversal in the standard library. Defines a function that takes inputs n for number of fish and d for direction. Throws if d is not "L" or "R".

(n,d,_=c=>c.repeat(10),x=_(`_`),z=a=>a.reverse``.join``)=>
([p,q,g,r,s]=d>`L`?d>`R`?[]:[`)`,`(`,`>`,z,y=>z(y.split``)]:
[`(`,`)`,`<`,a=>a.join``,y=>y],` ${x}
`+r([p,x,s(`@%`)])+`
`+(r([`|`,g,`*`,q,`_____`,`><`,`||`])+`
`).repeat(n)+r([`'`,_(`=`),`''`]))

Try it online


Welcome to PPCG! We hope you like it here... Let's see what we can do to golf your score down... Great commencing effort!
— WallyWest

@WallyWest thanks! Shaved off another 17 bytes by pulling out a function and changing the if...else if to nested ternaries with a destructuring assignment. I'm out of ideas though...
— Jared Smith

1
@WallyWest I use the _ function twice, once for the 10 underscores (which gets used twice), once for the 10 equal signs, so having it in a function saves me a byte. And unless I'm using template strings wrong, using them instead of concatenation is 3 bytes more.
— Jared Smith

1
@WallyWest thanks for the tip, that and removing some unneeded parens saved 14 bytes.
— Jared Smith

1
@Zacharý done. If I didn't enjoy making strangers on the internet happy, I wouldn't be on SE in the first place.
— Jared Smith
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.