Перекладач з англійської на чужих


18

Брифінг

Інопланетяни оселилися на землі і, як не дивно, їх алфавіт точно такий, як у нас. Їх мова також дуже схожа на нашу з деякими дуже чіткими та легкими для обчислення відмінностями.

Виклик

Візьміть рядок і виведіть еквівалент мови іноземця. Переклад працює як такий:

Поміняйте всі голосні слова на відповідні:

  Vowel |   With
--------+--------
   a    |   obo
   e    |   unu
   i    |   ini
   o    |   api
   u    |   iki

Ви також можете написати іншого перекладача для перекладу іноземця-> англійською, але це необов'язково.

Приклади

Input: Shaun
Output: Shoboikin

Input: Java
Output: Jobovobo

Input: Hello, World!
Output: Hunullapi, Wapirld!

Якщо голосна з великої літери, то ви пишете з великої літери першу букву ..

Input: Alan
Output: Obolobon

Input: Australia
Output: Oboikistroboliniobo

Правила

  • Застосовуються стандартні лазівки
  • Повинно працювати над текстом, який містить нові рядки
  • Ви можете написати функцію, лямбда або повну програму

    Capingrobotikilobotiniapins apin wrinitining thunu runuvunursunu trobonslobotapir!


Я не впевнений, що ви також можете написати іншого перекладача для перекладу Alien-> Англійська мова має означати. Чи можемо ми написати звичайний перекладач замість звичайного?
Денніс

4
Можливо, це лише я, але мені не очевидно, що і тут несе цей сенс. У всякому разі, я не впевнений, як це правило, якщо воно не є частиною фактичного завдання.
Денніс

@Dennis Ти трохи пудубонтонічний, але я відредагував це, щоб зробити його більш зрозумілим.
Шон Уайлд

2
Чому вимога до нових рядків? На мою думку, це непотрібно і нічого не додає до основної суті виклику.
Аднан

1
Чи може вхід містити будь-який символ ASCII або лише підмножину. Наприклад, чи будуть колись цифри на вході?
Райлі

Відповіді:


14

Haskell, 100 91 байт

(>>= \x->last$[x]:[y|(z:y)<-words"aobo eunu iini oapi uiki AObo EUnu IIni OApi UIki",z==x])

5
Hoboskunull точно
jk.

12

TI-Basic, 173 + 59 + 148 = 380 байт

Сподіваємось, іноземці використовують калькулятори TI-83/84;)

Основна програма, 173 байти

БОНУС: Тримайте другий чи третій рядки залежно від того, хочете ви перекладати звичайний чи зворотний перекладач.

