Візьміть телефон! Це вібрує!


14

Ви нещодавно отримали новий телефон, але вам не дуже подобається спосіб його вібрації, ви вирішили створити свої власні схеми вібрації. Отже, ви написали програму, в якій використовували ключові слова long, shortі pauseщоб ваш телефон вібрував відповідно до цих ключових слів.

Завдання

Створіть невелику програму , яка приймає рядок long, shortі pauseта виводить інший рядок , що представляє фонетичний звук телефону вібраційного;Rrrr - Rr

longзвуки - Rrrr
shortзвуки є Rr
(Корпус має значення)
pause- штрих, -
всі звуки розмежовані тире з навколишніми просторами' - '

Випробування

вхід:    long long short long short
вихід:Rrrr - Rrrr - Rr - Rrrr - Rr

вхід:   long long long short short short
вихід:Rrrr - Rrrr - Rrrr - Rr - Rr - Rr

вхід:   short short short pause short short short
вихід:Rr - Rr - Rr - - - Rr - Rr - Rr

вхід:   long short short long long pause short short
вихід:Rrrr - Rr - Rr - Rrrr - Rrrr - - - Rr - Rr

Це питання з тому відповіді будуть набрані в байтах, вигравши найменше байтів.


5
Це не суб'єктивний критерій? Я хотів би використовувати порожню рядок, це звучить як вібруючий телефон.

6
Ваше правило "звучить як" є занадто розпливчастим. Я б запропонував просто вимагати точних рядків. Код гольфу вимагає точних критеріїв, тому ми можемо оптимізувати код, не маючи аргументу, чи є поліпшення дійсним.
xnor

4
Чи треба розмежовувати звуки за допомогою a -? Це у вашому прикладі, але ніде не вказано.
JAD

12
У всіх прикладах використовується велика літера, а потім копії письма з нижнього регістру. Це правило?
xnor

3
Що потрібно зробити, перш ніж це можна буде повторно відкрити: 1) Вкажіть точні рядки (або набори рядків), які ми повинні використовувати, включаючи обмеження в регістрі, 2) Уточнити, чи можуть введення та / або вихід є масивом або слів, або масивів символів, 3) Вкажіть точний роздільник, який повинен бути використаний при виведенні в якості рядка.
Кудлатий

Відповіді:


12

Пайк , 22 20 байт

cFh.o6.&\R*\-|l4)J" - 

Спробуйте тут!

c                      -  split(input, " ")
 Fh.o6.&\R*\-|l4)      -  for i in ^:
  h                    -        ^[0]
   .o                  -       ord(^)
     6.&               -      ^ & 6
        \R*            -     ^
           \-|         -    ^ or "-"
              l4       -   ^.title()
                 J" -  - " - ".join(^)

Суть цієї відповіді - трансформація ["long", "short", "pause"] на [4, 2, 0]. Він отримує кодову точку першої літери кожного слова і ANDвидає її 6. За щасливим збігом обставин вона перетворюється на значення, які ми шукаємо. (Я шукав ще кілька інших більш довгих рішень, перш ніж знайти це). Як тільки це буде зроблено, ми можемо додатково перетворити цей список вкладень ["RRRR", "RR", ""], помноживши наш int, на "R"який потім перетворюємось ["RRRR", "RR", "-"]і, нарешті, заголовком обробляємо його ["Rrrr", "Rr", "-"]. Потім ми приєднуємося до отриманого списку за" - "


Класний спосіб піти про це з трансформацією!
tisaconundrum

Рішення абсурдно схоже в Pyth: j" - "m|*\M.&Chd6\-c:-)
Містер Xcoder

Також ОП додає простір до прикладів, але не вказує їх, я просив пояснення з цього приводу.
Джонатан Аллан

@JonathanAllan Байти \xefі \xa6є, .oі .&відповідно. Це зворотно сумісна зміна, якщо якщо встановлено високий біт, він виконує його, як і старі 2-байтні команди. Я пишу це таким чином, щоб полегшити читача, і тому що Пайк технічно більше не використовує кодову сторінку, і мені не хочеться вставляти випадкові байти, які не працюють
Blue


11

Хаскелл , 71 66 59 байт

g 'o'="Rr"
g 'n'="rr"
g 'p'="-"
g ' '=" - "
g _=""
f=(g=<<)

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

О, так, =<< це concatMap.

Приймає перевага того факту , що "long"і "short"обидва мають букву o.


Вам не потрібно платити 2 байти за f=точкові функції, дозволені без призначення
Post Rock Garf Hunter

Ви можете зберегти один цілий байт за допомогою лямбдака, перейшовши на лямбдабот haskell:(>>=(\case 'o'->"Rr";'n'->"rr";'p'->"-";' '->" - ";_->""))
BlackCap

7

JavaScript (ES6), 65 59 байт

s=>s.split` `.map(x=>x<'m'?'Rrrr':x<'q'?'-':'Rr').join` - `

let f =

s=>s.split` `.map(x=>x<'m'?'Rrrr':x<'q'?'-':'Rr').join` - `

