Fare un acronimo


24

Obbiettivo

Il tuo obiettivo è creare un programma che converta un input nel suo acronimo. Il tuo input è garantito per avere solo lettere e spazi. L'input avrà esattamente uno spazio tra le parole. È necessario emettere l'acronimo dell'input.

Regole

  • Il tuo codice non può fare distinzione tra maiuscole e minuscole (ad esempio fooe Foosono uguali)
  • Il tuo codice deve ignorare le seguenti parole e non inserirle nell'acronimo: and or by of
  • Non puoi presumere che le parole siano tutte minuscole.
  • L'output deve essere interamente in maiuscolo, senza separazione tra i caratteri.
  • Una nuova riga finale è accettata ma non necessaria.
  • Se la lingua è un acronimo funzione built-in, è possibile che non usarlo.

Esempi

(ingressi / uscite raggruppati)

United States of America
USA

Light Amplification by Stimulation of Emitted Radiation
LASER

united states of america
USA

Jordan Of the World
JTW

punteggio

Questa è una sfida di , quindi vince il codice più corto.

Classifica

var QUESTION_ID=75448,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>


Ho aggiunto 2 casi di test.
Aplet123,

1
@ Aplet123 Sei sicuro che sia quello che vuoi? Perché in tal caso, la sfida si riduce alla rimozione di spazi e lettere minuscole. (Esempio 4 byte in Retina: T` l)
Martin Ender

4
Un po 'troppo tardi per cambiarlo, ma in genere ti aspetteresti anche di rimuovere parole come "a", "an", "the", "for", "to", ecc.
Darrel Hoffman,

2
Questo sta mettendo da parte il fatto che gli Stati Uniti non sono un acronimo, è un'abbreviazione? La NASA è un acronimo perché dici la parola "nasa". Se scrivi le lettere, non è un acronimo.
corsiKa

1
Possiamo supporre che l'input avrà sempre un output non vuoto?
Downgoat,

Risposte:


10

Pyth, 25 21 20 byte

shM-crz1dc4."@YK½¼

Provalo qui!

Grazie a @Jakube per aver salvato un byte!

Spiegazione

shM-crz1dc4. "@ YK½¼ # z = input

     rz1 # converte l'input in maiuscolo
    cd # suddivide l'input negli spazi
         c4. "@ YK½¼ # crea un elenco di parole da una stringa compressa che deve essere ignorata
   - # filtra queste parole
 hM # accetta solo la prima lettera di tutte le parole
s # li unisce in una stringa

La stringa compressa diventa ANDBYOROF


Un piccolo trucco per l'imballaggio delle stringhe: ."@YK½¼salva un byte "ANDORBYOF. È praticamente @ANDBYOROFpieno.
Jakube,

Dang, i caratteri non ascii sono stati cancellati. Fai i bagagli @ANDBYOROFe vedi cosa ottieni.
Jakube,

@Jakube Grazie! Ho provato a imballarlo prima, ma alla fine ho sempre avuto la stessa lunghezza o più a lungo.
Denker,

10

Gelatina , 21 20 byte

,“°ɲịĊs°gɗ»ṣ€⁶Œuḟ/Ḣ€

Provalo online!

(-1 grazie a @Dennis.)

,“°ɲịĊs°gɗ»              Pair input with the string "OR OF by AND"
           ṣ€⁶           Split both by spaces
              Œu         Uppercase
                ḟ/       Reduce filter (removing ignored words from input)
                  Ḣ€     Keep first letters of remaining words

Il dizionario di Jelly è un po 'strano in quanto ha ANDin maiuscolo ma byin minuscolo ...


8

Retina, 29 31 36 byte

T`l`L
 |(AND|OR|BY|OF)\b|\B.

Newline previsto alla fine.

Grazie a Martin Büttner per aver salvato 5 byte

Provalo online

T`l`L                  # Replace lowercase with uppercase
 |(AND|OR|BY|OF)\b|\B. # Regex match, it doesn't matter if we match 'AND' in SHAND
                       #   since the 'SH' will still become 'S' or am I missing something?
                       # Replace with nothing

Non ho familiarità con la retina. Cosa fa T`l`L?
Cyoce,

@Cyoce Vedi aggiornamento con spiegazione
andlrc

6

JavaScript (ES6), 56 byte

Salvataggio di un byte grazie a @ edc65.

s=>s.toUpperCase().replace(/\B.| |(AND|O[RF]|BY)\b/g,"")

Spiegazione

Il codice è autoesplicativo, spiegherò solo la regex:

\B.          // Matches any character (`.`), that's not the start of a word
|            // Matches spaces
|(...)\b     // Matches all the words that should be ignored

Ha rimosso tutti questi caratteri corrispondenti e mette in maiuscolo la parola


1
mettendo .toUpperCase () prima della regexp potresti evitare la ibandiera
edc65

@dec65 idea intelligente, grazie!
Downgoat,

Abbastanza sicuro che i genitori non siano necessari qui
Shaun H

5

JavaScript, 61 64 66 63 byte

a=>a.toUpperCase().replace(/(AND|O[FR]|BY|(\w)\w+)( |$)/g,"$2")

Utilizza un'espressione regolare per trovare le parole non presenti nell'elenco: and, or, of, bye acquisisce la prima lettera. Quindi capitalizza la stringa di lettere risultante.

EDIT: 64 byte - Risolto per le parole iniziano conof,or,by,and

EDIT: 66 byte - Risolto per controllare tutte le parole compresa l'ultima parola.

EDIT: 63 byte - 3 byte salvati grazie a @ edc65 e @Cyoce !


Non funziona perFoo Offline Bar
Downgoat,

Il consenso generale è che non è necessario assegnare la funzione a una variabile.
Cyoce,

mettendo .toUpperCase () prima della regexp potresti evitare la ibandiera
edc65

5

vim, 46

gUU:s/ /\r/g<cr>:g/\vAND|OR|OF|BY/d<cr>:%s/.\zs.*\n<cr>
gUU                      make line uppercase
:s/ /\r/g<cr>            replace all spaces with newlines
:g/\vAND|OR|OF|BY/d<cr>  remove unwanted words
:%s/.\zs.*\n<cr>         remove all non-initial characters and newlines

Mi piace particolarmente quell'ultimo pezzo. Il primo .nella regex corrisponde al primo carattere della riga. Quindi usiamo \zsper avviare la parte "attualmente sostituita", in effetti non sostituendo il carattere iniziale. .*corrisponde al resto della riga e \ncorrisponde alla nuova riga finale. Dal momento che non specifichiamo una stringa di sostituzione, vim rimuove semplicemente tutto nella corrispondenza, lasciando solo le iniziali.


vimè un linguaggio di programmazione
CousinCocaine

4

CJam, 28 24 22 byte

qeuS/"AOBONRYFD"4/z-:c

Provalo online . Grazie a Sp3000 per aver segnalato un bug e suggerito una correzione, e a Dennis per aver salvato 4 6 (!) Byte.

Spiegazione

qeuS/  e# Convert the input to uppercase and split on spaces
"AOBONRYFD"4/z  e# Push the array of short words. See more below
-      e# Remove each short word from the input words
:c     e# Cast the remaining words to characters, which is a
       e# shorter way of taking the first letter

Dennis ha suggerito questo trucco per abbreviare l'elenco delle parole: dividendo AOBONRYFDin quattro pezzi, otteniamo

AOBO
NRYF
D

Trasposizione di colonne in righe con il z operatore, otteniamo le parole giuste!


4

Julia, 72 63 61 55 byte

s->join(matchall(r"\b(?!AND|OR|OF|BY)\S",uppercase(s)))

Questa è una funzione anonima che accetta una stringa e restituisce una stringa. Per chiamarlo, assegnarlo a una variabile.

Convertiamo la stringa in uppercase, selezioniamo ogni corrispondenza dell'espressione regolare \b(?!AND|OR|OF|BY)\Scome un array ejoin in una stringa.

Risparmiato 8 byte grazie a Dennis!



3

Rubino, 45 43 byte

->s{s.upcase.scan(/\b(?!AND|OR|OF|BY)\S/)*''}

Questa è una funzione lambda che accetta una stringa e restituisce una stringa. Per chiamarlo, assegnalo a una variabile ed eseguif.call(input) .

Utilizza lo stesso approccio della mia risposta Julia , vale a dire convertire in maiuscolo, ottenere corrispondenze dell'espressione regolare\b(?!AND|OR|OF|BY)\S e unire in una stringa.

Provalo qui

2 byte salvati grazie a manatwork!


3
.join*''. A proposito, non è necessario assegnarlo a nulla per chiamarlo. Basta passare gli argomenti come pedice:->s{s.upcase.scan(/\b(?!AND|OR|OF|BY)\S/)*''}['United States of America']
manatwork

@manatwork Oh, grazie!
Alex A.

3

PHP, 92 byte

Primo tentativo di codice golf.

foreach(explode(" ",str_replace(["AND","OR","BY","OF"],"",strtoupper($s)))as$x){echo$x[0];}

La variabile $sè la frase da convertire:$s = "United States of America" .

Richiede PHP 5.4 o versioni successive per il funzionamento della sintassi di array brevi.


Solo FYI, i code-golf vengono segnati bytesse non diversamente specificato, e puoi usare solo #a all'inizio della linea per fare un colpo di testa.
cat

2
C'è un problema. L'uso di $srichiede register_globals, ma è stato rimosso da PHP dalla 5.4, quindi la risposta non può funzionare poiché è necessaria la 5.4 per la sintassi dell'array breve. È necessario ottenere la stringa di input come argomento ( $argv, un argomento di funzione o simile).
circa il

3

Coreutils Bash + GNU, 103 76 byte

for i in ${@^^};do grep -qE '\b(AND|OR|BY|OF)\b'<<<$i||echo -n ${i:0:1};done

Corri con

./codegolf.sh Light Amplification BY Stimulation of Emitted Radiationofo

con un singolo argomento citato o con più argomenti.

(Ho distorto l'ultima parola per contenere di ).


60 byte

Grazie a @manatwork.

for i in ${@^^};{ [[ $i = @(AND|OR|BY|OF) ]]||printf %c $i;}

Scusa, ma quella awktelefonata sembra orribile. Che ne dici di sostituirlo con ${@^^}?
arte

@manatwork, buon punto, non ci ho pensato ...
rexkogitans

Sembra molto meglio Ora sostituisci la grepchiamata con [[ $i = @(AND|OR|BY|OF) ]]. ;) E con ciò puoi anche rimuovere la parte “+ GNU coreutils” dall'intestazione del post.
arte

Ancora una cosa: potresti sostituire il echocon printf. Inoltre è possibile applicare Digital Trauma s' punta brace troppo. (Altro in Suggerimenti per giocare a golf a Bash .)for i in ${@^^};{ [[ $i = @(AND|OR|BY|OF) ]]||printf %c $i;}
Manatwork

Stavo cercando la notazione bash simile a grep 's \b, ma couldnot trovarlo ... E non lo sapevodo...done si può sostituire da parentesi graffe.
rexkogitans,

3

JavaScript, 104 85 byte

Risparmiato 19 byte grazie a @ Aplet123 .

Divide la stringa per spazi, quindi controlla se sono le parole di, o, e, o di. Se lo è, lo ignora, altrimenti ne prende la prima lettera. Quindi unisce l'array e rende la stringa maiuscola.

a=_=>_.split` `.map(v=>/\b(o(f|r)|and|by)\b/i.test(v)?"":v[0]).join("").toUpperCase()

Ungolfed:

function a(_) {
       _ = _.split` `; //Split on spaces
       _ = _.map(function(v){return new RegExp("\b(o(f|r)|and|by)\b","i").test(v)}); //Check if the banned words are in the result
       _ = _.join(""); //Join it into a string
       _ = _.toUpperCase(); //Convert it to uppercase
};

Perché c'è un backtick alla fine? Causa un errore e non è destinato a essere lì. Probabilmente dovresti rimuovere il backtick.
Aplet123,

Inoltre, non è necessario var. Non ci preoccupiamo di inquinare l'ambito globale nel codice golf: P
NinjaBearMonkey

Non funziona. Se si guardano gli esempi, l'input `stati uniti d'
america`

Sì, l'ho notato. Stupidi nomi di funzioni incorporate super lunghi.
clamchowder314

È possibile impostare Z _.map(v=>/o(f|r)|and|by/.test(v)?"":v[0]) invece di "". Puoi rimuovere la _.forEach(p=>Z+=p[0].toUpperCase());linea e sostituirla return Zcon return Z.join("").toUpperCase()
Aplet123

3

MATL , 34 27 byte

1 byte in meno grazie a @AandN

KkYb'OF AND OR BY'YbX-c1Z)!

Provalo online!

Xk                  % convert to uppercase
Yb                  % split by spaces. Gives a cell array of input words
'AND OR BY OF'      % ignored words separated by spaces
Yb                  % split by spaces. Gives a cell array of ignored words
X-                  % setdiff: remove ignored words (result is stable)
c                   % convert to 2D char array, padding words with spaces
1Z)                 % take first column
!                   % transpose into a row

1
Forse funziona con 33 byte? XkYb{'OF' 'AND' 'OR' 'BY'}X-c1Z)!
Adnan,

2

05AB1E , 33 32 28 byte

Codice:

‘€ƒ€—€‚€‹‘ð¡)Uuð¡)vXyQO>iy¬?

Utilizza la codifica CP-1252 .


2

Python, 81 byte

lambda s:''.join(c[0]for c in s.upper().split()if c not in'AND OF OR BY'.split())

2

Haskell, 100 99 98 82 75 byte

Sono abbastanza sicuro che può essere abbreviato molto di più mentre faccio ancora schifo nell'uso $, .ecc. Quindi continuo ad usarlo() insted =)

Grazie @nimi per il tuo aiuto magico!

import Data.Char
w=words
x=[h!!0|h<-w$toUpper<$>x,notElem h$w"OF BY OR AND"]

Esempio:

*Main> a "united states by america"
"USA"

Oh, quell'operatore di .composizione sembra abbastanza intuitivo. Non sono mai sicuro di ciò che viene valutato in quale ordine.
flawr

capitolo 6 di Learn you a Haskell for Great Good! ha una buona introduzione al funzionamento dell'applicazione $e alla composizione con. .
nimi,

1
Ritornando alla non-pointfree e una lista di comprensione è ancora più breve: a x=[h!!0|h<-w$toUpper<$>x,notElem h$w"OF BY OR AND"].
nimi,

Now this is definitely over my head, I'm going to have to learn quicker=)
flawr

2

Python, 103 96 bytes

This is my first attempt at code golf, and this could probably be golfed a lot more. Thanks to DenkerAffe for saving seven characters.

lambda x:"".join([x[0]for y in x.split(" ") if y.lower() not in ['and','or','of','by']]).upper()

It takes the input, turns it into a list of words and takes their first letter if it's not one of the forbidden words, then turns everything to uppercase.


2
It was trying to execute the input. In Python 3 that doesn't happen. (I think it saves 2 bytes to switch to Python 3 (-4 for input vs raw_input, +2 for print("".join..) vs print"".join..) Also no space between a symbol and a keyword.
CalculatorFeline

Or you just go with a lambda which gets the input as argument. This is always allowed here if the challenge doesn't forbid it explicitly.
Denker

@CatsAreFluffy It might help to switch to Python 3, but I highly prefer Python 2 over it because who likes parentheses anyways?
mriklojn

You can save the lower() when you uppercase the input first, before you do anything. Your filter list then becomes ['AND','OR',...]., but the rest would stay the same. You can also drop some whitespaces behind braces. x[0]for ... is completly valid in Python.
Denker

Remove spaces between symbols and keywords(it works)
CalculatorFeline

2

JavaScript, 80 72 55 53 bytes

Code

function a(t){t=t.toUpperCase();t=t.replace(/AND|OR|BY|OF|\B.| |/g,"");return t}

function a(t){return t.toUpperCase().replace(/AND|OR|BY|OF|\B.| |/g,"")}

I just read about arrow functions and realized I could shorten this up even more.

a=t=>t.toUpperCase().replace(/AND|OR|BY|OF|\B.| |/g,"")

According to this, you don't count the assignment in the length, so -2 bytes.

t=>t.toUpperCase().replace(/AND|OR|BY|OF|\B.| |/g,"")

This is my first golf, so it's not very good.


2

PHP, 68 61 58 bytes

Uses ISO-8859-1 encoding.

for(;$w=$argv[++$x];)stripos(_AND_OR_BY_OF,$w)||print$w&ß;

Run like this (-d added for aesthetics only):

php -d error_reporting=30709 -r 'for(;$w=$argv[++$x];)stripos(_AND_OR_BY_OF,$w)||print$w&ß; echo"\n";' united states oF america

Ungolfed:

// Iterate over the CLI arguments (words).
for(;$w = $argv[++$x];)
    // Check if the word is one of the excluded words by substring index.
    // The check is case insensitive.
    stripos("_AND_OR_BY_OF", $w) ||
        // Print the word, converting to uppercase and getting only the
        // first char by using bitwise AND.
        print $w & "ß";
  • Saved 7 bytes by using bitwise AND instead of using ucwords.
  • Saved 3 bytes by using ISO-8859-1 encoding and using ß (binary 11011111) for binary AND instead of a negated space (binary 00100000).

1

Mathematica, 132 117 bytes

ToUpperCase[First/@Characters@DeleteCases[StringDelete[StringSplit@#,"of"|"and"|"or"|"by",IgnoreCase->True],""]<>""]&

15 bytes saved thanks to @CatsAreFluffy.


1arg StringSplit defaults to splitting on whitespace (-5bytes)
CalculatorFeline

1
Also you can replace the word list with "of"|"and"|"or"|"by". Also {"a","b","c"}<>""==StringJoin[{"a","b","c"}]. One last thing: Characters automatically maps over lists.
CalculatorFeline

1
The leaderboard would prefer that you put a comma after Mathematica. Also you're welcome :)
CalculatorFeline

1

PowerShell, 81 Bytes

(-join($args[0].Split(" ")|?{$_-notmatch"^(and|or|by|of)$"}|%{$_[0]})).ToUpper()

Explanation

Split on the spaces creating an array. Drop the offending members. Pull the first character and join together. Use ToUpper() on the resulting string.


Realized that would match Anderson and drop it. Added 4 bytes
Matt

1

Lua, 122 Bytes

I would have love to use a pattern to get rid of the banned words, but sadly, lua isn't made to match groups of characters... So I had to use a for loop instead, which is much more expensive.

s=arg[1]for k,v in next,{"of","and","by","or"}do
s=s:gsub(v,"")end
print(s:gsub("(%a)%a+",string.upper):gsub("%s","").."")

Ungolfed

s=arg[1]                               -- initialise s with the argument
for k,v in next,{"of","and","by","or"} -- iterate over the array of banned words
do
    s=s:gsub(v,"")                     -- replace the occurences of v by 
end                                    --   an empty string
print(s:gsub("(%a)%a+",                -- replace words (separated by spaces)
              string.upper)            -- by their first letter capitalised
         :gsub("%s","")                -- replace spaces with empty strings
                       .."")           -- concatenate to prevent the number of 
                                       -- substitutions to be shown

Hey! I also made a Lua submission, here: codegolf.stackexchange.com/a/75616/33183.
Trebuchette

1

Factor, 175 bytes

I learned a lot by writing this.

USING: strings ascii sets splitting kernel sequences math.ranges ;
>lower " " split [ { "and" "or" "by" "of" } in? not ] filter [ first dup [a,b] >string ] map "" join >upper 

As a word:

USING: strings ascii sets splitting kernel sequences math.ranges ;

: >initialism ( str -- str )
  >lower " " split                            ! string.lower.split(" ")
  [ { "and" "or" "by" "of" } in? not ] filter ! word in { } ?
  [ first dup [a,b] >string ]          map    ! word[0]
  "" join >upper ;                            ! "".join.upper

Unit tests:

USING: tools.test mk-initialism ;
IN: mk-initialism.tests

{ "LASER" } [ "Light Amplification by Stimulation of Emitted Radiation" >initialism ] unit-test
{ "USA"   } [ "United States OF Americaof" >initialism ]                              unit-test
{ "USA"   } [ "united states and america" >initialism ]                               unit-test
{ "JTW"   } [ "Jordan Of the World" >initialism ]                                     unit-test

Pass!


1

Lua, 113 112 93 bytes

arg[1]:upper():gsub("%w+",function(w)io.write(("AND OR BY OF"):find(w)and""or w:sub(0,1))end)

Wow, totally forgot the existence of %w! That's a great one!
Katenkyo

Katenkyo: Well, this would also work with %a; %a matches letters, and %w matches letters and numbers. The main thing is using a custom function in gsub.
Trebuchette

Yeah, I see that it is easier to remove AND OR BY OF when selecting words... I used no custom function because they cost a lot, so I though gsub("(%a)%a+",string.upper) after removing them would have been better
Katenkyo

1

C#, 134 bytes

Golfed

class P{static void Main(string[] a){foreach (var s in a){if(!"AND OR BY OF".Contains(s.ToUpper())){Console.Write(s.ToUpper()[0]);}}}}

Readable

class P
{
    static void Main(string[] a)
    {
        foreach (var s in a)
        {
            if (!"AND OR BY OF".Contains(s.ToUpper()))
            {
                Console.Write(s.ToUpper()[0]);
            }
        }
    }
}

Execute from command line

75448.exe Light Amplification by Stimulation of Emitted Radiation

LASER

75448.exe united states of america

USA


0

IPOS - non competing, 27 bytes

uS`"AND|OR|BY|OF"ER`%S!h%S-

This works in the current version (v0.2) of the interpreter.

Example run

python IPOS.py -i "United States of America" uS`\"AND|OR|BY|OF\"ER`%S!h%S-
USA

The backslashes there are only for escaping of the quotes and are not needed for the program.

Explanation

u                  # Make the input uppercase
S                  # Push a space to the stack
`"AND|OR|BY|OF"ER` # Push a command to the stack, that replaces matches of the regex
                   # with an empty string
%                  # Split the uppercased input string on spaces, apply the command and
                   # join back on spaces. This removes the required words from the input.
S                  # Push a space to the stack
!h                 # Push a command that only selects the first character of a string
%                  # Split on spaces, apply the command and join back on spaces
S-                 # Remove the remaining spaces (forgot to make this usuable
                   # with regexes, would have saved me some bytes here :( )

0

bash / GNU coreutils, 60 bytes

sed -e's/\b'{and,o[rf],by}'\W*//Ig' -re's/(\w)\S* ?/\u\1/g'


0

Pylongolf2, 14 bytes (UTF-8)

c| l1╨3♀~

Pylongolf2 has many non-ASCII characters that count as 2 bytes.

c| l1╨3♀~
c         read input
 |        split by space (note the space after |)
   l1     substring(0, 1)
     ╨3   convert to uppercase
       ♀~ pop the array into the stack and print it.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.