"("+Ans+")→Str1
"@a~obo@A~Obo@e~unu@E~Unu@i~ini@I~Ini@o~api@O~Api@u~iki@U~Iki@→Str2    <-- English to Alien
"@obo~a@Obo~A@unu~e@Unu~E@ini~i@Ini~I@api~o@Api~O@iki~u@Iki~U@→Str2    <-- Alien to English
For(I,2,length(Ans
If "@"=sub(Str2,I-1,1
Then
Str1+"~"+sub(Str2,I,inString(Str2,"@",I)-I
prgmQ
Ans→Str1
End
End

Підпрограма ( prgmQ), 59 байт:

Ans→Str9
inString(Ans,"~
sub(Str9,Ans,length(Str9)-Ans+1→Str8
Str9
prgmR
Repeat Str9=Ans+Str8
Ans+Str8→Str9
prgmR
End

Підпрограма ( prgmR), 148 байт:

Ans→Str0
inString(Ans,"~→Z
inString(Str0,"~",Ans+1→Y
inString(sub(Str0,1,Z-1),sub(Str0,Z+1,Ans-Z-1→X
sub(Str0,1,-1+inString(Str0,"~
If X
sub(Str0,1,X-1)+sub(Str0,Y+1,length(Str0)-Y)+sub(Str0,X+length(sub(Str0,Z+1,Y-Z-1)),Z-X-length(sub(Str0,Z+1,Y-Z-1

PS ~представляє маркер 0x81і @являє собою маркер 0x7F, дізнайтеся більше тут .

PPS Частина чому ці програми мають високу кількість байт , так як sub(, inString(, length(, і все малі літери два байта кожен ...


Я думаю, ти один раз переплутав prgmRі prgmQв заголовках коду?
Байт-командир

Так, дякую, що зловив це @ByteCommander :)
Timtech

8

Perl, 56 байт

Включає +1 для -p

Введіть дані про STDIN

alien.pl:

#!/usr/bin/perl -p
s%\w%"`"&$&|("A\x0fboE\x15nuI\x09niO\x01piU\x09ki"=~/\u$&\K.../,$&)%eg

Працює, як показано, але замінює \xXXвтечі фактичним персонажем, щоб отримати заявлений бал


1
+1 Оголошено лише для аватара Alien. Жартую, рішення теж приємне.
Хаотичний

1
Ісус Христос .. Перл у кращих випадках, пані та панове.
Priidu Neemre

6

sed 89

s,a,&b\n,gi
s,i,&n\r,gi
s,o,&p\r,gi
s,u,&k\r,gi
s,e,&n\f,gi
y,aeouAEOU\n\r\f,ouaiOUAIoiu,

Чи працює це для введення даних, що містить нові рядки?
Йорданія

@Jordan Це робить. sed читає "по одному рядку за часом". Таким чином, він буде обробляти все до першого нового рядка, друкувати його, друкувати новий рядок, а потім починати заново, якщо буде більше тексту.
Райлі

Ах, звичайно. 👍🏻
Йорданія

@Jordan Це не було правилом, коли я писав це, але все одно закінчився.
Райлі

6

Python, 99 95 93 байт

lambda s:"".join(("ouiaiOUIAI bnnpkbnnpk ouiiiouiii"+c)["aeiouAEIOU".find(c)::11] for c in s)

На ideone.com ...

Досить просто. Просто візьміть індекс, у якому ми знаходимо кожного символу у списку голосних, і скористайтеся ним, щоб витягнути три потрібні нам символи. Якщо його не знайдено, .find()повертається, -1тому просто наклейте поточний символ на кінець рядка. Пробіли необхідні, щоб будь-яка літера "a"не включала додану c. Перекладені голосні згруповані за літерним порядком (перша буква кожного перекладу, потім друга, потім третя).


Ого, приємний творчий підхід. Я вражений :)
Байт командир

1
Ви можете видалити місце в["aeiouAEIOU".find(c)::11] for
акроліт

6

05AB1E , 28 27 20 байт

žÀ.•₅%~≠#ùÛãú•3ôD™«‡

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

Unuxplobonobotiniapin

žÀ                    # the string "aeiouAEIOU"
  .•₅%~≠#ùÛãú•        # the string "obounuiniapiiki"
              3ô      # split in pieces of 3
                D™«   # concatenate with a title-case copy
                   ‡  # transliterate

2
Ini lapivunu gapilfining!
Shaun Wild

@BasicallyAlanTuring: Займав мене занадто довго, щоб перекласти це в моїй голові. Думаю, мені потрібен зворотний перекладач: P
Емінья

2
Пройдіться, не повинно бути занадто важким: P
Shaun Wild

Страшно, я думаю, це говорить про те, що я люблю гольф.
datagod

Я змінив своє запитання, через що ви не відповідаєте. Це повинно працювати з новими рядками
Shaun Wild


5

Пітон, 129 байт

lambda s:"".join([str,str.capitalize][ord(l)<91]({"a":"obo","e":"unu","i":"ini","o":"api","u":"iki"}.get(l.lower(),l))for l in s)

Дивіться, як це працює на ideone.com

Ось більш красиво відформатована версія:

lambda s: \
    "".join(
        [str, str.capitalize][ord(l) < 91](
            {"a":"obo", "e":"unu", "i":"ini", "o":"api", "u":"iki"}
            .get(l.lower(), l)
        )
    for l in s)

Найцікавіші частини - це те, { ... }.get(l.lower(), l)що намагається шукати букву, що зберігається в lперетвореному в нижній регістр словнику, і повертає перекладену версію (якщо вона знайдена), або інша оригінальна літера,
і [str, str.capitalize][ord(l) < 91]( ... )яка перевіряє, чи був початковий лист великої літери ( Точка коду ASCII нижче 91), а потім або викликає str()функцію з буквою як аргумент (якщо це не була велика літера, нічого не робить) або str.capitalize()функцію (перетворює першу літеру рядка аргументу у верхній регістр).


5

C (gcc) , 150 141 136 134 байт

a;i;e(char*n){for(char*v=" AEIOUIAI",*t;i=*n++;printf(&a))t=index(v,i-i/96*32),a=t?t-v:0,a=a?v[a+3]|L" 潢畮楮楰楫"[a]<<8|i&32:i;}

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

На основі відповіді @algmyr та -8 завдяки @ ASCII-лише

Менш гольф-версія

a;i;
e(char*n){
  for(char*v=" AEIOUIAI",*t;i=*n++;printf(&a))
    t=index(v,i-i/96*32),
    a=t?t-v:0,
    a=a?v[a+3]|L" 潢畮楮楰楫"[a]<<8|i&32:i;
}

149? a;l;i;e(char*n){for(char*v=" AEIOU",*t;i=*n++;printf("%c%c%c"+4*!a,(a?" OUIAI"[a]:i)|i&32," bnnpk"[a]," ouiii"[t=index(v,i-32*l),a=t?t-v:0]))l=i>96;}
Лише ASCII

можливо також 149:a;l;i;e(char*n){for(char*v="AEIOU",*t;i=*n++;printf("%c%c%c"+4*!a,(a?" OUIAI"[a]:i)|i&32," bnnpk"[a]," ouiii"[t=index(v,i&95),a=t&&t-v<5?t-v+1:0]));}
ASCII,

144:a;l;i;e(char*n){for(char*v=" AEIOU",*t;i=*n++;)printf("%c%c%c"+4*!a,a?" OUIAI"[a]|i&32:i," bnnpk"[a]," ouiii"[t=index(v,i-i/96*32),a=t?t-v:0]);}
Лише ASCII лише

4

Пакетна, 215 байт

@echo off
set/pt=
set s=
:l
if "%t%"=="" echo(%s%&exit/b
set c=%t:~0,1%
for %%a in (obo.a unu.e ini.i api.o iki.u Obo.A Unu.E Ini.I Api.O Iki.U)do if .%c%==%%~xa set c=%%~na
set s=%s%%c%
set t=%t:~1%
goto l

Здійснює введення даних STDIN. Обробка символів за символом має зручність бути чутливими до регістру.


Пакет - це лише найгірший інструмент для всього, чи не так? (Ну, принаймні, ти побив TI-Basic :) Приємно бачити кодовий гольф у Batch, до речі!
YoYoYonnY

4

Pyth, 42 байти

#sXw"aeiouAEIOU"+Jc"obounuiniapiiki"3mrd3J

Програма, яка приймає вхід на STDIN і друкує вихід.

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

Як це працює

#sXw"aeiouAEIOU"+Jc"obounuiniapiiki"3mrd3J  Program.
#                                           Loop until error statement:
   w                                         Get w, the next line of the input
                   "obounuiniapiiki"         Yield string literal "obounuiniapiiki"
                  c                 3        Split that into groups of three characters
                 J                           Assign that to J and yield J
                                     mrd3J   Map title case over J
                +                            Merge the lower and title groups
    "aeiouAEIOU"                             Yield string literal "aeiouAEIOU"
  X                                          Translate w from that to the three-character
                                             groups
 s                                           Concatenate that
                                             Implicitly print

4

C, 167 байт

Я дійсно не хотів порушувати звичку завжди виконувати основні функції при кодуванні C, але це істотно коротше, ніж версія з основним, і таким чином я отримав ще один лист, щоб написати те, що я хотів!

Гольф

a;l;i;e(char*n){for(;i=*n++;l=i>90,i-=32*l,a=!(i-65)+2*!(i-69)+3*!(i-73)+4*!(i-79)+5*!(i-85),printf(a?"%c%c%c":"%c",(a?"HOUIAI"[a]:i)+l*32,"ibnnpk"[a],"!ouiii"[a]));}

Прокоментував

a;l;i;
e(char*n)
{
    for(;
        i = *n++;  /* Get char and advance */
        l = i>90,  /* Is lowercase? */
        i -= 32*l, /* Make uppercase */

        /* Is 1,2,3,4,5 depeding on the vowel and 0 for no vowel */
        a = !(i-65) + 2*!(i-69) + 3*!(i-73) + 4*!(i-79) + 5*!(i-85),

        printf(a?"%c%c%c":"%c",        /* Print 1 or 3 chars? */
               (a?"HOUIAI"[a]:i)+l*32, /* Print appropriate char+case */
                  "ibnnpk"[a],            /* Print appropriate char */
                  "!ouiii"[a]));          /* Print appropriate char */
}

Щось особливе в C, і як жахливо ви можете бути з покажчиками тощо.



@ceilingcat Я б сказав, опублікуйте свою відповідь самостійно. Це досить розходиться, щоб заслужити власну відповідь. :)
algmyr


3

Javascript (ES6), 94 93 92 байт

s=>s.replace(/[aeiou]/gi,c=>"OUIAIouiai"[n="AEIOUaeiou".search(c)]+"bnnpk"[n%=5]+"ouiii"[n])

Збережено 1 байт завдяки edc65
Збережено 1 байт завдяки Нілу

Демо

let f =
s=>s.replace(/[aeiou]/gi,c=>"OUIAIouiai"[n="AEIOUaeiou".search(c)]+"bnnpk"[n%=5]+"ouiii"[n])

function translate() {
  document.getElementById("o").value = f(document.getElementById("i").value);
}
translate();
<input id="i" size=80 oninput="translate()" value="Hello, World!"><br><input id="o" size=80 disabled>


1
Щоб перевірити значення повернення .indexOfта .searchвикористовувати ~замість<0
edc65

1
Я подивився, що станеться, якщо ви заміните лише голосні, і я спочатку отримав, s=>s.replace(/[aeiou]/gi,c=>"ouiaiOUIAI"[n="aeiouAEIOU".indexOf(c)]+"bnnpk"[n%=5]+"ouiii"[n])який досі становить 93 байти. Але оскільки cзараз відомо, що це гласна, тепер ви можете використовувати searchзамість цього, indexOfщоб зберегти байт!
Ніл

@Neil - Приємно! Я спробував і те, і інше, але не думав про їх поєднання.
Арнольд

2

Java 8, 172 байти

String f(String s){String v="AEIOUaeiou",r="OboUnuIniApiIkiobounuiniapiiki",o="";for(char c:s.toCharArray()){int n=v.indexOf(c);o+=n>-1?r.substring(n*3,n*3+3):c;}return o;}

неозорений:

String f(String s){
    String v="AEIOUaeiou",r="OboUnuIniApiIkiobounuiniapiiki",o="";
    for(char c:s.toCharArray()){
        int n=v.indexOf(c);
        o+=n>-1?r.substring(n*3,n*3+3):c;
    }
    return o;
}

І інопланетянин повертається до англійської (171 байт):

String g(String s){String[] v="AEIOUaeiou".split(""),r="Obo Unu Ini Api Iki obo unu ini api iki".split(" ");for(int i=0;i<v.length;i++)s=s.replaceAll(r[i],v[i]);return s;}

Безумовно:

String g(String s){
    String[] v="AEIOUaeiou".split(""),r="Obo Unu Ini Api Iki obo unu ini api iki".split(" ");
    for(int i=0;i<v.length;i++)s=s.replaceAll(r[i],v[i]);
    return s;
}

2

Tcl, 75 байт

Рядок для перекладу знаходиться в змінній s.

string map {A Obo a obo E Unu e unu I Ini i ini O Api o api U Iki u iki} $s

2

Математика, 128 байт

#~StringReplace~{"a"->"obo","A"->"Obo","e"->"unu","E"->"Unu","i"->"ini","I"->"Ini","o"->"api","O"->"Api","u"->"iki","U"->"Iki"}&

Не впевнений, чи можна отримати більш коротку програму, скориставшись IgnoreCase->Trueразом із перевіркою справи.


2

C 178 байт

char*p[256],*a="obo\0unu\0ini\0api\0iki\0Obo\0Unu\0Ini\0Api\0Iki",*b="aeiouAEIOU";main(c){for(c=0;b[c];++c)p[b[c]]=a+4*c;for(;(c=getchar())>0;)p[c]?printf("%s",p[c]):putchar(c);}


@ceilingcat & c може бути нормальним, якщо він збереже число як byte1 byte2 byte3 ... Наприклад, 255 в пам'яті як ff 00 00 00, але якщо є інший ендіан для 255, у нас є 00 00 00 ff і друкується рядок порожнечі ...
RosLuP


2

C #, 133 121 байт

s=>{int i;return string.Concat(s.Select(c=>(i ="AIUEOaiueo".IndexOf(c))>-1?"OboIniIkiUnuApioboiniikiunuapi".Substring(i*3,3):c+""));}

Редагувати (завдяки milk)

дякую :) Я насправді знаю це перевантаження, але якось повністю забув це, коли писав це ..

s=>string.Concat(s.Select((c,i)=>(i="AIUEOaiueo".IndexOf(c))>-1?"OboIniIkiUnuApioboiniikiunuapi".Substring(i*3,3):c+""));

Ви можете використовувати Select(char, int)перевантаження, щоб не потрібно було декларувати, iі зможете все це скласти в один рядок. s=>string.Concat(s.Select((c,i)=>(i="AIUEOaiueo".IndexOf(c))>-1?"OboIniIkiUnuApioboiniikiunuapi".Substring(i*3,3):c+""));
молоко

2

C, 207 202 байт (завдяки Cyoce)

#include <stdio.h>
#define r(c,t) case c:printf(t);continue;
int main(){int c;while(~(c=getchar())){switch(c){r('a',"obo")r('e',"unu")r('i',"ini")r('o',"api")r('u',"iki")default:putchar(c);}}return 0;}

1) Я ненавиджу пропускати тип перед будь-яким видом декларацій

2) I don't really like to put unusable code (without main() function)

Usage:

c89 cg.c -o cg; echo "Testing" | ./cg

Welcome to PPCG!
Martin Ender

@MartinEnder, that's unexpected... but thank you :)
Xdevelnet

(c=getchar())!= EOF can become ~(c=getchar())
Cyoce


1

Swift 2.2 196 bytes

¯\_(ツ)_/¯

Golfed

var r = ["a":"obo","e":"unu","i":"ini","o":"api","u":"iki"];var q={(s:String) in var o = "";for var i in s.lowercaseString.characters{o += r[String(i)] != nil ? r[String(i)]!:String(i)};print(o);}

unGolfed

var r = ["a":"obo","e":"unu","i":"ini","o":"api","u":"iki"]
var q={(s:String) in
    var o = ""
    for var i in s.lowercaseString.characters {
        o += r[String(i)] != nil ? r[String(i)]!:String(i)
    }
    print(o)
}

Are the spaces in var r = [ necessary?
Cyoce

Yeah in the playgrounds app if you don't put a space in between an assignment it give you an error and tells you to add spaces. Swift is probably one of the worst languages to golf with but I thought it would be fun to try.
Danwakeem

And it was interesting it didn't give me that error when I was assigning a variable to a closure. Hence the shrugging man
Danwakeem

yeah I noticed that too. That's why I was confused.
Cyoce

0

Perl 6,  84  82 bytes

{my%o=<a obo e unu i ini o api u iki>;S:i:g[<{%o.keys}>]=%o{$/.lc}.samecase($/~'a')}
{my%o=<a obo e unu i ini o api u iki>;S:i:g[<[aeiou]>]=%o{$/.lc}.samecase($/~'a')}

Expanded:

# bare block lambda with implicit parameter 「$_」
{
  # create the mapping
  my %v = <a obo e unu i ini o api u iki>;

  # replace vowels in 「$_」
  S
    :ignorecase
    :global
  [
    <[aeiou]>
  ]

  = # replace them with:

  %v{ $/.lc }
  # change it to be the same case as what was matched, and a lowercase letter
  .samecase( $/ ~ 'a' )
}

Usage:

my &english-to-alien = {my%o=<a obo e unu i ini o api u iki>;S:i:g[<[aeiou]>]=%o{$/.lc}.samecase($/~'a')}

say english-to-alien 'Australia'; # Oboikistroboliniobo

0

C - 192 bytes

(newlines added for clarity)

int c,j,b;main(){
char*f[]={"bo","nu","ni","pi","ki",""},
s[]={14,16,0,-14,-12};
while(c=getchar()){for(b=j=0;j<10;++j)
{if(c=="aeiouAEIOU"[j]){c+=s[j%=5];b=1;break;}}
printf("%c%s",c,f[b?j:5]);}}

Just lookup tables and a boolean switch.

Lookup each letter in table (string) of vowels; if found, then modify it according to the rule in table s. Print each character followed by a string: if a vowel was found, print the character modified by the value in s followed by the rest of the syllable stored in table f; if a vowel was not found, print the original character and an empty string.



0

Ruby, 102 93 91 88 78 bytes

gsub(/[#{b='aeiouAEIOU'}]/){'obounuiniapiikiOboUnuIniApiIki'[b.index($&)*3,3]}

Explanation:

Execute the line like ruby -pe "gsub(/[#{b='aeiouAEIOU'}]/){'obounuiniapiikiOboUnuIniApiIki'[b.index($&)*3,3]}", next up type, for example, Australia it should output: Oboikistroboliniobo.

It's pretty straightforward, replace all vowels with a substring based on the index of the to-be replaced vowel in (b), times 3 and the next 3 characters in the translation string.


1
I suspect the leading and trailing quotation marks (and internal escapes if the input has quotation marks) in the output might disqualify this. Anyway, you can save two bytes by moving the assignment of b into the Regexp (/[#{b=...}/).
Jordan

1
I think the space p $* is unnecessary
Cyoce

1
Use the -p flag to save additional bytes. ruby -pe 'gsub(/[#{b="aeiouAEIOU"}]/){"obounuiniapiikiOboUnuIniApiIki"[b.index($&)*3,3]}'
Value Ink

I count 78 + 2 (-pe). How do you get 71?
Not that Charles

@NotthatCharles do the characters needed for execution really matter in this case? I just didn't count them.
Biketire

0

TI-BASIC, 201 197 195 bytes

Ans+" →Str1:"AEIOUaeiou→Str2:"OUIAIouiai→Str3:"bonunipiki→Str4:1→X:While X<length(Str1:inString(Str2,sub(Str1,X,1→A:5fPart(.2A→B:If A:sub(Str1,1,X-1)+sub(Str3,A,1)+sub(Str4,2B-1,2)+sub(Str1,X+1,length(Str1)-X→Str1:X+1+2(A>0→X:End:sub(Str1,1,length(Str1)-1

To think that I'd find another TI-BASIC answer here!

Anyway, the input is an English string in Ans.
The output is the translated string.

Examples:

"HE
HE
prgmCDGF1A
HUnu
"Hello
Hello
prgmCDGF1A
Hunullapi

Explanation:
(Newlines added for readability. Multiple lines from the same line will be denoted with a : in the following code block.)

Ans+" →Str1                     ;append a space to the input string and store the result
                                ; in "Str1"
"AEIOUaeiou→Str2                ;store the upper- and lowercase vowels in "Str2"
"OUIAIouiai→Str3                ;store the beginning letter of each corresponding translated
                                ; vowel in "Str3"
"bonunipiki→Str4                ;store the remaining letters of each translated vowel
                                ; in "Str4"
1→X                             ;store 1 in "X"
While X<length(Str1             ;loop until all English letters have been checked
inString(Str2,sub(Str1,X,1→A    ;get the current letter and store its index in "Str2"
                                ; into "A"
5fPart(.2A→B                    ;get which translated vowel end should be used
                                ; B ranges from 1 to 5
If A                            ;if the current letter is a vowel
sub(Str1,1,X-1)                 ;extract the substring of the input before the
                                ; current letter
: +sub(Str3,A,1)                ;append the translated vowel start
: +sub(Str4,2B-1,2)             ;append the translated vowel end
: +sub(Str1,X+1,length(Str1)-X  ;append the remaining substring of the input
: →Str1                         ;store the result of these concatenations into "Str1"
X+1+2(A>0→X                     ;check if A>0 (if the current letter was a vowel)
                                ; if true, increment "X" by three
                                ; if false, increment "X" by one
End
sub(Str1,1,length(Str1)-1       ;remove the trailing space and store the result in "Ans"
                                ;implicit print of "Ans"

Notes:

  • TI-BASIC is a tokenized language. Character count does not equal byte count.

  • Lowercase letters in TI-BASIC are two bytes each.

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