console.log(f("long long short long short")); // => Rrrr - Rrrr - Rr - Rrrr - Rr
console.log(f("long long long short short short")); // => Rrrr - Rrrr - Rrrr - Rr - Rr - Rr
console.log(f("short short short pause short short short")); // => Rr - Rr - Rr - - - Rr - Rr - Rr
console.log(f("long short short long long pause short short")); // => Rrrr - Rr - Rr - Rrrr - Rrrr - - - Rr - Rr


7

05AB1E , 33 27 25 21 байт

#εÇн6&'m×™'-)éθ}… - ý

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

Пояснення

#                       # split input on spaces
 ε             }        # apply to each
  Çн                    # get the character code of the head
    6&                  # AND with 6
      'm×               # repeat "m" this many times
         ™              # title case
          '-)           # wrap in a list with "-"
             éθ         # get the longest string       
                … - ý   # join to string using " - " as separator

Збережено 3 байти, використовуючи AND 6трюк з відповіді щуки мудрої риби






4

R , 77 байт

cat(c('Rrrr','Rr','-')[match(scan(,''),c('long','short','pause'))],sep=' - ')

Здійснює введення через STDIN, перевіряє, чи відповідає вхід long, shortабо pauseзамінює відповідність на Rrrr, Rrабо -відповідно.

Потім він друкується з -прокладеними пробілами як роздільник, що відповідає бажаному виводу.


You can save 2 bytes by switching from match to %in%: scan(,'') %in% c('long','short','pause')
YCR

@YCR I don't think that'll work. a %in% b checks whether entries in the a are present in b, while match(a, b) returns the actual indices of the matches. Since we can assume that the input is valid, using %in% would just return a vector of TRUEs.
JAD

Arf, true. I have test it with c('long','short','pause').
YCR

That's because when you feed a boolean vector into [, it is interpreted as [which(bool) == TRUE], which in your example would be [c(1,2,3)], which in turn happens to give the correct output.
JAD

Instead of sep=' - ' you can use s=' - ' for 2 bytes less
Rift

4

Röda, 73 57 47 46 40 44 bytes

f&a{a~=*`s\w+|l;Rr;ong;rr;p\w+;-; ; - `/";"}

Try it online!

+4 bytes due to rule change (must use Rrrr instead of any 4 letter variant).

Previous code:

{[[split()|["Bzzz"]if[_="long"]else["Bz"]if[_1="short"]else["-"]]&" - "]}

Using Mmm and Mm is 1 byte shorter.
ATaco

@ATaco It's said in the question that "Long sounds should be 4 characters long, and short sounds should be 2 characters long".
fergusq

ATaco, please note that the criteriums have been further specified in the question.
tisaconundrum

4

C (gcc), 93 77 76 bytes

-2 bytes thanks to Scepheo!
-1 byte thanks to Cyoce!

Takes a NULL terminated **char or equivalent as an input.

f(char**a){for(;*a;*++a&&printf(" - "))printf(**a&6?**a&1?"Rr":"Rrrr":"-");}

Try it online!

Explanations:

f(char**a){
  // While the string at the current position is not NULL
  for(;*a;
    // Advances the pointer to the next string
    // Then if the current string is not NULL, prints a delimiter
    *++a&&printf(" - ")
  )
    /* 
      If the 1st char of the string is not a 'p'
        If the 1st char is not a 'l'
          Prints "Rr"
        Else
          Prints "Rrrr"
      Else:
        Prints "-"
     */
    printf(**a&6?**a&1?"Rr":"Rrrr":"-");
}

2
I think you can combine a++,*a into *++a to save two bytes, and take advantage of the vague "sound" definition to use *a instead of "Rrrr" to save another four bytes.
Scepheo

Your second suggestion is genius!
scottinet

1
Can you move part of the increment stage of the for-loop to the body instead of being comma-separated?
Cyoce

This indeed saves a byte. Good catch!
scottinet


3

Batch, 88 bytes

@set/ps=
@set s=%s: = - %
@set s=%s:long=Rrrr%
@set s=%s:short=Rr%
@echo %s:pause=-%

Takes input on STDIN. Unfortunately loop overhead costs 26 bytes so this is just boring replacements.


2
Suggested edit to remove all of the @s
Stephen

@Stephen Yes, I got the notification...
Neil

Nice! Just two things, though: I counted that answer to be 84 bytes long, not 88. Also, OP has replaced Mmmm and Mm with Rrrr and Rr, it would be nice to update your answer c:
Matheus Avellar

Batch as of what platform? I doubt MS-DOS 6.22 would do what XP does when in enhanced command mode.
TOOGAM

@TOOGAM Yeah, when I say Batch I usually mean Windows NT's CMD.EXE's version.
Neil


2

PHP, 113 bytes

<?$s=[];for($i=1;$i<$argc;$i++){$c=$argv[$i][0];$s[]=($c<'m')?'Rrrr':(($c<'q')?'-':'Rr');}echo implode(' - ',$s);

Try it online!

