Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Objective

Your goal is to make a program that converts an input to its acronym. Your input is guaranteed to have only letters and spaces. The input will have exactly one space between words. You must output the acronym of the input.

Rules

  • Your code cannot be case-sensitive(e.g. foo and Foo are the same)
  • Your code must ignore the following words and not put them in the acronym: and or by of
  • You cannot assume that the words are all lowercase.
  • The output must be entirely capitalised, with no separation between characters.
  • A trailing newline is accepted but not necessary.
  • If your language has an acronym function builtin, you may not use it.

Examples

(inputs/outputs grouped)

United States of America
USA

Light Amplification by Stimulation of Emitted Radiation
LASER

united states of america
USA

Jordan Of the World
JTW

Scoring

This is a challenge so the shortest code wins.

Leaderboard

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>

share|improve this question
    
I have added 2 test cases. – Aplet123 Mar 13 at 12:05
1  
@Aplet123 Are you sure that's what you want? Because if that's the case, the challenge boils down to removing spaces and lower case letters. (E.g. 4 bytes in Retina: T` l) – Martin Ender Mar 13 at 12:17
4  
Bit too late to change it, but you'd generally also expect words like "a", "an", "the", "for", "to", etc. to be removed. – Darrel Hoffman Mar 13 at 14:58
2  
This is setting aside the fact that USA is not an acronym, it's an abbreviation? NASA is an acronym because you say the word "nasa". If you spell out the letters, it isn't an acronym. – corsiKa Mar 13 at 17:25
1  
Can we assume the input will always have a non-empty output? – Downgoat Mar 13 at 17:34

29 Answers 29

up vote 9 down vote accepted

Pyth, 25 21 20 bytes

shM-crz1dc4."@YK½¼

Try it here!

Thanks to @Jakube for saving one byte!

Explanation

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

     rz1               # convert input to uppercase
    c   d              # split input on spaces
         c4."@YK½¼     # create a list of the words from a packed string which shall be ignored
   -                   # filter those words out
 hM                    # only take the first letter of all words
s                      # join them into one string

The packed string becomes ANDBYOROF

share|improve this answer
    
A little string packing trick: ."@YK½¼ saves one byte over "ANDORBYOF. It's basically @ANDBYOROF packed. – Jakube Mar 13 at 14:05
    
Dang, the non-ascii-chars got deleted. Just pack @ANDBYOROF and see what you get. – Jakube Mar 13 at 14:07
    
@Jakube Thanks! Tried to pack it before, but always ended up with the same length or longer. – DenkerAffe Mar 13 at 14:26

Jelly, 21 20 bytes

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

Try it online!

(-1 thanks to @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

Jelly's dictionary is a bit weird in that it has AND in uppercase yet by in lowercase...

share|improve this answer

Retina, 29 31 36 bytes

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

Intended newline at the end.

Thanks to Martin Büttner for saving 5 bytes

Try it 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
share|improve this answer
    
I'm unfamiliar with retina. What does T`l`L do? – Cyoce Mar 14 at 6:59
    
@Cyoce See update with explanation – andlrc Mar 14 at 12:58

JavaScript, 61 64 66 63 bytes

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

It uses a Regular Expression to find get words that aren't from the list: and, or, of, by, and captures the first letter. It then capitalizes the resulting string of letters.

EDIT: 64 Bytes - Fixed for words start with of,or,by,and

EDIT: 66 Bytes - Fixed to check all words including last word.

EDIT: 63 Bytes - Saved 3 Bytes thanks to @edc65 and @Cyoce!

share|improve this answer
    
Doesn't work for Foo Offline Bar – Downgoat Mar 13 at 17:27
    
@Downgoat Thanks, fixed. – Joseph Didion Mar 13 at 17:34
    
General consensus is you don't need to assign the function to a variable. – Cyoce Mar 14 at 6:17
    
putting .toUpperCase() before the regexp you could avoid the i flag – edc65 Mar 14 at 7:44

JavaScript (ES6), 56 bytes

Saved a byte thanks to @edc65.

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

Explanation

The code is self explanatory, I'll just explain the regex:

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

It removed all of these matched characers and uppercases the word

share|improve this answer
1  
putting .toUpperCase() before the regexp you could avoid the i flag – edc65 Mar 14 at 7:44
    
@edc65 smart idea, thanks! – Downgoat Mar 15 at 0:21
    
Pretty sure the parens are not needed here – Shaun H Mar 15 at 20:29

CJam, 28 24 22 bytes

qeuS/"AOBONRYFD"4/z-:c

Try it online. Thanks to Sp3000 for pointing out a bug and suggesting a fix, and to Dennis for saving 4 6(!) bytes.

Explanation

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 suggested this trick for shortening the word list: Splitting AOBONRYFD into chunks of four, we get

AOBO
NRYF
D

Transposing columns into rows with the z operator, we get the proper words!

share|improve this answer

Perl, 32 bytes

say uc=~/\b(?!AND|OR|OF|BY)\S/g

+1 byte for the -n flag.

Algorithm stolen from @AlexA's Julia answer.

share|improve this answer

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

I particularly like that last bit. The first . in the regex matches the first character of the line. Then we use \zs to start the "actually-being-replaced" part, effectively not replacing the initial character. .* matches the rest of the line, and \n matches the trailing newline. Since we don't specify a replace string, vim simply removes everything in the match, leaving only initials.

share|improve this answer
    
vim is a programming language – CousinCocaine Mar 23 at 20:36

Julia, 72 63 61 55 bytes

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

This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.

We convert the string to uppercase, select each match of the regular expression \b(?!AND|OR|OF|BY)\S as an array, and join it into a string.

Saved 8 bytes thanks to Dennis!

share|improve this answer

Ruby, 45 43 bytes

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

This is a lambda function that accepts a string and returns a string. To call it, assign it to a variable and do f.call(input).

It uses the same approach as my Julia answer, namely convert to uppercase, get matches of the regular expression \b(?!AND|OR|OF|BY)\S, and join into a string.

Try it here

Saved 2 bytes thanks to manatwork!

share|improve this answer
3  
.join*''. By the way, no need to assign it to anything to call it. Just pass it the arguments as subscript: ->s{s.upcase.scan(/\b(?!AND|OR|OF|BY)\S/)*''}['United States of America'] – manatwork Mar 13 at 16:37
    
@manatwork Oh nice, thanks! – Alex A. Mar 13 at 17:13

PHP, 92 bytes

First attempt at code golf.

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

The variable $s is the phrase to be converted: $s = "United States of America".

Requires PHP 5.4 or above for short array syntax to work.

share|improve this answer
    
Just FYI, code-golfs are scored in bytes unless otherwise noted, and you can use just a # at the beginning of the line to make a header. – cat Mar 15 at 0:19
2  
There's a problem. Using $s requires register_globals, but that has been removed from PHP since 5.4, so your answer cannot work as you require 5.4 for short array syntax. You need to get the input string as an argument ($argv, a function argument or similar). – aross Mar 15 at 14:52

Bash + GNU coreutils, 103 76 bytes

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

Run with

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

either with single argument quoted or with multiple arguments.

(I distorted the last word to contain of).


60 bytes

Thanks to @manatwork.

for i in ${@^^};{ [[ $i = @(AND|OR|BY|OF) ]]||printf %c $i;}
share|improve this answer
    
Sorry, but that awk call looks horrible. What about replacing it with ${@^^}? – manatwork Mar 15 at 11:29
    
@manatwork, good point, didnot think of that... – rexkogitans Mar 15 at 11:36
    
Looks much better. Now please replace the grep call with [[ $i = @(AND|OR|BY|OF) ]]. ;) And with that you can also remove the “ + GNU coreutils” part from the post header. – manatwork Mar 15 at 11:37
    
One more thing: you could replace the echo with printf. Furthermore you can apply Digital Trauma's brace tip too. (More in Tips for golfing in Bash.) for i in ${@^^};{ [[ $i = @(AND|OR|BY|OF) ]]||printf %c $i;} – manatwork Mar 15 at 11:45
    
I was looking for the bash notation similar to grep's \b but couldnot find it... And I did not know that do...done can be replace by curly braces. – rexkogitans Mar 15 at 12:01

JavaScript, 104 85 bytes

Saved 19 bytes thanks to @Aplet123.

Splits the string by spaces then checks if it is the words of, or, and, or by. If it is, it ignores it, otherwise it takes the first letter of it. It then joins the array and makes the string uppercase.

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
};
share|improve this answer
    
Thanks for the help! – clamchowder314 Mar 13 at 14:52
    
Why is there a backtick at the end? It causes an error and is not intended to be there. You should probably remove the backtick. – Aplet123 Mar 13 at 15:20
    
Also, you don't need var. We don't worry about polluting the global scope in code golf :P – NinjaBearMonkey Mar 13 at 15:24
    
It does not work. If you look at the examples the input ` united states of america ` it gives the output ` usa ` not ` USA ` – Aplet123 Mar 13 at 15:27
    
Yeah, I noticed that. Stupid super long built-in function names. – clamchowder314 Mar 13 at 15:30

MATL, 34 27 bytes

1 byte fewer thanks to @AandN

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

Try it 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
share|improve this answer
1  
Maybe this works with 33 bytes? XkYb{'OF' 'AND' 'OR' 'BY'}X-c1Z)! – Adnan Mar 13 at 12:35
    
@AandN Good idea! Thanks! – Luis Mendo Mar 13 at 12:36

05AB1E, 33 32 28 bytes

Code:

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

Uses CP-1252 encoding.

share|improve this answer

Haskell, 100 99 98 82 75 bytes

I am quite sure it can be shortened a lot more as I still suck at using $,. etc. so I keep using () insted=)

Thanks @nimi for your help magic!

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

Example:

*Main> a "united states by america"
"USA"
share|improve this answer
    
Oh, that . composition operator looks quite intuitive. I am just never sure what is evaluated in what order. – flawr Mar 13 at 19:34
    
chapter 6 of Learn you a Haskell for Great Good! has a good introduction to function application with $ and composition with .. – nimi Mar 13 at 21:07
1  
Switching back to non-pointfree and a list comprehension is even shorter: a x=[h!!0|h<-w$toUpper<$>x,notElem h$w"OF BY OR AND"]. – nimi Mar 13 at 22:06
    
Now this is definitely over my head, I'm going to have to learn quicker=) – flawr Mar 15 at 9:55

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.

share|improve this answer
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 Mar 13 at 19:03
    
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. – DenkerAffe Mar 14 at 3:39
    
@CatsAreFluffy It might help to switch to Python 3, but I highly prefer Python 2 over it because who likes parentheses anyways? – AbbKazPow Mar 14 at 20:59
    
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. – DenkerAffe Mar 14 at 23:20
    
Remove spaces between symbols and keywords(it works) – CalculatorFeline Apr 2 at 18:55

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.

share|improve this answer

Mathematica, 132 117 bytes

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

15 bytes saved thanks to @CatsAreFluffy.

share|improve this answer
    
1arg StringSplit defaults to splitting on whitespace (-5bytes) – CalculatorFeline Mar 13 at 16:07
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 Mar 13 at 16:11
    
@CatsAreFluffy thanks :) – martin Mar 13 at 16:19
1  
The leaderboard would prefer that you put a comma after Mathematica. Also you're welcome :) – CalculatorFeline Mar 13 at 16:20

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.

share|improve this answer
    
Realized that would match Anderson and drop it. Added 4 bytes – Matt Mar 14 at 1:50

Python, 81 bytes

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

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
share|improve this answer
    
Hey! I also made a Lua submission, here: codegolf.stackexchange.com/a/75616/33183. – Trebuchette Mar 16 at 4:17

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!

share|improve this answer

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)
share|improve this answer
    
Wow, totally forgot the existence of %w! That's a great one! – Katenkyo Mar 16 at 7:37
    
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 Mar 16 at 17:02
    
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 Mar 17 at 7:22

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

share|improve this answer

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.
    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).
share|improve this answer

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 :( )
share|improve this answer

bash / GNU coreutils, 60 bytes

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

share|improve this answer

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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.