First attempt at code golf, so probably a lot of optimisations available!


2

Vim (52 bytes)

:s/long/Rrrr/ge|s/short/Rr/ge|s/pause/-/ge|s/ / - /genter

Can probably be made shorter...


Stringing the commands together like this stops the train if one of them errors IE if there's no pause or something in the given string, the replacements after the one that failed won't work. You can either split them on separate lines or put an e flag at the end
nmjcman101

Corrected the error. I still feel there ought to be some way to speed it up, but the only other way I thought of (after turning "pause" into a dash, s/[^ -]/r/, capitalize the first R after every space, trim four-r to two-r) came out longer.
David Heyman

1

Excel, 100 bytes

=REPLACE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"long","- Bzzz"),"short","- Bz"),"pause","- -"),1,2,"")

Per examples, Input is SPACE separated string, as is output.

Question itself does not mention a SPACE requirement, allowing for a slightly shorter 97 byte solution:

=REPLACE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"long","-Bzzz"),"short","-Bz"),"pause","--"),1,1,"")

1

AutoIt, 145 bytes

EXECUTE(STRINGREPLACE('MSGBOX(0,0,STRINGSTRIPWS(====INPUTBOX(0,0),"PAUSE",""),"LONG","Rrrr"),"SHORT","Rr")," "," - "),4))',"=","STRINGREPLACE("))

(AutoIt is really bad choice for code golf, tried my best to make it small as possible)


Welcome to the site! :)
James

1

Alice, 37 bytes

/ lRnrhR
\""orgrp-""!yi'."?-e"ySNo?@/

Try it online!

Explanation

This program makes the following substitutions:

  • l, hR
  • o, n, gr
  • p-
  • Space → Space
  • Everything else → Nothing
"longhp "!i.?eyN?"RrrrR- "y' " - "So@

"longhp "    Push this string
!            Immediately move to tape
i            Take input string
.            Duplicate
?ey          Remove all instances of the characters "longhp " from copy
N            Remove the remaining characters from the original, leaving only "longhp "
?"RrrrR- "y  Replace the characters in "longhp " with the corresponding characters in "RrrrR- "
' " - "S     Replace all spaces with " - "
o            Output
@            Terminate

1

Sed, 50 bytes

Takes input from stdin, prints to stdout

s/l\w*/Rrrr -/g
s/s\w*/Rr -/g
s/p\w*/- -/g
s/ -$//

Edit - saved 2 bytes

Sed, 40 bytes

Copying idea from Nitrodon's answer

s/[srtaue]//g
y/lhongp/RRrrr-/
s/ / - /g

Edit: saved another 2 bytes



0

Paradoc (v0.2.10), 21 bytes (CP-1252)

Wμ‹6&'r\°"-":Ãu}« rTc

Try it online!

Takes a string on the stack and results in a string on the stack. Prepend i to turn into a full program that reads from STDIN.

Uses &6 like the Pyke answer and everybody else, but joins the tokens together slightly differently, by adding a "-" token after each noise, deleting the last one, and then joining these tokens by spaces. Seems to save a byte over joining by " - ".

Explanation:

W                     .. Break into words
 μ             }      .. Map over this block:
  ‹                   .. Take the first character
   6&                 .. Binary AND with 6, to get 4, 2, or 0
     'r               .. Character "r"
       \              .. Swap top two of stack
        °             .. Replicate, to get "rrrr", "rr", or ""
         "-"          .. Push string "-"
            :         .. Duplicate on stack
             Ã        .. Compute the max...
              u       .. ... underneath the top of the stack (so, of the
                      .. second and third elements on the stack, i.e. the
                      .. string of "r"s and "-")
                      .. The mappped block ends here; we now have
                      .. something like ["rrrr", "-", "-", "-", "rr", "-"]
                «     .. Take all but the last
                  r   .. Join with spaces (this built-in's name is two
                      .. characters, the first of which is a space)
                   Tc .. Title-case

v0.2.11 will support shaving two more bytes by replacing with x and "-" with '-.



0

Ruby, 67 bytes

p ARGV[0].split(' ').map{|w|w<'m'?'Rrrr':w<'q'?'-':'Rr'}.join ' - '

This is Johan Karlsson's JavaScript solution ported to Ruby. If you like this answer, you should upvote Johan's answer.

The key idea is to compare the word strings 'short', etc. to a single character in order to distinguish between words.

| Word  | < 'm' | < 'q' | Output |
|-------|-------|-------|--------|
| short | false | false | 'Rr'   |
| long  | true  | N/A   | 'Rrrr' |
| pause | false | true  | '-'    |

Or, in alphabetical order:

  • long
  • m
  • pause
  • q
  • short

Try it online!


0

Ruby, 78 bytes

p ARGV[0].chars.map{|c|{p:'-',o:'Rr',g:'rr',' '.to_sym=>' - '}[c.to_sym]}.join

The only important parts of the input are p, o, g, and space... ignore the rest.

  • short becomes o
  • long becomes og
  • pause becomes p

Try it online!



Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.